diff --git a/.agents/sources-of-truth.md b/.agents/sources-of-truth.md index c17a1be..4c5ef45 100644 --- a/.agents/sources-of-truth.md +++ b/.agents/sources-of-truth.md @@ -3,12 +3,13 @@ Use the source that owns the fact being discussed. Read the relevant source before changing a dependent document or generated artifact. - The user's request sets the authorized task scope and product choices for that task. +- When present, the root PRD.md defines product requirements, delivery stages, and acceptance criteria. It is a self-contained specification, not an implementation status report. - Source code shows behavior that exists in this checkout. A passing test gives evidence only for the behavior it exercises. -- api/core/openapi.yml and api/ml/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output. +- api/core/openapi.yml, api/ml/openapi.yml, api/runner/openapi.yml, and api/labd/openapi.yml, with their referenced source files, define the public and internal HTTP contracts. Bundles and generated clients are derived output. - Backend migrations define the database schema. sqlc query files define queries that sqlc generates. -- Makefiles and checked-in tool configuration define supported project commands and options. Lockfiles preserve selected application dependency versions. Toolchain declarations define runtime versions; the Go backend uses exact version 1.26.8. Compose and Dockerfiles define image references, including intentionally moving `latest` or `alpine` tags. +- Makefiles and checked-in tool configuration define supported project commands and options. Lockfiles preserve selected application dependency versions. Toolchain declarations define runtime versions; the Go backend uses exact version 1.26.9. Compose and Dockerfiles define image references, including intentionally moving `latest` or `alpine` tags. - Compose, Nginx, and observability configuration define the local deployment scaffold. They do not prove that a remote deployment or production security review occurred. -- docs/ru/ARCHITECTURE.md records product and architecture decisions. docs/en/ARCHITECTURE.md is its maintained English counterpart. These documents include planned behavior and must label it as planned. +- docs/ru/ARCHITECTURE.md explains the architecture and current service boundaries. docs/en/ARCHITECTURE.md is its maintained English counterpart. Any planned behavior must be labeled as planned. - README.md is the primary Russian entry point; README.en.md is its maintained English counterpart. Neither replaces service guides or contracts. When sources disagree, do not resolve the conflict by file age alone. State what the code currently does, what the design asks for, and which source needs correction. Ask for a decision only when the conflict blocks work within the authorized scope. diff --git a/.agents/standards/backend.md b/.agents/standards/backend.md index eed1ea2..9e77597 100644 --- a/.agents/standards/backend.md +++ b/.agents/standards/backend.md @@ -27,8 +27,8 @@ Use PostgreSQL through the repository's pgx and sqlc boundary. Schema changes ar Prefer the selected wahrwelt-kit packages only where they provide a useful technical boundary and have a pinned, verified version. Libraries such as logging, HTTP, metrics, and PostgreSQL helpers do not own product behavior. Do not add unused JWT, WebSocket, or other framework dependencies. -Redis belongs behind the outbound cache port and its secondary adapter. Bootstrap owns its client lifecycle. Redis, PostgreSQL, and the SeaweedFS bucket are required for readiness. Set cache entries with a positive TTL; future product consumers must tolerate misses, eviction, and restart. Do not treat cache entries as authoritative product records or add product caching without defining ownership and invalidation. +Redis belongs behind the outbound cache port and its secondary adapter. Bootstrap owns its client lifecycle. Redis, PostgreSQL, and the SeaweedFS bucket are required for readiness. Set cache entries with a positive TTL; consumers must tolerate misses, eviction, and restart. Do not treat cache entries as authoritative product records or add product caching without defining ownership and invalidation. SeaweedFS belongs behind the outbound ObjectStorage port and the seaweedfs secondary adapter. Keep AWS SDK and S3 types inside that adapter. Bootstrap owns client resources; HeadBucket checks readiness without creating the bucket. Stream object content and close Get response bodies. Product upload/download authorization, content limits, and retention rules must be defined before exposing file operations. -Current code is an operational scaffold. Do not describe the health handler, database ping, or wiring as account, assessment, matching, or invitation behavior. +Describe implemented behavior from the current usecases, routes, and tests. Health checks and dependency wiring alone do not establish a working product flow. diff --git a/.agents/standards/contracts.md b/.agents/standards/contracts.md index 33f3db0..15beea3 100644 --- a/.agents/standards/contracts.md +++ b/.agents/standards/contracts.md @@ -4,10 +4,12 @@ The repository has separate public and internal OpenAPI contracts: - api/core/openapi.yml describes browser-to-Go operations. - api/ml/openapi.yml describes internal Go-to-ML operations. +- api/runner/openapi.yml describes internal operations between Go and the code runner. +- api/labd/openapi.yml describes internal lab provisioner operations. -Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint both specifications. Do not hand-edit bundled files. +Edit the split source files referenced by these roots. Use the API Makefile to merge schemas, bundle, and lint every specification. Do not hand-edit bundled files. -The selected Go server generator is ogen. The generated Go handler is mounted under chi. Orval generates the TypeScript client and related frontend artifacts. The Go ML client is configured in backend/codegen/ogen-ml.yml and generated into backend/internal/adapter/secondary/ml/api/. datamodel-code-generator uses ml/codegen/pyproject.toml to generate Pydantic v2 models in ml/src/lincodex_ml/api/models.py from the ML bundle. There are three code generation unit directories: backend/codegen/, frontend/codegen/, and ml/codegen/. Each consumer owns the configuration for its generated code; contract sources remain shared under api/. +ogen generates Go servers and clients; chi mounts the backend HTTP handler. Orval generates frontend clients, hooks, schemas, and mocks. datamodel-code-generator generates ML Pydantic v2 models. Each consumer keeps configuration in its own codegen/ directory: backend, frontend, ml, runner, or labd. Backend client settings are ogen-ml.yml, ogen-code-runner.yml, and ogen-labd.yml; their output stays in the corresponding secondary adapter's api/ directory. Contract sources remain shared under api/. OpenAPI 3.2.0 is the target contract version. Verify only the feature subset used by this repository through the pinned bundler, linter, ogen, Go runtime path, Orval, Python Pydantic models, and documentation pipeline. A passing fixture does not establish full support for every OpenAPI 3.2 feature. Record the exact checks run. diff --git a/.agents/standards/database.md b/.agents/standards/database.md index 0e2a8cc..4ea7974 100644 --- a/.agents/standards/database.md +++ b/.agents/standards/database.md @@ -1,6 +1,6 @@ # Database standard -PostgreSQL is the planned system of record for product data and future background jobs. The current schema contains only what the technical scaffold needs. +PostgreSQL is the system of record for product data and durable jobs. Use the migrations and queries to establish the current schema. Put schema changes in ordered backend/db/migrations/ files and queries in backend/db/queries/. sqlc output is derived. Never edit generated SQL models or query code by hand. diff --git a/.agents/standards/frontend.md b/.agents/standards/frontend.md index 2494630..58f9714 100644 --- a/.agents/standards/frontend.md +++ b/.agents/standards/frontend.md @@ -4,12 +4,14 @@ The frontend is a React single-page application built with Vite, TypeScript, and When changing the frontend toolchain or dependencies, select current stable releases and commit the matching runtime declarations, package manifest, and lockfile updates. Do not add prereleases unless the task explicitly calls for them. Keep the lockfile so installs remain repeatable after selecting the stable release. -Use FSD boundaries when product features are added: app composes pages, widgets, features, entities, and shared code. Higher layers can import lower layers; shared code must not depend on product entities. Keep transport DTOs separate from UI models. +Use FSD boundaries: app composes pages, widgets, features, entities, and shared code. Higher layers can import lower layers; shared code must not depend on product entities. Keep transport DTOs separate from UI models. Use the generated Orval client as the contract-derived transport surface. Put shared fetch behavior in the existing API client. Do not hand-edit generated files. Keep the API prefix in one layer so it is not duplicated. Model server data in the selected query library and form drafts in form state. Avoid adding a second store for data already owned by the server cache. Show loading, empty, error, retry, and forbidden states as product flows are implemented. -MSW fixtures are test inputs. They do not prove that a backend workflow exists. The current page is a minimal status view; do not document full candidate or employer interfaces as implemented. +MSW fixtures are test inputs, not evidence of a backend workflow. Check current route and feature implementations before describing a screen as available. Protected cabinet routes restore the server session through SessionGate. /status checks API liveness, not product readiness. + +Vitest runs in the Node environment without a DOM. Component and route tests check rendered markup and query behavior. Use the existing Playwright suite through make -C deploy test-e2e for browser interactions against an isolated local stack; inspect its selected scenarios and skips before claiming coverage. All source comments are in English. User-facing interface copy can be localized. diff --git a/.agents/standards/infrastructure.md b/.agents/standards/infrastructure.md index 6095c14..9db77f9 100644 --- a/.agents/standards/infrastructure.md +++ b/.agents/standards/infrastructure.md @@ -1,17 +1,19 @@ # Infrastructure standard -The local scaffold uses three independent Compose projects: core application, ML, and monitoring. Starting the core project does not start monitoring or ML. +Core application, ML, and monitoring use separate Compose projects. Start core first: ML and monitoring join its network. Starting core does not start either project. The code runner and LXD lab provisioner have separate host setup under deploy/labs/. The runner development container uses deploy/docker/docker-compose.runner.dev.yml. -Upstream container images use the requested moving `latest` or `alpine` tags where the image publishes them. These tags can change; read the current Compose and Dockerfile references instead of recording an old component version. Keep Go at exact version 1.26.8 in `go.mod`, toolchain declarations, and the backend build image. Application dependency lockfiles remain checked in and should not be removed when image tags float. +Upstream container images use the requested moving `latest` or `alpine` tags where the image publishes them. These tags can change; read the current Compose and Dockerfile references instead of recording an old component version. Keep Go at exact version 1.26.9 in `go.mod`, toolchain declarations, and the backend build image. Application dependency lockfiles remain checked in and should not be removed when image tags float. The core frontend container serves static assets with Nginx and proxies /api to Go. The default host binding is loopback at port 8080. This scaffold does not terminate production TLS. Grafana is also bound to loopback at port 3000. -The ML Compose file binds to 127.0.0.1:8000 by default. A remote ML host needs an explicit private bind address, restricted firewall rules, and a deliberate scrape target. Leave ML_METRICS_TARGET empty when Prometheus must not scrape a remote ML host. +The ML Compose file binds to 127.0.0.1:8000 by default and requires a shared ML_SERVICE_TOKEN. A remote ML host needs an explicit private bind address and restricted firewall rules. Leave ML_METRICS_TARGET empty when no ML scrape is configured; a nonempty target also needs bearer authentication in Prometheus because ML protects /metrics. -Start the core project before monitoring because monitoring joins its Docker network. The monitoring Compose project collects only the explicitly configured core services. Do not expose PostgreSQL, Redis, SeaweedFS, backend metrics, Prometheus, Loki, exporters, or the Docker socket proxy publicly. +Start the core project before monitoring because monitoring joins its Docker network. The monitoring Compose project collects only the explicitly configured core services. Do not expose PostgreSQL, Redis, SeaweedFS, Kafka, backend metrics, Prometheus, Loki, exporters, or the Docker socket proxy publicly. Redis runs in the core project with password authentication, bounded memory, allkeys-lru eviction, and persistence disabled. Keep it private to the Compose network. The separate monitoring project supplies redis-exporter; ML does not use Redis in the current scaffold. +Kafka runs in the core project as one internal KRaft broker and controller with a bounded JVM heap, a memory limit, and a named volume. Keep its listener private to the Compose network and create topics explicitly; it carries events only through the transactional outbox. + SeaweedFS runs as a single-node S3-compatible server in the core project. Persist both data and metadata in its named volume. Keep every storage port private; require credentials for S3 access. Nginx does not proxy private objects directly. Ordinary shutdown preserves the volume; this local setup does not provide HA or off-host backups. Use the repository's Compose and observability Make targets to render and validate configuration. Keep secrets in a local .env or deployment secret store, not in committed examples. Do not claim TLS, public availability, multi-node reliability, or a successful deploy based on Compose syntax checks. diff --git a/.agents/standards/ml.md b/.agents/standards/ml.md index 98d1ad3..5ac23fd 100644 --- a/.agents/standards/ml.md +++ b/.agents/standards/ml.md @@ -1,6 +1,6 @@ # ML service standard -The ML service is a separate Python HTTP service. Its current role is an operational scaffold with health and readiness routes; there is no model-backed product endpoint yet. +The ML service is a separate Python HTTP service. It serves health and readiness routes and one model-backed endpoint, `POST /v1/embeddings`, with pinned embedding models whose files are verified against the lock files in ml/model/ (baked into the image, or local files on a GPU host). Every route except health and readiness requires the shared bearer token. Ordinary tests use the deterministic fake encoder; the real models run only in the marked slow tests. Keep the service contract in api/ml/. The Go client uses backend/codegen/ogen-ml.yml and is consumed under backend/internal/adapter/secondary/ml/api/. Python model generation belongs to ml/codegen/pyproject.toml: datamodel-code-generator produces Pydantic v2 models from api/ml/openapi.bundle.yml in ml/src/lincodex_ml/api/models.py. Keep generator dependencies in ml/pyproject.toml and uv.lock; the codegen pyproject contains tool settings only. Health/readiness handlers import generated models instead of maintaining duplicate transport schemas. @@ -8,7 +8,7 @@ Use make -C ml generate to bundle the contract and generate models. The root gen Readiness must describe whether the required model or inference runtime is available. Return not-ready while it is unavailable. Do not invent a successful result or label a fixture as a model response. -When inference is added, validate structured output, bound input and output size, apply timeouts, and preserve model and schema versions. Avoid logging resume text, contact details, credentials, or full prompts. Treat document contents and model output as untrusted data. +Validate inference output, bound input and output size, apply timeouts, and preserve model and schema versions. Avoid logging resume text, contact details, credentials, or full prompts. Treat document contents and model output as untrusted data. Use uv with the checked-in lockfile. Keep ordinary lint, type checks, and tests independent of external model downloads and GPU access. Model quality evaluation is a separate, reproducible task with documented data and limits. diff --git a/.agents/standards/security.md b/.agents/standards/security.md index fb57f9e..ed460f7 100644 --- a/.agents/standards/security.md +++ b/.agents/standards/security.md @@ -10,6 +10,6 @@ Treat resumes, API payloads, model output, repository documents, dependencies, t Keep health routes minimal. Keep /metrics and infrastructure administration surfaces on internal interfaces. Review bind addresses and network access whenever a Compose or Nginx change affects reachability. -Architecture notes about privacy controls are requirements for future product behavior. They are not proof of legal compliance, completed authorization, or a security audit. +Verify privacy controls in the current code and access tests. Architecture notes alone are not proof of enforcement, legal compliance, or a security audit. Run configured security checks through `security/Makefile`. Trivy HIGH/CRITICAL findings, including unfixed vulnerabilities, block validation; Gitleaks, govulncheck, configured Semgrep findings, and scanner errors also fail their checks. Scan both repository inputs and built images, and require complete Git history for secret scanning. Keep reports local and redact secret values. Any exception must be specific, reviewed, and record a reason, owner, and expiry; review expiry explicitly where the tool does not enforce it. Do not add broad exclusions to make a scan pass. These checks complement gosec and do not replace authorization tests or a security audit. diff --git a/.agents/standards/testing.md b/.agents/standards/testing.md index df19079..f8ddee0 100644 --- a/.agents/standards/testing.md +++ b/.agents/standards/testing.md @@ -6,7 +6,7 @@ Use unit tests for domain and application behavior, component tests for frontend Contract changes need bundle and lint checks, regeneration of affected consumers, and generated drift checks. Infrastructure changes need rendered Compose configuration and the validator for each changed monitoring or deployment file. -The technical deployment smoke checks service routes and infrastructure readiness. It does not validate a candidate or employer workflow. The deploy test-e2e target is reserved and currently fails with a deferred message until the business-flow suite exists. +The technical deployment smoke checks service routes and infrastructure readiness. The deploy test-e2e target runs Playwright against an isolated throwaway stack, including candidate and employer scenarios in frontend/e2e/. Report which scenarios ran, failed, or were skipped; a smoke pass alone does not validate a business workflow. Do not report ranking accuracy, assessment validity, production latency, load capacity, privacy correctness, or model quality without the corresponding measured test and its dataset, environment, and limits. Planned targets and synthetic examples are not results. diff --git a/.agents/workflows/development.md b/.agents/workflows/development.md index 0735593..e72b15b 100644 --- a/.agents/workflows/development.md +++ b/.agents/workflows/development.md @@ -8,4 +8,8 @@ Preserve concurrent edits. If ownership is unclear or a collision appears, stop Use Make targets instead of maintaining duplicate shell command lists. Generate derived output from its source. Validate the affected boundary, then hand off the exact files changed and evidence collected. +Keep planning identifiers and progress reports inside the local PRD directory. Describe behavior and rationale in code comments, documentation, and commit messages without referring to numbered backlog items. Never stage or commit PRD. Use the configured human Git identity and do not add assistant authorship or coauthor trailers. + +Keep READMEs short: purpose, essential commands, and links to the relevant guide. Document current behavior from code and configuration. Update existing sections instead of appending implementation diaries, old test results, or copies of API schemas. Preserve required setup steps and operational limits in both languages. + Keep ignore rules in the component that owns the artifacts. Each service has its own .gitignore; the root .gitignore covers only files at the repository root. Do not collect service caches and build outputs in one root ignore file. diff --git a/.dockerignore b/.dockerignore index 1e77157..2da3552 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,6 +6,10 @@ Thumbs.db .env .env.example +**/.env +**/.env.* +# Release manifests, build records, and evidence stay out of build contexts. +deploy/release **/node_modules **/dist **/coverage diff --git a/.env.example b/.env.example index 5bca2ed..bcfe470 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,10 @@ APP_PROJECT=app APP_NETWORK=app_default APP_HTTP_PORT=8080 +# Address the frontend port is published on. Keep the loopback default for a +# local stack. On a host that sits behind the edge proxy, set the address of +# its tunnel interface (for example 10.79.0.2); never 0.0.0.0. +APP_HTTP_BIND=127.0.0.1 POSTGRES_DB=lincodex POSTGRES_USER=lincodex @@ -13,6 +17,119 @@ SEAWEEDFS_ACCESS_KEY=lincodex-local SEAWEEDFS_SECRET_KEY=replace-this-storage-secret SEAWEEDFS_BUCKET=lincodex +# Kafka KRaft cluster identifier. It is not a secret and grants no access; it +# ties the formatted log directory to one cluster. Generate your own value with +# `docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid` +# before the first start; changing it later stops Kafka from using the existing volume. +KAFKA_CLUSTER_ID=SJv4PXUUSJGbK3eSPC57qA + +# Mail. EMAIL_PROVIDER is required and selects exactly one transport: +# resend, smtp, or disabled; there is no default. resend sends through the +# Resend HTTP API and the working stand sets it explicitly. This example sets +# disabled so that local runs need no key. This build has no SMTP transport +# yet, so smtp fails startup after its settings are validated. disabled sends +# nothing and reports the mail channel as unavailable; it never confirms an +# address or skips an account check. +EMAIL_PROVIDER=disabled +EMAIL_FROM=no-reply@example.com +# Label of the provider account (lowercase letters, digits, ".", "_", "-"), +# never the key. Every new delivery is pinned to EMAIL_PROVIDER and this +# label, and the mail quota is counted under it. Change it whenever the key +# belongs to another provider account, and only then: renaming the label of +# the same account resets the local quota count. +EMAIL_ACCOUNT=default +EMAIL_TIMEOUT=10s +# Recipients the configured provider account may be sent per UTC day and per +# UTC calendar month. Empty means the Resend Free plan limits, 100 and 3000, +# for resend and disabled; smtp requires both values. A used-up quota makes +# mail wait for the reset; nothing buys a plan or switches the transport. +EMAIL_QUOTA_DAILY= +EMAIL_QUOTA_MONTHLY= +# Recipients per UTC day and per UTC month that product notifications leave +# free for service mail (verification and password reset). Empty means a fifth +# of the matching quota limit, 20 and 600 on the Resend Free plan. Notifications +# are admitted only while the window stays at or above the reserve after them. +EMAIL_SERVICE_RESERVE_DAILY= +EMAIL_SERVICE_RESERVE_MONTHLY= +# Public origin for links in mail. Email confirmation requires the browser's +# Origin header to match this scheme, host, and port. Use HTTPS except on +# localhost, 127.0.0.1, or [::1]. Do not add a path, query, or fragment. +APP_PUBLIC_URL=http://localhost:8080 +# Read only when EMAIL_PROVIDER=resend, where it is required. Keep the real +# key in the server environment only; it is never logged. +RESEND_API_KEY= +# Read only when EMAIL_PROVIDER=smtp. SMTP_TLS_MODE is starttls or tls; +# plaintext SMTP is not supported. +SMTP_HOST= +SMTP_PORT= +SMTP_USERNAME= +SMTP_PASSWORD= +SMTP_TLS_MODE= + +# Password hashing: Argon2id derivations that may run at once, from 1 to 4. +# Each takes 64 MiB; the backend container has 1 CPU and 768 MB of memory, so +# more than 1 only adds memory while the derivations share the CPU. +PASSWORD_HASH_CONCURRENCY=1 + +# The app Docker network has a pinned subnet and the frontend container a fixed +# address on it, so the backend can trust exactly that one proxy. Change the +# two together if the range collides with another network or route. +APP_SUBNET=172.29.79.0/24 +APP_FRONTEND_IP=172.29.79.10 +# Registration and email confirmation. IDENTITY_KEY_SECRET is required. It +# keys idempotency records, rate-limit counters, session CSRF tokens, and +# organization-scoped candidate aliases across restarts and instances. +# Use at least 32 bytes. There is no usable example value: leave it empty here +# and generate one for every deployment (Compose refuses an empty value): +# openssl rand -base64 48 +# A value that starts with replace-this is refused. Without it the backend refuses to start, unless a development stand sets +# IDENTITY_ALLOW_EPHEMERAL_KEY=true (a random secret per process; candidate +# aliases also change after restart). +IDENTITY_KEY_SECRET= +# Registration and every verification resend count toward both per-address limits. +VERIFICATION_MAIL_MIN_INTERVAL=1m +VERIFICATION_MAIL_DAILY_LIMIT=5 +# Confirmation attempts are limited to 5 per token per hour by the service. +# This token limit is fixed; it has no environment setting. +# IDENTITY_CLIENT_HOURLY_LIMIT applies to registration, confirmation, resends, +# and login per resolved client address per hour, when available. +IDENTITY_CLIENT_HOURLY_LIMIT=30 +# Login attempts are limited by the resolved client address and normalized +# email address. The email limit applies whether or not the account exists. +IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT=10 +# Sessions expire after this much inactivity or at the absolute lifetime, +# whichever comes first. Idle must not exceed absolute; idle is capped at 30d +# and absolute at 365d. +IDENTITY_SESSION_IDLE_TIMEOUT=24h +IDENTITY_SESSION_ABSOLUTE_LIFETIME=168h + +# Off by default. Allow demo_basic category assignment only for a reviewed +# synthetic opening with an exactly pinned manifest and product policy. +# demo_express never assigns a category. Leave false outside a synthetic stand. +ASSESSMENT_DEMO_CATEGORIES_ENABLED=false + +# Own code runner for code practice. Empty CODE_RUNNER_URL keeps it off: the +# backend then reports the runner as unavailable and runs nothing. To enable +# it, set the https URL of the runner VM, its service token, a separate random +# run key, and the CA that signed the runner certificate (a file path inside +# the container, or the PEM text with \n for line breaks). Generate both +# secrets with `openssl rand -hex 32`; keep them in the server environment only. +# CODE_RUNNER_SERVER_NAME is the certificate name when the URL is an IP the +# certificate does not list; CODE_RUNNER_REQUEST_TIMEOUT defaults to 10s. +CODE_RUNNER_URL= +CODE_RUNNER_TOKEN= +CODE_RUNNER_RUN_KEY= +CODE_RUNNER_CA_FILE= +CODE_RUNNER_CA_PEM= +CODE_RUNNER_SERVER_NAME= +CODE_RUNNER_REQUEST_TIMEOUT= + +# Reverse proxies the backend trusts to report the client address in +# X-Forwarded-For. Leave it unset: the default is the frontend container's +# APP_FRONTEND_IP as a single address. A wider list lets other containers (or a +# client behind them) choose their own address; empty trusts nobody. +# TRUSTED_PROXY_CIDRS= + # Optional PostgreSQL metrics login, created when the database volume is initialized. POSTGRES_EXPORTER_USER=metrics_reader POSTGRES_EXPORTER_PASSWORD=replace-this-metrics-password @@ -25,5 +142,9 @@ GRAFANA_ADMIN_PASSWORD=replace-this-grafana-password ML_BIND_ADDRESS=127.0.0.1 ML_HTTP_PORT=8000 ML_METRICS_TARGET= +# Shared bearer token of the ML service and the backend (a secret of at least +# 32 characters, for example openssl rand -hex 32); required by the ML +# container and by the backend while SEMANTIC_MATCHING_ENABLED is true. +ML_SERVICE_TOKEN= # For rootless Docker, use the Unix socket from `docker context inspect`. DOCKER_SOCKET_PATH=/var/run/docker.sock diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc75846..7cbf21e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: api: name: API contracts runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 30 steps: - name: Check out source uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 @@ -46,8 +46,30 @@ jobs: python-version-file: ml/.python-version cache: pip cache-dependency-path: scripts/requirements-codegen.txt + # make -C api verify runs check-toolchain, which generates the OpenAPI 3.2 + # fixture with ogen, Orval, and datamodel-code-generator, so the job also + # needs the frontend and ML toolchains. + - name: Install declared pnpm + run: npm install --global "$(node -p "require('./frontend/package.json').packageManager")" + - name: Cache pnpm store + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.local/share/pnpm/store + key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm- + - name: Set up uv + uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0 + with: + version: 0.12.22 + enable-cache: true + cache-dependency-glob: ml/uv.lock - name: Install API tooling run: make -C api install + - name: Install frontend dependencies + run: make -C frontend install + - name: Install ML dependencies + run: make -C ml install - name: Check API formatting and compatibility run: make -C api fmt-check verify - name: Check compatibility with the pull request base @@ -79,7 +101,7 @@ jobs: run: make -C backend test-race integration: - name: Integration tests (${{ matrix.shard }}/2) + name: Integration tests (${{ matrix.shard }}/${{ strategy.job-total }}) runs-on: ubuntu-24.04 timeout-minutes: 30 strategy: @@ -99,10 +121,12 @@ jobs: cache-dependency-path: backend/go.sum - name: Install Go dependencies run: make -C backend deps - - name: Run PostgreSQL, Redis, and SeaweedFS integration shard + # The shard total comes from the matrix size, so adding a shard cannot + # leave TEST_SHARD_TOTAL stale; an index outside the total fails the run. + - name: Run PostgreSQL, Redis, SeaweedFS, and Kafka integration shard env: TEST_SHARD_INDEX: ${{ matrix.shard }} - TEST_SHARD_TOTAL: "2" + TEST_SHARD_TOTAL: ${{ strategy.job-total }} GOFLAGS: -race run: make -C backend test-int @@ -208,6 +232,8 @@ jobs: persist-credentials: false - name: Check Compose files run: make -C deploy check + - name: Test the public Nginx perimeter on throwaway containers + run: make -C deploy perimeter-test - name: Check observability files run: make -C observability check - name: Build the separate ML image @@ -294,6 +320,55 @@ jobs: - name: Build and check technical health routes run: make -C deploy smoke + e2e: + name: Browser E2E + needs: + - backend + - frontend + - infrastructure + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - name: Check out source + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + with: + persist-credentials: false + - name: Set up Node.js + uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 + with: + node-version-file: frontend/.node-version + - name: Install declared pnpm + run: npm install --global "$(node -p "require('./frontend/package.json').packageManager")" + - name: Cache pnpm store + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: ~/.local/share/pnpm/store + key: ${{ runner.os }}-pnpm-${{ hashFiles('frontend/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm- + # The runner mounts the installed @playwright/test into the browser image. + - name: Install frontend dependencies + run: make -C frontend install + # deploy/scripts/e2e.sh generates its own throwaway env file with random + # secrets outside the workspace and starts a fresh, uniquely named stand, + # so the job needs no repository secrets and no root .env. + - name: Run the Playwright suite on an isolated stand + run: make -C deploy test-e2e + # Only the Playwright report, failed-test traces and screenshots, and the + # stand logs are uploaded; the generated env file never enters this tree. + - name: Upload E2E diagnostics + if: ${{ failure() }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: e2e-diagnostics-attempt-${{ github.run_attempt }} + path: | + frontend/test-results/e2e/report/ + frontend/test-results/e2e/results/ + frontend/test-results/e2e/stand.log + if-no-files-found: warn + include-hidden-files: false + retention-days: 14 + aggregate: name: Required CI result if: always() @@ -306,35 +381,24 @@ jobs: - codegen - infrastructure - smoke + - e2e - security - security-images runs-on: ubuntu-24.04 + timeout-minutes: 5 steps: + # Every job in needs must report success. failure, cancelled, and + # skipped (for example after a failed dependency) all fail this result, + # and a job added to needs is checked without a separate line here. - name: Require every CI job to pass env: - API_RESULT: ${{ needs.api.result }} - BACKEND_RESULT: ${{ needs.backend.result }} - INTEGRATION_RESULT: ${{ needs.integration.result }} - FRONTEND_RESULT: ${{ needs.frontend.result }} - ML_RESULT: ${{ needs.ml.result }} - CODEGEN_RESULT: ${{ needs.codegen.result }} - INFRASTRUCTURE_RESULT: ${{ needs.infrastructure.result }} - SMOKE_RESULT: ${{ needs.smoke.result }} - SECURITY_RESULT: ${{ needs.security.result }} - SECURITY_IMAGES_RESULT: ${{ needs.security-images.result }} + NEEDS_JSON: ${{ toJSON(needs) }} run: | - printf 'api=%s backend=%s frontend=%s ml=%s codegen=%s infrastructure=%s smoke=%s\n' \ - "$API_RESULT" "$BACKEND_RESULT" "$FRONTEND_RESULT" "$ML_RESULT" \ - "$CODEGEN_RESULT" "$INFRASTRUCTURE_RESULT" "$SMOKE_RESULT" - test "$API_RESULT" = success - test "$BACKEND_RESULT" = success - printf 'integration=%s\n' "$INTEGRATION_RESULT" - test "$INTEGRATION_RESULT" = success - test "$FRONTEND_RESULT" = success - test "$ML_RESULT" = success - test "$CODEGEN_RESULT" = success - test "$INFRASTRUCTURE_RESULT" = success - test "$SMOKE_RESULT" = success - printf 'security=%s security-images=%s\n' "$SECURITY_RESULT" "$SECURITY_IMAGES_RESULT" - test "$SECURITY_RESULT" = success - test "$SECURITY_IMAGES_RESULT" = success + set -euo pipefail + jq -r 'to_entries[] | "\(.key)=\(.value.result)"' <<<"$NEEDS_JSON" + test "$(jq 'length' <<<"$NEEDS_JSON")" -gt 0 + failed=$(jq -r '[to_entries[] | select(.value.result != "success") | .key] | join(" ")' <<<"$NEEDS_JSON") + if [ -n "$failed" ]; then + printf 'Required jobs did not succeed: %s\n' "$failed" >&2 + exit 1 + fi diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index cb25b9b..5dfa36c 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -40,6 +40,7 @@ jobs: needs: - docs runs-on: ubuntu-24.04 + timeout-minutes: 5 steps: - name: Require documentation checks to pass env: diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile index 54897ad..d091851 100644 --- a/Makefile +++ b/Makefile @@ -13,44 +13,48 @@ install: ## Install project dependencies printf '\n==> %s install\n' "$$part"; \ $(MAKE) -C "$$part" install || status=1; \ done; \ - printf '\n==> backend deps\n'; \ - $(MAKE) -C backend deps || status=1; \ + for part in backend runner labd; do \ + printf '\n==> %s deps\n' "$$part"; \ + $(MAKE) -C "$$part" deps || status=1; \ + done; \ exit "$$status" generate: ## Generate shared contracts, Go and TypeScript code, and Python models $(MAKE) -C api bundle API_PREPARED=1 $(MAKE) -C backend generate + API_PREPARED=1 $(MAKE) -C runner generate + API_PREPARED=1 $(MAKE) -C labd generate API_PREPARED=1 $(MAKE) -C frontend generate API_PREPARED=1 $(MAKE) -C ml generate gen: generate ## Alias for generate fmt: ## Format all project parts - @status=0; for part in api backend frontend ml; do \ + @status=0; for part in api backend runner labd frontend ml; do \ printf '\n==> %s fmt\n' "$$part"; \ $(MAKE) -C "$$part" fmt || status=1; \ done; exit "$$status" fmt-check: ## Check formatting without changing files - @status=0; for part in api backend frontend ml; do \ + @status=0; for part in api backend runner labd frontend ml; do \ printf '\n==> %s fmt-check\n' "$$part"; \ $(MAKE) -C "$$part" fmt-check || status=1; \ done; exit "$$status" lint: ## Run configured linters - @status=0; for part in api backend frontend ml; do \ + @status=0; for part in api backend runner labd frontend ml; do \ printf '\n==> %s lint\n' "$$part"; \ $(MAKE) -C "$$part" lint || status=1; \ done; exit "$$status" test: ## Run unit and component tests - @status=0; for part in backend frontend ml; do \ + @status=0; for part in backend runner labd frontend ml; do \ printf '\n==> %s test\n' "$$part"; \ $(MAKE) -C "$$part" test || status=1; \ done; exit "$$status" check: ## Run local checks for code, docs, deployment, and observability - @status=0; for part in api backend frontend ml deploy observability; do \ + @status=0; for part in api backend runner labd frontend ml deploy observability; do \ printf '\n==> %s check\n' "$$part"; \ $(MAKE) -C "$$part" check || status=1; \ done; \ diff --git a/README.en.md b/README.en.md index 7d8f93e..eabe0c7 100644 --- a/README.en.md +++ b/README.en.md @@ -2,50 +2,61 @@ [Русский](README.md) | English -Lincodex is a technical scaffold for a platform that helps employers find IT specialists. The current checkout provides service health routes, PostgreSQL, Redis, and SeaweedFS readiness checks, cache and S3 storage adapters, a minimal status page, Docker Compose files, OpenAPI contracts, and optional monitoring. Product workflows such as accounts, assessments, candidate search, invitations, and resume processing are planned and are not implemented. +Lincodex helps employers find IT specialists by verified skills. Candidates complete a profile, take assessments, and control their card's visibility. Employers describe hiring needs, search for candidates, and send invitations; contact details become available after the candidate consents. -## Start locally +The core stack is Go + chi, React + TypeScript, PostgreSQL, Redis, SeaweedFS, and Kafka. ML, code execution, lab environments, and monitoring run separately. Demonstration categories do not establish assessment validity for real candidates. -Copy .env.example to .env, replace every placeholder password, then run: +## Quick start - make -C deploy config - make -C deploy up +Install Docker with the Compose plugin, GNU make, Python 3, and openssl. -Open http://127.0.0.1:8080. The local Nginx listener is bound to loopback and does not provide production TLS. +1. Copy `.env.example` to `.env` and replace the `replace-this-...` values. +2. Generate `IDENTITY_KEY_SECRET` with `openssl rand -base64 48`. +3. Build and start the core stack: -To start the separate monitoring stack after the core services: +```sh +make -C deploy config +make -C deploy build +make -C deploy up +``` - make -C deploy monitoring-up +Open http://localhost:8080. The address must match `APP_PUBLIC_URL`. The `config` check uses the example environment; it does not validate your `.env` values. -Grafana is available at http://127.0.0.1:3000 on the local machine. See the deployment guide before exposing any service to another host. +Mail defaults to `EMAIL_PROVIDER=disabled`, so new accounts cannot verify their email. Configure Resend for real delivery using the [deployment guide](docs/en/DEPLOYMENT.md). `make -C deploy down` stops the services and keeps their data. -## Development +## Demonstration -The root Makefile provides install, generate, fmt, fmt-check, lint, test, check, verify, and docs-check targets. Run make help for the current command list. The development and testing guides describe the service-specific commands and what the current checks cover. +A separate stand provides synthetic data and prepared accounts: -## Documentation +```sh +make -C deploy demo-seed DEMO_MODE=isolated +``` -Short directory guides: +Open http://localhost:8090 and follow `/demo`. The command prints account names; `DEMO_ACCOUNT_PASSWORD` in the demo settings supplies their password. These accounts do not require email delivery. See [DEPLOYMENT.md](docs/en/DEPLOYMENT.md) for details and cleanup. + +Start monitoring separately with `make -C deploy monitoring-up`. Grafana defaults to http://127.0.0.1:3000. + +## Directories | Directory | Purpose | | --- | --- | | [api/](api/README.en.md) | Shared OpenAPI contracts | -| [backend/](backend/README.en.md) | Main Go service | +| [backend/](backend/README.en.md) | Core Go service | | [frontend/](frontend/README.en.md) | React and TypeScript interface | -| [ml/](ml/README.en.md) | Separate Python service for ML | -| [deploy/](deploy/README.en.md) | Docker Compose, Nginx, and service startup | +| [ml/](ml/README.en.md) | ML API and models | +| [runner/](runner/README.en.md) | Isolated code execution | +| [labd/](labd/README.en.md) | Lab environment provisioning | +| [deploy/](deploy/README.en.md) | Compose, Nginx, and deployment | | [observability/](observability/README.en.md) | Metrics, logs, and dashboards | -| [security/](security/README.en.md) | Security scanners and rules | -| [docs/](docs/README.en.md) | Detailed Russian and English guides | -| [requirements/](requirements/README.en.md) | Original specification and brand assets | -| [scripts/](scripts/README.en.md) | Shared code generation and validation scripts | -| [.github/](.github/workflows/) | GitHub Actions workflows | -| [.agents/](.agents/README.en.md) | Agent rules | +| [security/](security/README.en.md) | Security checks | +| [docs/](docs/README.en.md) | Russian and English guides | +| [requirements/](requirements/README.en.md) | Specification and brand assets | +| [scripts/](scripts/README.en.md) | Shared scripts and checks | +| [.github/](.github/workflows/) | GitHub Actions | +| [.agents/](.agents/README.en.md) | Repository working rules | -- Source materials: [specification](requirements/specification.pdf), [brandbook](requirements/brandbook/). -- Russian: [architecture](docs/ru/ARCHITECTURE.md), [development](docs/ru/DEVELOPMENT.md), [deployment](docs/ru/DEPLOY.md), [testing](docs/ru/TESTING.md), [security](docs/ru/SECURITY.md) -- English: [architecture](docs/en/ARCHITECTURE.md), [development](docs/en/DEVELOPMENT.md), [deployment](docs/en/DEPLOY.md), [testing](docs/en/TESTING.md), [security](docs/en/SECURITY.md) +Development commands: `make help`. Start with [DEVELOPMENT.md](docs/en/DEVELOPMENT.md); see [TESTING.md](docs/en/TESTING.md) for checks and [ARCHITECTURE.md](docs/en/ARCHITECTURE.md) for the design. ## License -No project-wide license has been assigned in this repository. Check the license terms of each dependency and container image before redistribution. +Project code is distributed under [GPL-3.0-only](LICENSE). Dependencies and source materials may have their own terms of use. diff --git a/README.md b/README.md index 8c2c6cb..90f5240 100644 --- a/README.md +++ b/README.md @@ -2,54 +2,61 @@ Русский | [English](README.en.md) -Lincodex - технический каркас платформы, на которой работодатели находят IT-специалистов. Сейчас в проекте есть маршруты проверки состояния сервисов, проверка готовности PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, минимальная страница состояния, файлы Docker Compose, контракты OpenAPI и отдельно запускаемый мониторинг. Учетные записи, оценка кандидатов, поиск сотрудников, приглашения и обработка резюме запланированы, но пока не реализованы. +Lincodex помогает работодателям находить IT-специалистов по подтвержденным навыкам. Кандидат заполняет профиль, проходит оценку и управляет видимостью карточки. Работодатель описывает потребность, ищет кандидатов и отправляет приглашения; контакты открываются после согласия кандидата. -## Локальный запуск +Основной стек: Go + chi, React + TypeScript, PostgreSQL, Redis, SeaweedFS и Kafka. ML, исполнитель кода, лабораторные окружения и мониторинг подключаются отдельно. Демонстрационные категории не означают, что оценка уже откалибрована на реальных кандидатах. -Скопируйте `.env.example` в `.env`, замените все пароли-заглушки и выполните: +## Быстрый старт + +Нужны Docker с Compose plugin, GNU make, Python 3 и openssl. + +1. Скопируйте `.env.example` в `.env` и замените значения `replace-this-...`. +2. Для `IDENTITY_KEY_SECRET` создайте секрет: `openssl rand -base64 48`. +3. Соберите и запустите основной стек: ```sh make -C deploy config +make -C deploy build make -C deploy up ``` -Откройте http://127.0.0.1:8080. Локальный Nginx слушает только loopback-интерфейс; TLS для продакшена не настроен. +Откройте http://localhost:8080. Адрес должен совпадать с `APP_PUBLIC_URL`. Проверка `config` использует пример окружения; она не подтверждает правильность вашего `.env`. -Мониторинг запускается отдельно, после основных сервисов: +По умолчанию `EMAIL_PROVIDER=disabled`: новый аккаунт нельзя подтвердить без почты. Для реальной отправки настройте Resend по [руководству развертывания](docs/ru/DEPLOYMENT.md). Команда `make -C deploy down` останавливает сервисы, сохраняя данные. + +## Демонстрация + +Отдельный стенд содержит синтетические данные и готовые аккаунты: ```sh -make -C deploy monitoring-up +make -C deploy demo-seed DEMO_MODE=isolated ``` -Grafana доступна на локальной машине по адресу http://127.0.0.1:3000. Перед открытием доступа с других хостов прочитайте руководство по развертыванию. +Адрес стенда: http://localhost:8090, маршрут демонстрации: `/demo`. Команда выводит логины; пароль задает `DEMO_ACCOUNT_PASSWORD` в настройках демонстрации. Эти аккаунты не требуют отправки писем. Подробности и очистка стенда описаны в [DEPLOYMENT.md](docs/ru/DEPLOYMENT.md). -## Разработка +Мониторинг запускается отдельно командой `make -C deploy monitoring-up`. Grafana по умолчанию доступна на http://127.0.0.1:3000. -Корневой Makefile содержит цели `install`, `generate`, `fmt`, `fmt-check`, `lint`, `test`, `check`, `verify` и `docs-check`. Актуальный список команд доступен через `make help`. Команды отдельных сервисов и границы текущих проверок описаны в руководствах по разработке и тестированию. - -## Документация - -Краткие описания каталогов: +## Каталоги | Каталог | Назначение | | --- | --- | | [api/](api/README.md) | Общие OpenAPI-контракты | -| [backend/](backend/README.md) | Основной сервис на Go | -| [frontend/](frontend/README.md) | Интерфейс на React и TypeScript | -| [ml/](ml/README.md) | Отдельный Python-сервис для ML | -| [deploy/](deploy/README.md) | Docker Compose, Nginx и запуск сервисов | +| [backend/](backend/README.md) | Основной Go-сервис | +| [frontend/](frontend/README.md) | Интерфейс React и TypeScript | +| [ml/](ml/README.md) | ML API и модели | +| [runner/](runner/README.md) | Изолированное выполнение кода | +| [labd/](labd/README.md) | Подготовка лабораторных окружений | +| [deploy/](deploy/README.md) | Compose, Nginx и развертывание | | [observability/](observability/README.md) | Метрики, логи и дашборды | -| [security/](security/README.md) | Сканеры и правила безопасности | -| [docs/](docs/README.md) | Подробные руководства на русском и английском | -| [requirements/](requirements/README.md) | Исходное ТЗ и брендбук | -| [scripts/](scripts/README.md) | Общие скрипты кодогенерации и проверок | -| [.github/](.github/workflows/) | Workflow GitHub Actions | -| [.agents/](.agents/README.md) | Правила работы агентов | +| [security/](security/README.md) | Проверки безопасности | +| [docs/](docs/README.md) | Руководства на русском и английском | +| [requirements/](requirements/README.md) | ТЗ и брендбук | +| [scripts/](scripts/README.md) | Общие скрипты и проверки | +| [.github/](.github/workflows/) | GitHub Actions | +| [.agents/](.agents/README.md) | Правила работы с репозиторием | -- Исходные материалы: [ТЗ](requirements/specification.pdf), [брендбук](requirements/brandbook/). -- На русском: [архитектура](docs/ru/ARCHITECTURE.md), [разработка](docs/ru/DEVELOPMENT.md), [развертывание](docs/ru/DEPLOY.md), [тестирование](docs/ru/TESTING.md), [безопасность](docs/ru/SECURITY.md). -- На английском: [архитектура](docs/en/ARCHITECTURE.md), [разработка](docs/en/DEVELOPMENT.md), [развертывание](docs/en/DEPLOY.md), [тестирование](docs/en/TESTING.md), [безопасность](docs/en/SECURITY.md). +Команды разработки: `make help`. Начните с [DEVELOPMENT.md](docs/ru/DEVELOPMENT.md); проверки описаны в [TESTING.md](docs/ru/TESTING.md), архитектура - в [ARCHITECTURE.md](docs/ru/ARCHITECTURE.md). ## Лицензия -Общая лицензия проекта пока не определена. Перед распространением проверьте условия лицензий каждой зависимости и образа контейнера. +Код проекта распространяется на условиях [GPL-3.0-only](LICENSE). Зависимости и исходные материалы могут иметь собственные условия использования. diff --git a/api/Makefile b/api/Makefile index 896160a..f5ca14c 100644 --- a/api/Makefile +++ b/api/Makefile @@ -16,29 +16,42 @@ install: ## Install pinned OpenAPI tooling npm ci --prefix "$(API_DIR)" --ignore-scripts --no-audit --no-fund .PHONY: bundle -bundle: ## Merge split schemas and create public and ML bundles +bundle: ## Merge split schemas and create public, ML, code runner, and lab provisioner bundles "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/core" "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/ml" + "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/runner" + "$(CODEGEN_PYTHON)" "$(ROOT_DIR)/scripts/merge-schemas.py" "$(API_DIR)/labd" "$(REDOCLY)" bundle "$(API_DIR)/core/openapi.yml" --output "$(API_DIR)/core/openapi.bundle.yml" "$(REDOCLY)" bundle "$(API_DIR)/ml/openapi.yml" --output "$(API_DIR)/ml/openapi.bundle.yml" + "$(REDOCLY)" bundle "$(API_DIR)/runner/openapi.yml" --output "$(API_DIR)/runner/openapi.bundle.yml" + "$(REDOCLY)" bundle "$(API_DIR)/labd/openapi.yml" --output "$(API_DIR)/labd/openapi.bundle.yml" .PHONY: lint -lint: bundle ## Lint both bundled contracts +lint: bundle ## Lint every bundled contract "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/core/openapi.bundle.yml" "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/ml/openapi.bundle.yml" + "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/runner/openapi.bundle.yml" + "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/labd/openapi.bundle.yml" .PHONY: check -check: lint ## Build and lint both contract bundles +check: lint ## Build and lint every contract bundle and run the contract tests PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_merge_schemas.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_contract_copies.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_assessment_contract.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_match_contract.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_runner_contract.py' + PYTHONDONTWRITEBYTECODE=1 "$(CODEGEN_PYTHON)" -m unittest discover -s "$(ROOT_DIR)/scripts" -p 'test_lab_contract.py' .PHONY: check-compat check-compat: bundle ## Compare the public contract with API_BASE_REF API_BASE_REF="$(API_BASE_REF)" REDOCLY="$(REDOCLY)" CODEGEN_PYTHON="$(CODEGEN_PYTHON)" bash "$(ROOT_DIR)/scripts/check-api-compat.sh" .PHONY: check-toolchain -check-toolchain: ## Check OpenAPI 3.2.0 support and generated validation behavior +check-toolchain: ## Check OpenAPI 3.2.0 support with ogen, Orval, and Pydantic on the compatibility fixture "$(REDOCLY)" lint --config "$(API_DIR)/redocly.yaml" "$(API_DIR)/testdata/openapi-3.2.0.yml" $(MAKE) -C "$(ROOT_DIR)/backend" check-ogen-compat + $(MAKE) -C "$(ROOT_DIR)/frontend" check-orval-compat + $(MAKE) -C "$(ROOT_DIR)/ml" check-pydantic-compat .PHONY: fmt fmt: ## Format handwritten OpenAPI YAML files diff --git a/api/README.en.md b/api/README.en.md index a738156..2cbb3a3 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -2,14 +2,57 @@ [Русский](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. +OpenAPI 3.2.0 is the shared source for HTTP contracts. Change the specification first, then generate server adapters, clients, and models. -- `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. +## Structure -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/`. +| Directory | API | +| --- | --- | +| [core/](core/openapi.yml) | Public Go API under `/api/v1` | +| [ml/](ml/openapi.yml) | Internal ML API | +| [runner/](runner/openapi.yml) | Code execution | +| [labd/](labd/openapi.yml) | Lab environment provisioning | +| [testdata/](testdata/openapi-3.2.0.yml) | Generator compatibility fixture | -From the repository root, `make -C api check` checks contracts and `make generate` updates all generated code. +Each contract's `openapi.yml` references `routes/` and `components/`. [merge-schemas.py](../scripts/merge-schemas.py) merges schemas grouped by subject, then Redocly builds `openapi.bundle.yml`. Do not edit derived files by hand. -See the [development guide](../docs/en/DEVELOPMENT.md). +## Generation + +Run these commands from the repository root: + +```sh +make -C api install +make -C api check +make generate +make check-generated +``` + +`check` builds and validates contracts. `generate` updates every consumer. `check-generated` detects differences from committed output; it does not run generation itself. + +| Consumer | Generator and configuration | +| --- | --- | +| Go backend | ogen, [backend/codegen/](../backend/codegen/) | +| Go runner and labd | ogen, each service's `codegen/` directory | +| React | Orval: client, query hooks, Zod schemas, and MSW; [frontend/codegen/](../frontend/codegen/) | +| Python ML | datamodel-code-generator: Pydantic; [ml/codegen/](../ml/codegen/) | + +`make -C api check-toolchain` checks the OpenAPI 3.2 features in a dedicated fixture. It verifies the current toolchain, not every feature of the standard. + +Compare the public contract with an existing Git ref using `make -C api check-compat API_BASE_REF=`. + +## Contract conventions + +- Errors: RFC 9457, `application/problem+json`, stable `code`, and safe messages. The `Problem` schema defines the response fields. +- Sessions: an HttpOnly cookie; mutating session requests also send `X-CSRF-Token`. The origin must match the application configuration. +- Send `Idempotency-Key` where the operation requires it. Reuse the key when retrying the same action; use a new key for different content. +- Concurrent updates use `If-Match` or `expected_version` as specified by the operation. On conflict, reload server state and preserve the user's draft. +- Lists use bounded cursor pagination. Identifiers are UUIDs and timestamps are UTC date-times. An absent field may differ from `null`. +- Read exact codes, limits, required headers, and examples from each operation and its shared components. + +## Boundaries + +An operation in the specification does not prove its handler is complete. Check `backend/internal/adapter/primary/http/v1/` and its tests. An unimplemented operation can return `501 not_implemented`. + +Internal ML, runner, and labd APIs are not browser entry points. The public health route is `/api/v1/healthz`; service guides cover operational `/healthz`, `/readyz`, and metrics. + +See [DEVELOPMENT.md](../docs/en/DEVELOPMENT.md) for contract changes and [TESTING.md](../docs/en/TESTING.md) for checks. diff --git a/api/README.md b/api/README.md index d17bea6..3045cb7 100644 --- a/api/README.md +++ b/api/README.md @@ -2,14 +2,57 @@ Русский | [English](README.en.md) -Общие OpenAPI-контракты для Go, frontend и ML. Сначала изменяется контракт, затем из него генерируются типы, серверный код и клиенты нужных сервисов. +OpenAPI 3.2.0 - общий источник HTTP-контрактов. Сначала меняется спецификация, затем генерируются серверные адаптеры, клиенты и модели. -- `core/` - публичный API основного backend. -- `ml/` - внутренний HTTP API ML-сервиса. -- `testdata/` - спецификация для проверки совместимости инструментов с OpenAPI 3.2.0. +## Структура -Маршруты лежат в `routes/`, схемы - в `components/`. Файлы `openapi.bundle.yml` собираются автоматически. Конфигурации генераторов находятся в `backend/codegen/`, `frontend/codegen/` и `ml/codegen/`. +| Каталог | API | +| --- | --- | +| [core/](core/openapi.yml) | Публичный Go API под `/api/v1` | +| [ml/](ml/openapi.yml) | Внутренний ML API | +| [runner/](runner/openapi.yml) | Исполнитель кода | +| [labd/](labd/openapi.yml) | Подготовка лабораторных окружений | +| [testdata/](testdata/openapi-3.2.0.yml) | Проверка совместимости генераторов | -Из корня: `make -C api check` проверяет контракты, `make generate` обновляет весь сгенерированный код. +В каждом контракте `openapi.yml` подключает `routes/` и `components/`. Тематические схемы объединяет [merge-schemas.py](../scripts/merge-schemas.py), после чего Redocly создает `openapi.bundle.yml`. Производные файлы вручную не редактируются. -Подробнее: [разработка](../docs/ru/DEVELOPMENT.md). +## Генерация + +Команды выполняются из корня репозитория: + +```sh +make -C api install +make -C api check +make generate +make check-generated +``` + +`check` собирает и проверяет контракты. `generate` обновляет всех потребителей. `check-generated` ищет отличия от закоммиченного результата и сам генерацию не запускает. + +| Потребитель | Генератор и настройки | +| --- | --- | +| Go backend | ogen, [backend/codegen/](../backend/codegen/) | +| Go runner и labd | ogen, настройки в `codegen/` каждого сервиса | +| React | Orval: клиент, query hooks, Zod-схемы и MSW; [frontend/codegen/](../frontend/codegen/) | +| Python ML | datamodel-code-generator: Pydantic; [ml/codegen/](../ml/codegen/) | + +`make -C api check-toolchain` проверяет используемые возможности OpenAPI 3.2 на отдельной спецификации. Это проверка текущего набора инструментов, а не обещание поддержки всех возможностей стандарта. + +Для сравнения публичного контракта с существующим Git ref: `make -C api check-compat API_BASE_REF=`. + +## Соглашения контракта + +- Ошибки: RFC 9457, `application/problem+json`, стабильный `code` и безопасные сообщения. Поля ответа задает схема `Problem`. +- Сессия: HttpOnly cookie; изменяющие запросы с сессией также передают `X-CSRF-Token`. Origin должен соответствовать настройке приложения. +- `Idempotency-Key` передается для операций, где он требуется контрактом. Повтор того же действия использует прежний ключ; другое содержимое требует нового. +- Конкурентные изменения используют `If-Match` или `expected_version` согласно операции. При конфликте клиент перечитывает состояние и сохраняет пользовательский черновик. +- Списки используют ограниченную cursor pagination. Идентификаторы - UUID, время - UTC date-time. Отсутствующее поле и `null` могут иметь разный смысл. +- Коды, лимиты, обязательные заголовки и примеры берутся из конкретной операции и общих компонентов. + +## Границы + +Наличие операции в спецификации не доказывает готовность ее обработчика. Проверяйте реализацию в `backend/internal/adapter/primary/http/v1/` и ее тесты. Нереализованная операция может вернуть `501 not_implemented`. + +Внутренние API ML, runner и labd не предназначены для прямого доступа из браузера. Публичный health-маршрут - `/api/v1/healthz`; служебные `/healthz`, `/readyz` и метрики описаны в руководствах сервисов. + +Процесс изменения контрактов: [DEVELOPMENT.md](../docs/ru/DEVELOPMENT.md). Проверки: [TESTING.md](../docs/ru/TESTING.md). diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml new file mode 100644 index 0000000..288e164 --- /dev/null +++ b/api/core/components/examples.yml @@ -0,0 +1,4615 @@ +ValidationFailed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10 + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + - in: header + pointer: /Idempotency-Key + code: required + message: The value is required. +Unauthenticated: + summary: No valid session + value: + type: urn:lincodex:problem:unauthenticated + title: Authentication required + status: 401 + code: unauthenticated + detail: Sign in and repeat the request. + trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b +Forbidden: + summary: The caller may not access the object + value: + type: urn:lincodex:problem:forbidden + title: Access denied + status: 403 + code: forbidden + detail: You do not have permission to perform this operation. + trace_id: 7a8b9c0d-1e2f-4a3b-8c4d-5e6f7a8b9c0d +NotFound: + summary: Unknown route or invisible object + value: + type: urn:lincodex:problem:not_found + title: Resource not found + status: 404 + code: not_found + detail: The requested resource does not exist. + trace_id: 1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f +IdempotencyInProgress: + summary: The first request with this key is still running + value: + type: urn:lincodex:problem:idempotency_in_progress + title: Request with this idempotency key is in progress + status: 409 + code: idempotency_in_progress + detail: Retry after the original request completes. + trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a +StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b +DomainValidationFailed: + summary: The body violates a domain rule + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6c + errors: + - in: body + pointer: /salary_from + code: invalid + message: The value does not match the contract. +VersionConflict: + summary: If-Match does not match the current version + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b +PayloadTooLarge: + summary: The request body exceeds the limit + value: + type: urn:lincodex:problem:payload_too_large + title: Request body too large + status: 413 + code: payload_too_large + detail: Reduce the request body size and retry. + trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e +IdempotencyKeyReused: + summary: The same Idempotency-Key was sent with a different body + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Idempotency key reused with a different request + status: 422 + code: idempotency_key_reused + detail: Use a new Idempotency-Key for a different request. + trace_id: 4f5a6b7c-8d9e-4f0a-9b1c-3d4e5f6a7b8c +PreconditionRequired: + summary: The operation requires If-Match + value: + type: urn:lincodex:problem:precondition_required + title: Precondition required + status: 428 + code: precondition_required + detail: Send If-Match with the ETag of the version you read. + trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d +RateLimited: + summary: Too many requests + value: + type: urn:lincodex:problem:rate_limited + title: Too many requests + status: 429 + code: rate_limited + detail: Wait for the Retry-After interval and retry. + trace_id: 6b7c8d9e-0f1a-4b2c-9d3e-5f6a7b8c9d0e +Internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. + trace_id: 9c0d1e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f +NotImplemented: + summary: Operation declared in the contract without an implementation + value: + type: urn:lincodex:problem:not_implemented + title: Operation not implemented + status: 501 + code: not_implemented + detail: This operation is not available yet. + trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a +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 +VerificationCodeInvalid: + summary: The code does not verify the email + value: + type: urn:lincodex:problem:verification_token_invalid + title: Verification code is not valid + status: 400 + code: verification_token_invalid + detail: Check the code and the password, or request a new message. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b +VerificationCodeMalformed: + summary: The code is not six digits + 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: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c + errors: + - in: body + pointer: /code + code: invalid + message: The value does not match the contract. +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 +SpecializationCatalog: + summary: Illustrative MVP catalog with the Backend and Network Engineer banks published + description: >- + Illustrative values. The directions, specializations, and grades follow + the MVP scale; `test_availability` comes from the published task banks, + so the grades and languages shown here are not a statement about any + deployed bank. + value: + directions: + - code: development + title: Разработка + specializations: + - code: backend + title: Backend + test_availability: + status: available + grades: [intern, junior, middle, senior] + task_languages: [python, go] + note: null + - code: frontend + title: Frontend + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: mobile + title: Mobile + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: infrastructure + title: Инфраструктура + specializations: + - code: network_engineer + title: Сетевой инженер + test_availability: + status: available + grades: [junior, middle] + task_languages: [] + note: null + - code: devops_sre + title: DevOps/SRE + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: data + title: Данные + specializations: + - code: data_analyst + title: Аналитик данных + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: ds_ml + title: DS/ML + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: security + title: Безопасность + specializations: + - code: information_security + title: Информационная безопасность + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: quality + title: Качество + specializations: + - code: qa + title: QA + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + grades: + - code: intern + title: Стажер + - code: junior + title: Junior + - code: middle + title: Middle + - code: senior + title: Senior +NewCandidateQuestionnaire: + summary: A candidate who has not saved the questionnaire yet + value: + version: 0 + specializations: [] + work_context: null + updated_at: null +BackendGoAndNetworkEngineerQuestionnaire: + summary: Backend with Go and Network Engineer, two independent specializations + description: >- + Go is a task language of the `backend` specialization and PostgreSQL and + gRPC are stack tags; none of them is a category. The candidate has two + specializations, `backend` and `network_engineer`, each assessed + independently. The self-assessed grades are claims; no confirmed grade + appears. + value: + version: 3 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: [go] + stack: [PostgreSQL, gRPC, Kafka] + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: [Cisco IOS, BGP] + experience: null + work_context: + work_formats: [remote, hybrid] + updated_at: "2026-10-05T09:30:00Z" +BackendGoAndNetworkEngineerQuestionnaireUpdate: + summary: Save Backend with Go and Network Engineer over version 2 + value: + expected_version: 2 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: [go] + stack: [PostgreSQL, gRPC, Kafka] + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: [Cisco IOS, BGP] + experience: null + work_context: + work_formats: [remote, hybrid] +QuestionnaireTooManySpecializations: + summary: Three specializations were sent; at most two are allowed + 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: 6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f + errors: + - in: body + pointer: /specializations + code: invalid + message: The value does not match the contract. +QuestionnaireUnknownGrade: + summary: A self-assessed grade outside the grade scale, such as lead + 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: 7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a + errors: + - in: body + pointer: /specializations/0/self_assessed_grade + code: invalid + message: The value does not match the contract. +QuestionnaireRepeatedSpecialization: + summary: The same specialization was chosen twice + 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: 8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b + errors: + - in: body + pointer: /specializations/1/specialization + code: invalid + message: The value does not match the contract. +AssessmentAvailability: + summary: Backend open in demo_basic, Network Engineer blocked + description: >- + Illustrative values. Backend junior and middle can start in the + demo_basic mode, with their limits shown before the start; intern and + senior have no sufficient bank. Network Engineer junior waits for its + same-grade retry interval after an unconfirmed attempt. + value: + specializations: + - specialization: backend + confirmed_grade: null + confirmed_basis: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - specialization: network_engineer + confirmed_grade: null + confirmed_basis: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: cooldown + mode: demo_basic + available_at: "2026-11-12T00:00:00Z" + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null +AssessmentAttemptCreateBackendJunior: + summary: Start Backend junior with Go tasks + value: + kind: root + specialization: backend + target_grade: junior + task_language: go +AssessmentAttemptCreated: + summary: New demo_basic attempt with its first item + description: >- + The server chose demo_basic from the published bank and fixed the policy, + bank, and algorithm versions; creation started session 1. A retry of + this create with the same Idempotency-Key and body within 24 hours + replays exactly this 201 response and creates nothing; read the attempt + for its current state. The attempt has no practice, because code + practice stays disabled until the sandbox isolation is verified. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 1 + kind: root + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: null + chain_deadline: null + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + sequence: 1 + prompt: "Какой HTTP-статус вернуть, если запрос валиден, но ресурс находится в состоянии, не допускающем операцию?" + content: + format: choice + multiple: false + options: + - id: k7 + text: "400" + - id: p2 + text: "404" + - id: x9 + text: "409" + - id: c4 + text: "500" + practices: [] +AssessmentCorrectiveAttemptCreated: + summary: Corrective attempt shares the root chain deadline + value: + id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + version: 1 + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: "2026-11-23T09:00:00Z" + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-22T10:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 25 + current_item: + id: 01928f7e-9999-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: "What does an HTTP 412 response indicate for expected_version?" + content: + format: choice + multiple: false + options: + - id: a1 + text: The version is stale. + - id: b2 + text: The request is malformed. + practices: [] +AssessmentExpressAttemptCreated: + summary: Short training attempt without a qualification category + value: + id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c01 + version: 1 + kind: demo_express + specialization: null + target_grade: null + task_language: null + root_attempt_id: null + chain_deadline: null + mode: demo_express + state: in_progress + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-08T10:05:00Z" + sessions: + used: 1 + max: 1 + idle_timeout_seconds: 300 + finished_at: null + progress: + answered_items: 0 + max_items: 5 + current_item: + id: 01928f7f-aaaa-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: "Choose the status code that signals a version conflict." + content: + format: choice + multiple: false + options: + - id: c3 + text: "412" + - id: d4 + text: "200" + practices: [] +AssessmentAnswerAccepted: + summary: Answer to item 1 stored; item 2 follows + description: >- + The answer of AssessmentChoiceAnswer was stored and the version advanced + from 1 to 2. The response does not say whether the answer was correct. + A retry with the same Idempotency-Key replays exactly this response. + Sending the same answer to item 1 again, even with a new key or the + older expected_version 1, stores nothing and returns 200 with the + current attempt. AssessmentOrderAnswer answers item 2 next. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 2 + kind: root + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: null + chain_deadline: null + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 1 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + sequence: 2 + prompt: "Упорядочите шаги обработки запроса в обработчике HTTP." + content: + format: order + elements: + - id: d3 + text: Записать ответ + - id: a7 + text: Проверить сессию + - id: c2 + text: Выполнить операцию + - id: b1 + text: Разобрать и проверить тело + practices: [] +AssessmentAttemptCompleted: + summary: demo_basic attempt finalized; read the result next + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 14 + kind: root + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: null + chain_deadline: null + mode: demo_basic + state: completed + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: "2026-10-08T10:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: "2026-10-08T10:24:00Z" + progress: + answered_items: 12 + max_items: 12 + current_item: null + practices: [] +AssessmentAttemptResumed: + summary: Adaptive attempt resumed on its sixth item in session 2 + description: >- + A reload or a new session returns the same item instance with the same + lines; nothing tells whether the five earlier answers were correct, and + seed items look like scored ones. The retest started from the previous + ability estimate of the specialization. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 7 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 5 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + sequence: 6 + prompt: "Найдите строку, из-за которой соединения с базой данных не возвращаются в пул." + content: + format: find_error + syntax: python + max_selections: 1 + lines: + - number: 1 + text: "def load_user(pool, user_id):" + - number: 2 + text: " conn = pool.acquire()" + - number: 3 + text: " row = conn.fetchrow(QUERY, user_id)" + - number: 4 + text: " if row is None:" + - number: 5 + text: " raise NotFound(user_id)" + - number: 6 + text: " pool.release(conn)" + - number: 7 + text: " return row" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentAttemptPracticePending: + summary: Item part finished, main practice not submitted + description: >- + The adaptive stop rule ended the item part after 14 items, but no grade + is decided until the main practice has a finished verdict. The current + item is the practice; hidden checks and seeds are not part of it. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 16 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу." + content: + format: practice + languages: [python] + max_source_length: 20000 + public_examples: + - input: "[[1,3],[2,6],[8,10]]" + expected_output: "[[1,6],[8,10]]" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentAttemptPracticeVerdictPending: + summary: Practice submitted, verdict pending in the sandbox + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 17 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: pending + submitted_at: "2026-11-20T10:05:00Z" + verdict: null + failure_reason: null +AssessmentAttemptSandboxFailed: + summary: Sandbox queue was full; the practice can be submitted again + description: >- + The failure does not depend on the solution and consumes nothing. The + practice item is current again; a resubmission, with the same or a + different solution, queues it again and advances the version. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 18 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: "Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу." + content: + format: practice + languages: [python] + max_source_length: 20000 + public_examples: + - input: "[[1,3],[2,6],[8,10]]" + expected_output: "[[1,6],[8,10]]" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: failed + submitted_at: "2026-11-20T10:05:00Z" + verdict: null + failure_reason: sandbox_busy +AssessmentAttemptReadyToFinalize: + summary: Main practice verdict finished, ready to finalize + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 20 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: ready_to_finalize + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: "2026-11-20T10:09:00Z" + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null +AssessmentAttemptAdditionalPracticePending: + summary: Finalize offered an additional practice in the same attempt + description: >- + The probability of reaching middle was in the band below confirmation, + so finalize decided nothing yet: it appended an additional practice and + returned the attempt instead of a result. The attempt keeps its time and + session limits and spends no new attempt. Submitting the additional + practice leads back to ready_to_finalize; finalizing now declines it + and gives not_confirmed. A retry of that finalize with a new key and + the old expected_version 20 answers 412 and cannot decline by accident. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 21 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: additional_practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-20T09:00:00Z" + expires_at: "2026-11-23T09:00:00Z" + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + sequence: 16 + prompt: "Реализуйте LRU-кеш с операциями get и put за O(1)." + content: + format: practice + languages: [python] + max_source_length: 20000 + public_examples: + - input: "put(1,1); put(2,2); get(1); put(3,3); get(2)" + expected_output: "1, -1" + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: "2026-11-20T10:09:00Z" + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null + - kind: additional + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentAttemptInsufficientBank: + summary: Attempt ended because the bank could not cover the blueprint + description: >- + The bank ran out of unseen families for a required domain within the + item limit. The attempt ended without a confirmed grade instead of + repeating a family; its result has outcome not_determined, and it does + not count against the retry rules. + value: + id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + version: 10 + kind: root + specialization: network_engineer + target_grade: middle + task_language: null + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: insufficient_bank + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + started_at: "2026-11-21T12:00:00Z" + expires_at: "2026-11-24T12:00:00Z" + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: "2026-11-21T12:31:00Z" + progress: + answered_items: 8 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null +AssessmentChoiceAnswer: + summary: Answer item 1 of version 1 + value: + expected_version: 1 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + answer: + format: choice + option_ids: [x9] +AssessmentOrderAnswer: + summary: Answer item 2 with every element once + value: + expected_version: 2 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + answer: + format: order + element_ids: [a7, b1, c2, d3] +AssessmentNumberAnswer: + summary: Number answer + value: + expected_version: 3 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03 + answer: + format: number + number: 254 +AssessmentStringAnswer: + summary: String answer + value: + expected_version: 4 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04 + answer: + format: string + text: Retry-After +AssessmentFindErrorAnswer: + summary: Find-error answer for the resumed item + value: + expected_version: 7 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + answer: + format: find_error + line_numbers: [5] +AssessmentConfigurationAnswer: + summary: Configuration answer + value: + expected_version: 7 + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c07 + answer: + format: configuration + config: |- + interface GigabitEthernet0/1 + ip access-group BLOCK_TELNET in +AssessmentPracticeAnswer: + summary: Main practice solution + description: >- + Sent with expected_version 16 for the first submission. After a failed + verdict the client sends it again with the current version, such as 18 + in AssessmentAttemptSandboxFailed; the same source then queues again. + value: + expected_version: 16 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + answer: + format: practice + language: python + source_code: |- + def merge_intervals(intervals): + result = [] + for start, end in sorted(intervals): + if result and start <= result[-1][1]: + result[-1][1] = max(result[-1][1], end) + else: + result.append([start, end]) + return result +AssessmentFinalization: + summary: Finalize version 20 + value: + expected_version: 20 +AssessmentDemoBasicResult: + summary: demo_basic result with a confirmed grade and no uncertainty + description: >- + demo_basic computes no ability estimate, so `uncertainty` and `strength` + are null rather than zero, and no percentile is shown. The pass mark + comes from basic grading policy version 1, and the limitations name the + uncalibrated thresholds, the demo bank, and the missing practice. A + first confirmation is not a promotion, so the higher grade can be + tested at once. The result never changes; a repeated finalize returns + the completed attempt, and this read returns the same result. + value: + attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + specialization: backend + target_grade: junior + kind: root + root_attempt_id: null + chain_deadline: null + task_language: go + mode: demo_basic + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: junior + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + [uncalibrated_thresholds, demo_bank, practice_not_included, unproctored] + uncertainty: null + basic_score: + points: 9 + max_points: 12 + pass_points: 8 + practices: [] + gaps: [] + durations: + items_seconds: 1260 + practice_seconds: null + next_steps: + - action: take_higher_grade + grade: middle + available_at: null + decided_at: "2026-10-08T10:24:00Z" +AssessmentAdaptiveResult: + summary: Adaptive promotion confirmed with medium strength + description: >- + Illustrative values, continuing AssessmentAttemptAdditionalPracticePending. + The additional practice raised P_G to 0.84, in the medium band of the + policy version, so the grade is confirmed with medium strength. The + candidate already had junior, so this is a + promotion, and the next one waits for the promotion interval. The + thresholds are uncalibrated until the pilot. + value: + attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null + task_language: python + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: middle + previous_confirmed_grade: junior + strength: medium + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: + theta: 0.62 + standard_error: 0.24 + interval_95: + low: 0.15 + high: 1.09 + p_grade: 0.84 + basic_score: null + practices: + - kind: main + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + - kind: additional + verdict: + score: 3 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: true + gaps: + - domain: concurrency + title: Конкурентность + durations: + items_seconds: 1980 + practice_seconds: 1500 + next_steps: + - action: take_higher_grade + grade: senior + available_at: "2027-02-18T10:30:00Z" + decided_at: "2026-11-20T10:30:00Z" +AssessmentNotConfirmedResult: + summary: Adaptive attempt not confirmed after the additional practice + description: >- + P_G stayed below 0.80 after the additional practice, so middle is not + confirmed, and the candidate keeps no confirmed grade. After a failure, + including the first test, junior can be tested at once; accepting junior + on the evidence of this attempt is offered; middle opens again after the + same-grade retry interval. + value: + attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.70 + p_grade: 0.62 + basic_score: null + practices: + - kind: main + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + - kind: additional + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + gaps: + - domain: databases + title: Базы данных + durations: + items_seconds: 2100 + practice_seconds: 1800 + next_steps: + - action: take_lower_grade + grade: junior + available_at: null + - action: accept_lower_grade + grade: junior + available_at: null + - action: retake_same_grade + grade: middle + available_at: "2026-12-22T11:00:00Z" + decided_at: "2026-11-22T11:00:00Z" +AssessmentInsufficientBankResult: + summary: Attempt without a decision because the bank was insufficient + value: + attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + specialization: network_engineer + target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null + task_language: null + mode: adaptive + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + outcome: not_determined + not_determined_reason: insufficient_bank + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1860 + practice_seconds: null + next_steps: [] + decided_at: "2026-11-21T12:31:00Z" +AssessmentCorrectiveResult: + summary: Corrective result retains its root and fixed deadline + value: + attempt_id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: corrective + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: "2026-11-23T09:00:00Z" + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: [uncalibrated_thresholds, unproctored] + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.70 + p_grade: 0.62 + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1500 + practice_seconds: 900 + next_steps: [] + decided_at: "2026-11-22T11:00:00Z" +AssessmentExpressResult: + summary: Short training result with no qualification evidence + value: + attempt_id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c9d + specialization: null + target_grade: null + task_language: null + kind: demo_express + mode: demo_express + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + outcome: demonstration + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: [demonstration_only] + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 260 + practice_seconds: null + next_steps: [] + summary: The run demonstrates the task flow and creates no qualification evidence. + decided_at: "2026-11-22T11:00:00Z" +AssessmentSpecializationNotInQuestionnaire: + summary: The specialization is not in the questionnaire + 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: 9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c + errors: + - in: body + pointer: /specialization + code: invalid + message: The value does not match the contract. +AssessmentAnswerUnknownOption: + summary: The selected option does not belong to the item + 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: 0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d + errors: + - in: body + pointer: /answer/option_ids/0 + code: invalid + message: The value does not match the contract. +AssessmentAnswerUnknownField: + summary: The client sent its own score + 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: 1b2c3d4e-5f6a-4b7c-8d8e-9f0a1b2c3d4e + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +AssessmentItemNotCurrent: + summary: The answered item is not the current item, or it already has another answer + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f +AssessmentFinalizeNotReady: + summary: Premature finalize; the problem lists unanswered frozen items + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e + pending_item_ids: + - 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + - 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d +AssessmentAttemptNotAvailable: + summary: No attempt can start for the category now + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3d4e5f6a-7b8c-4d9e-8f0a-1b2c3d4e5f6a +AssessmentResultNotReady: + summary: The attempt has no result yet + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b +AssessmentStaleVersion: + summary: The command carried a stale expected_version + description: >- + Another tab or device changed the attempt after the client read version + 1. Nothing was stored; the client reads the attempt again and continues + from its current item. The repository answers a stale version with 412, + not 409. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c +NeedCreateManual: + summary: A manual need without a vacancy and without a text + description: Every field comes from the form as a decision with status confirmed, so every value is a confirmed manual value. There is no vacancy_id and no source_text; the domain is not given and stays unknown. + value: + title: Junior Go-разработчик для сервиса уведомлений + specialization: + value: backend + status: confirmed + grade: + value: junior + status: confirmed + required_skills: + - name: Go + status: confirmed + - name: PostgreSQL + status: confirmed + desired_skills: + - name: Docker + status: confirmed + tasks: + - text: Поддерживать и развивать сервис уведомлений + status: confirmed + work_formats: + value: + - hybrid + status: confirmed + location: + value: Москва + status: confirmed + salary: + value: + salary_from: 120000 + salary_to: 160000 + currency: RUB + period: month + tax_basis: net + status: confirmed +NeedCreateFromText: + summary: A need created from a pasted description + description: Only the title and the text are given. The server extracts suggestions from the text; nothing is confirmed until a member confirms it. + value: + title: Backend в команду платежей + source_text: "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно." +NeedManualWithoutVacancy: + summary: A complete manual need without a vacancy, with computed recommendations + description: The need created by NeedCreateManual. Every value is confirmed and manual, so the quote, extracted_in_version, and extraction_version are null; the domain was not given and stays unknown with null value and source rather than a guessed one. The hybrid format makes the location critical, and it is confirmed. The range of 120000-160000 has a width of about 29%. The first category scores 0.75 with Overlap 1, a money share rounded down to 0.5, and Supply 0.5 for 15 available candidates. The other two have fewer than five candidates, so their score is null and Supply enters their ranking as 0. The recommendation values are illustrative and say nothing about a deployed policy or real candidates. + value: + id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + vacancy_id: null + title: Junior Go-разработчик для сервиса уведомлений + source_text: null + version: 1 + requirements_version: 1 + requirements: + specialization: + status: confirmed + value: backend + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + grade: + status: confirmed + value: junior + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + required_skills: + - name: Go + taxonomy_code: go + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + - name: PostgreSQL + taxonomy_code: postgresql + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + desired_skills: + - name: Docker + taxonomy_code: docker + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + tasks: + - text: Поддерживать и развивать сервис уведомлений + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + domain: + status: unknown + value: null + source: null + work_formats: + status: confirmed + value: + - hybrid + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + location: + status: confirmed + value: Москва + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + salary: + status: confirmed + value: + salary_from: 120000 + salary_to: 160000 + currency: RUB + period: month + tax_basis: net + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + recommendations: + status: computed + requirements_version: 1 + policy_version: 1 + algorithm_version: need-rec.2026-10.1 + computed_at: "2026-10-06T08:15:02Z" + categories: + - specialization: backend + grade: junior + score: 0.75 + skill_overlap: + share: 1 + covered_skills: + - Go + - PostgreSQL + - Docker + uncovered_skills: [] + money: + status: computed + share: 0.5 + supply: from_5_to_29 + - specialization: backend + grade: intern + score: null + skill_overlap: + share: 0.8 + covered_skills: + - Go + - PostgreSQL + uncovered_skills: + - Docker + money: + status: insufficient_data + share: null + supply: fewer_than_5 + - specialization: devops_sre + grade: junior + score: null + skill_overlap: + share: 0.2 + covered_skills: + - Docker + uncovered_skills: + - Go + - PostgreSQL + money: + status: insufficient_data + share: null + supply: fewer_than_5 + created_at: "2026-10-06T08:15:00Z" + updated_at: "2026-10-06T08:15:00Z" +NeedExtractedWithUnknownSkill: + summary: A need from text with suggestions, an unknown skill, and missing fields + description: "The need created by NeedCreateFromText. Every value found in the text is extracted with its quote from the text of version 1 and the extractor version, and waits for confirmation. Temporal is not in the skill taxonomy, so its taxonomy_code is null instead of a guessed code. The text names no grade, place, or salary: they stay unknown with null value and source, and the critical ones are listed in missing_fields with a question. Without a confirmed skill there are no recommendations yet." + value: + id: 01928f7a-3c4d-7e5f-8a6b-7c8d9e0f1a23 + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + vacancy_id: null + title: Backend в команду платежей + source_text: "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно." + version: 1 + requirements_version: 1 + requirements: + specialization: + status: extracted + value: backend + source: + origin: extracted_from_text + quote: Ищем бэкенд-разработчика + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + grade: + status: unknown + value: null + source: null + required_skills: + - name: Go + taxonomy_code: go + status: extracted + source: + origin: extracted_from_text + quote: "Обязательно: Go, PostgreSQL и Temporal" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: PostgreSQL + taxonomy_code: postgresql + status: extracted + source: + origin: extracted_from_text + quote: "Обязательно: Go, PostgreSQL и Temporal" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: Temporal + taxonomy_code: null + status: extracted + source: + origin: extracted_from_text + quote: "Обязательно: Go, PostgreSQL и Temporal" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + desired_skills: + - name: Kafka + taxonomy_code: kafka + status: extracted + source: + origin: extracted_from_text + quote: Желательно опыт с Kafka + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + tasks: + - text: Развивать сервис выплат и переводить его на событийную модель + status: extracted + source: + origin: extracted_from_text + quote: "Задачи: развивать сервис выплат и переводить его на событийную модель" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + domain: + status: extracted + value: платежи + source: + origin: extracted_from_text + quote: в команду платежей + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + work_formats: + status: extracted + value: + - remote + source: + origin: extracted_from_text + quote: Работа удаленно + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + location: + status: unknown + value: null + source: null + salary: + status: unknown + value: null + source: null + readiness: + status: incomplete + missing_fields: + - field: specialization + reason: unconfirmed + question: Подтвердите специализацию, найденную в описании. + - field: grade + reason: unknown + question: "Какой грейд нужен: Intern, Junior, Middle или Senior?" + - field: required_skills + reason: unconfirmed + question: Подтвердите обязательные навыки, найденные в описании. + - field: work_formats + reason: unconfirmed + question: Подтвердите формат работы, найденный в описании. + - field: salary + reason: unknown + question: "Какую вилку в рублях вы предлагаете и в какой базе: на руки или до вычета НДФЛ?" + recommendations: + status: not_available + requirements_version: 1 + policy_version: null + algorithm_version: null + computed_at: null + categories: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" +NeedUpdateConfirmSuggestions: + summary: Confirm suggestions, answer the missing fields, and keep two suggestions open + description: Sent over version 1 of NeedExtractedWithUnknownSkill. The specialization, the required skills, and the work format are sent with their stored values and status confirmed, so they are confirmed and keep their quotes. The grade and the salary are new manual values. Kafka and the domain are sent with status extracted and their stored values, so they stay open suggestions. The tasks are absent and stay unchanged. + value: + expected_version: 1 + specialization: + value: backend + status: confirmed + grade: + value: middle + status: confirmed + required_skills: + - name: Go + status: confirmed + - name: PostgreSQL + status: confirmed + - name: Temporal + status: confirmed + desired_skills: + - name: Kafka + status: extracted + domain: + value: платежи + status: extracted + work_formats: + value: + - remote + status: confirmed + salary: + value: + salary_from: 250000 + salary_to: 320000 + currency: RUB + period: month + tax_basis: gross + status: confirmed +NeedConfirmedAfterUpdate: + summary: The need after the confirmation, as version 2 + description: Confirmed suggestions keep the origin extracted_from_text, their quotes, and extracted_in_version 1; the grade and the salary are manual. A confirmed requirement changed, so requirements_version is 2 as well. Kafka and the domain are still open suggestions; Kafka does not count in the recommendations, and Temporal stays without a taxonomy code, so no category covers it. The place is unknown but not critical, because the only format is remote. The range of 250000-320000 has a width of about 25%. Scores use the overlap 4/6, the money share rounded down to a quarter or the neutral 0.5, and the exact Supply of groups of five or more. The recommendation values are illustrative. + value: + id: 01928f7a-3c4d-7e5f-8a6b-7c8d9e0f1a23 + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + vacancy_id: null + title: Backend в команду платежей + source_text: "Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно." + version: 2 + requirements_version: 2 + requirements: + specialization: + status: confirmed + value: backend + source: + origin: extracted_from_text + quote: Ищем бэкенд-разработчика + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + grade: + status: confirmed + value: middle + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + required_skills: + - name: Go + taxonomy_code: go + status: confirmed + source: + origin: extracted_from_text + quote: "Обязательно: Go, PostgreSQL и Temporal" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: PostgreSQL + taxonomy_code: postgresql + status: confirmed + source: + origin: extracted_from_text + quote: "Обязательно: Go, PostgreSQL и Temporal" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: Temporal + taxonomy_code: null + status: confirmed + source: + origin: extracted_from_text + quote: "Обязательно: Go, PostgreSQL и Temporal" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + desired_skills: + - name: Kafka + taxonomy_code: kafka + status: extracted + source: + origin: extracted_from_text + quote: Желательно опыт с Kafka + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + tasks: + - text: Развивать сервис выплат и переводить его на событийную модель + status: extracted + source: + origin: extracted_from_text + quote: "Задачи: развивать сервис выплат и переводить его на событийную модель" + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + domain: + status: extracted + value: платежи + source: + origin: extracted_from_text + quote: в команду платежей + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + work_formats: + status: confirmed + value: + - remote + source: + origin: extracted_from_text + quote: Работа удаленно + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + location: + status: unknown + value: null + source: null + salary: + status: confirmed + value: + salary_from: 250000 + salary_to: 320000 + currency: RUB + period: month + tax_basis: gross + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + recommendations: + status: computed + requirements_version: 2 + policy_version: 1 + algorithm_version: need-rec.2026-10.1 + computed_at: "2026-10-06T09:20:01Z" + categories: + - specialization: backend + grade: middle + score: 0.61 + skill_overlap: + share: 0.67 + covered_skills: + - Go + - PostgreSQL + uncovered_skills: + - Temporal + money: + status: computed + share: 0.25 + supply: 30_or_more + - specialization: devops_sre + grade: middle + score: 0.45 + skill_overlap: + share: 0.33 + covered_skills: + - PostgreSQL + uncovered_skills: + - Go + - Temporal + money: + status: insufficient_data + share: null + supply: from_5_to_29 + - specialization: backend + grade: senior + score: 0.41 + skill_overlap: + share: 0.67 + covered_skills: + - Go + - PostgreSQL + uncovered_skills: + - Temporal + money: + status: computed + share: 0 + supply: from_5_to_29 + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:20:00Z" +NeedListPage: + summary: The last page of the needs of an organization + value: + items: + - id: 01928f7a-3c4d-7e5f-8a6b-7c8d9e0f1a23 + vacancy_id: null + title: Backend в команду платежей + version: 2 + specialization: + status: confirmed + value: backend + source: + origin: extracted_from_text + quote: Ищем бэкенд-разработчика + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + grade: + status: confirmed + value: middle + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:20:00Z" + - id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + vacancy_id: null + title: Junior Go-разработчик для сервиса уведомлений + version: 1 + specialization: + status: confirmed + value: backend + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + grade: + status: confirmed + value: junior + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + created_at: "2026-10-06T08:15:00Z" + updated_at: "2026-10-06T08:15:00Z" + page: + has_more: false + next_cursor: null +NeedSalaryRangeReversed: + summary: The lower salary bound is above the upper one + 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: 6b7c8d9e-0f1a-4b2c-8d3e-4f5a6b7c8d9f + errors: + - in: body + pointer: /salary/value/salary_to + code: invalid + message: The value does not match the contract. +NeedSalaryEqualBounds: + summary: Equal salary bounds; PRD FR13 requires salary_from < salary_to + 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: 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d + errors: + - in: body + pointer: /salary/value/salary_to + code: invalid + message: The value does not match the contract. +NeedSalaryRangeTooWide: + summary: A salary range wider than 40% of its midpoint, such as 100000-200000 + description: The width (200000 - 100000) / 150000 is about 67%. A range narrower than 10%, such as 100000-105000, gets the same answer. + 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: 2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e + errors: + - in: body + pointer: /salary/value/salary_to + code: invalid + message: The value does not match the contract. +NeedSalaryWithoutTaxBasis: + summary: A salary range without its tax basis + description: The responder rebuilds the path of a missing nested field from the decoder, so the pointer names the missing field. + 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: 7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0a + errors: + - in: body + pointer: /salary/value/tax_basis + code: required + message: The value is required. +NeedExtractedValueMismatch: + summary: Status extracted with a value that is not the stored suggestion + description: A request may keep only the stored suggestion unconfirmed. To set another value, it sends status confirmed. + 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: 3c4d5e6f-7a8b-4c9d-8e0f-2a3b4c5d6e7f + errors: + - in: body + pointer: /grade/status + code: invalid + message: The value does not match the contract. +NeedUnknownField: + summary: The client sent its own recommendation score + description: Recommendations, membership, and candidate minimums are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. + 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: 8d9e0f1a-2b3c-4d4e-8f5a-6b7c8d9e0f1b + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +NeedMissingExpectedVersion: + summary: A change without expected_version + 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: 9e0f1a2b-3c4d-4e5f-9a6b-7c8d9e0f1a2c + errors: + - in: body + pointer: /expected_version + code: required + message: The value is required. +NeedStaleVersion: + summary: The change carried a stale expected_version + description: Another member or a server-side extraction changed the need after the client read it. Nothing was changed; the client reads the need again and reapplies its unsaved edits. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d +SupportCaseCreateManualAssessment: + summary: A manual assessment of a category instead of the automated one + value: + type: manual_assessment + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + assessment_target: + specialization: backend + grade: middle +SupportCaseCreateGradeAppeal: + summary: An appeal of the result of an own attempt + value: + type: grade_appeal + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b +SupportCaseCreateCategoryAppeal: + summary: An appeal of a category that a manual assessment assigned + description: The category came from an expert without an attempt, so the appeal references the resolved manual assessment case. + value: + type: grade_appeal + description: Эксперт подтвердил Junior, но в рубрике Middle я выполнил все обязательные пункты. Прошу пересмотреть. + object: + type: support_case + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d +SupportCaseCreateTestUnavailable: + summary: A support case about a test that is not available + value: + type: support + description: Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + assessment_target: + specialization: backend + grade: senior +SupportCaseCreateComplaint: + summary: A complaint about the salary terms of an offer + value: + type: complaint + description: После принятия приглашения компания предложила сумму ниже указанной вилки. + complaint_reason: salary_terms_violation + object: + type: invitation + id: 01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e +SupportCaseManualAssessmentCreated: + summary: A new manual assessment request with its rubric and response target + description: The server moves the case to waiting_expert in the same transaction as the creation, so the 201 already shows both events. + value: + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + object: null + assessment_target: + specialization: backend + grade: middle + complaint_reason: null + rubric_version: 3 + response_target: + kind: operational_goal + business_days: 5 + due_at: "2026-10-13T09:00:00Z" + answered_at: null + late: false + policy_version: 1 + decision: null + history: + - sequence: 1 + kind: created + actor: user + occurred_at: "2026-10-06T09:00:00Z" + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: "2026-10-06T09:00:00Z" + status: waiting_expert + message: null + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" +SupportCaseGradeAppealResolved: + summary: An own grade appeal with a public decision + value: + id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + complaint_reason: null + rubric_version: null + response_target: + kind: operational_goal + business_days: 10 + due_at: "2026-10-15T10:00:00Z" + answered_at: "2026-10-09T14:30:00Z" + late: false + policy_version: 1 + decision: + outcome: not_upheld + reason: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + decided_at: "2026-10-09T14:30:00Z" + history: + - sequence: 1 + kind: created + actor: user + occurred_at: "2026-10-01T10:00:00Z" + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: "2026-10-01T10:00:00Z" + status: waiting_expert + message: null + - sequence: 3 + kind: status_changed + actor: support + occurred_at: "2026-10-07T08:15:00Z" + status: in_review + message: null + - sequence: 4 + kind: decision + actor: support + occurred_at: "2026-10-09T14:30:00Z" + status: resolved + message: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + created_at: "2026-10-01T10:00:00Z" + updated_at: "2026-10-09T14:30:00Z" +SupportCaseListPage: + summary: The last page of the case summaries of the current account + value: + items: + - id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + object: null + assessment_target: + specialization: backend + grade: middle + response_target: + kind: operational_goal + business_days: 5 + due_at: "2026-10-13T09:00:00Z" + answered_at: null + late: false + policy_version: 1 + decision_outcome: null + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" + - id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + response_target: + kind: operational_goal + business_days: 10 + due_at: "2026-10-15T10:00:00Z" + answered_at: "2026-10-09T14:30:00Z" + late: false + policy_version: 1 + decision_outcome: not_upheld + created_at: "2026-10-01T10:00:00Z" + updated_at: "2026-10-09T14:30:00Z" + - id: 01928f7a-4c5d-7e6f-8a9b-0c1d2e3f4a5b + number: SC-2026-000088 + type: support + status: in_review + object: null + assessment_target: + specialization: backend + grade: senior + response_target: + kind: operational_goal + business_days: 3 + due_at: "2026-10-02T12:00:00Z" + answered_at: "2026-10-01T09:20:00Z" + late: false + policy_version: 1 + decision_outcome: null + created_at: "2026-09-29T12:00:00Z" + updated_at: "2026-10-01T09:20:00Z" + page: + has_more: false + next_cursor: null +SupportCaseBlankDescription: + summary: The description is empty or contains only whitespace + 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: 5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d + errors: + - in: body + pointer: /description + code: invalid + message: The value does not match the contract. +SupportCaseUnknownType: + summary: The case type is not one of the five types + description: An unknown discriminator of the top-level oneOf concerns the whole body, so the pointer is empty. + 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: 6b7c8d9e-0f1a-4b2c-9d3e-4f5a6b7c8d9e + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +SupportCaseUnknownField: + summary: The client sent its own status or decision + description: Status, decision, moderator, priority, and response target are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. + 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: 7c8d9e0f-1a2b-4c3d-8e4f-5a6b7c8d9e0f + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +SupportCaseMalformedReference: + summary: The object identifier is not a UUID + description: The decoder rejects the identifier inside the selected variant, and the pointer names it. + 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: 0f1a2b3c-4d5e-4f6a-9b7c-8d9e0f1a2b3c + errors: + - in: body + pointer: /object/id + code: invalid + message: The value does not match the contract. +SupportCaseComplaintNeedsInvitation: + summary: The complaint reason requires an invitation reference + 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: 8d9e0f1a-2b3c-4d4e-9f5a-6b7c8d9e0f1a + errors: + - in: body + pointer: /object/type + code: invalid + message: The value does not match the contract. +SupportCaseAppealExists: + summary: The attempt or the manual assessment already has an appeal of this type + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b +InvitationCreateFromNeed: + summary: A draft for a candidate from the search results of a need + description: "Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided." + value: + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + response_period_days: 7 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока +InvitationUpdateTerms: + summary: The draft gets the training condition; the terms are sent complete + value: + expected_version: 1 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока +InvitationSendCommand: + summary: Send the draft that the client read as version 2 + value: + expected_version: 2 +InvitationSalaryRaiseCommand: + summary: The one raise of the upper bound from 260000 to 280000 net + value: + expected_version: 4 + salary_to: 280000 +InvitationWithdrawCommand: + summary: Withdraw the invitation that the client read as version 3 + value: + expected_version: 3 +InvitationAcceptEmailOnly: + summary: Accept terms version 3 and disclose only the email address + value: + expected_version: 5 + terms_version: 3 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email +InvitationAcceptStaleTerms: + summary: Accept terms version 2 after the organization raised the salary + description: The candidate read version 4 with terms version 2; the raise made version 5 with terms version 3, so the server answers 412. + value: + expected_version: 4 + terms_version: 2 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email + - phone +InvitationDeclineOther: + summary: Decline with the neutral reason other and no comment + value: + expected_version: 4 + reason: other +InvitationDeclineWithComment: + summary: Decline with a reason and an optional comment + value: + expected_version: 4 + reason: work_format + comment: Ищу только полностью удаленную работу. +InvitationCancelCommand: + summary: Cancel the participation after the acceptance + value: + expected_version: 6 +OrganizationInvitationDraft: + summary: A new draft, version 1 with terms version 1 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 1 + terms_version: 1 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" + delivered_at: null + viewed_at: null + responded_at: null +OrganizationInvitationDraftUpdated: + summary: The draft after the terms change, version 2 with terms version 2 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 2 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:20:00Z" + delivered_at: null + viewed_at: null + responded_at: null +OrganizationInvitationDelivered: + summary: The invitation in the candidate's inbox with a seven-day deadline + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: null + responded_at: null +OrganizationInvitationSalaryRaised: + summary: "The viewed invitation after the one raise of the upper bound: terms version 3" + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: viewed + expiry_reason: null + version: 5 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: true + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T14:00:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: null +OrganizationInvitationAccepted: + summary: "The accepted invitation: the email address is readable through the contacts operation" + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: true + salary_fit: within_range + contact_access: + status: available + fields: + - email + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" +OrganizationInvitationWithdrawn: + summary: The invitation withdrawn by the organization before an answer + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: withdrawn + expiry_reason: null + version: 4 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: "2026-10-13T09:30:00Z" + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T11:00:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: null + responded_at: null +OrganizationInvitationListPage: + summary: The last page of the invitations of an organization + description: The organization sees that the second invitation was declined, but not the reason or the comment. + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: "2026-10-13T09:30:00Z" + contact_access: + status: available + fields: + - email + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB + need: null + state: declined + expiry_reason: null + version: 4 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: "2026-10-08T10:00:00Z" + contact_access: + status: not_granted + fields: [] + created_at: "2026-10-05T09:00:00Z" + updated_at: "2026-10-06T08:00:00Z" + page: + has_more: false + next_cursor: null +CandidateInvitationDelivered: + summary: The delivered invitation as GetMyInvitation reads it, before a view is recorded + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: null + responded_at: null + updated_at: "2026-10-06T09:30:00Z" + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null +CandidateInvitationViewed: + summary: The terms after ViewMyInvitation, with the C4 choice and no contact + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: null + updated_at: "2026-10-06T12:00:00Z" + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null +CandidateInvitationAcceptedVisibilityBlocked: + summary: "Accepted while the profile is hidden from the organization: the grant is active but not readable" + description: The acceptance never lifts the hiding or publishes the profile. The organization sees contact_access closed without the reason. + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: active + readable: false + blocked_by: visibility + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: "2026-10-06T15:00:00Z" + revoked_at: null + revocation_reason: null +CandidateInvitationAccepted: + summary: The accepted invitation with the grant for the email address only + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" + updated_at: "2026-10-06T15:00:00Z" + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: active + readable: true + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: "2026-10-06T15:00:00Z" + revoked_at: null + revocation_reason: null +CandidateInvitationDeclined: + summary: The declined invitation with the candidate's own reason + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: declined + expiry_reason: null + version: 5 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T16:00:00Z" + updated_at: "2026-10-06T16:00:00Z" + contact_consent: null + decline: + reason: other + comment: null + declined_at: "2026-10-06T16:00:00Z" + contact_grant: null +CandidateInvitationCancelled: + summary: The participation cancelled after the acceptance; the grant of this invitation is revoked + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: cancelled_by_candidate + expiry_reason: null + version: 7 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: "Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель." + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + responded_at: "2026-10-06T15:00:00Z" + updated_at: "2026-10-07T10:00:00Z" + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: revoked + readable: false + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: "2026-10-06T15:00:00Z" + revoked_at: "2026-10-07T10:00:00Z" + revocation_reason: participation_cancelled +CandidateInvitationListPage: + summary: The last page of the candidate's inbox + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: "2026-10-13T09:30:00Z" + delivered_at: "2026-10-06T09:30:00Z" + viewed_at: "2026-10-06T12:00:00Z" + updated_at: "2026-10-06T12:00:00Z" + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: expired + expiry_reason: invitation_timeout + version: 3 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: "2026-10-04T10:00:00Z" + delivered_at: "2026-10-01T10:00:00Z" + viewed_at: null + updated_at: "2026-10-04T10:00:00Z" + page: + has_more: false + next_cursor: null +InvitationContactsEmailOnly: + summary: Synthetic contacts through a grant that covers only the email address + description: Every field the grant does not cover is null. The values are synthetic. + value: + invitation_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + grant_id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + granted_at: "2026-10-06T15:00:00Z" + full_name: null + email: candidate@example.com + phone: null + telegram: null +InvitationWithoutTaxBasis: + summary: A salary range without its tax basis + description: The tax basis is a required field of SalaryRange; the pointer names the missing nested field. + 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: 1f2a3b4c-5d6e-4f7a-8b9c-0d1e2f3a4b5c + errors: + - in: body + pointer: /terms/salary/tax_basis + code: required + message: The value is required. +InvitationWithoutCommunicationMethod: + summary: Terms without the communication method + description: The communication method is a required term; the pointer names the missing nested field. + 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: 2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d + errors: + - in: body + pointer: /terms/communication_method + code: required + message: The value is required. +InvitationPackageItemMissing: + summary: A package without the training condition + description: "Not providing a condition is the explicit item {status: not_provided}; leaving it out is a missing required field." + 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: 3b4c5d6e-7f8a-4b9c-8d0e-2f3a4b5c6d7e + errors: + - in: body + pointer: /terms/package/training + code: required + message: The value is required. +InvitationSalaryRangeTooWide: + summary: A salary range wider than 40% of its midpoint + 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: 4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f + errors: + - in: body + pointer: /terms/salary/salary_to + code: invalid + message: The value does not match the contract. +InvitationLocationRequired: + summary: The hybrid format without a place of work + 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-4b5c6d7e8f9a + errors: + - in: body + pointer: /terms/location + code: invalid + message: The value does not match the contract. +InvitationUnknownCandidate: + summary: A candidate handle that this organization cannot use + description: An unknown handle, a handle of another organization, and a profile that is no longer visible to the organization get the same answer. + 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: 6e7f8a9b-0c1d-4e2f-9a3b-5c6d7e8f9a0b + errors: + - in: body + pointer: /candidate_handle + code: invalid + message: The value does not match the contract. +InvitationCandidateDataInBody: + summary: The request carried a candidate's email address or salary minimum + description: Contacts and minimums are never request fields; any unknown field fails validation, and an unknown top-level field such as candidate_email points at the whole body. + 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: 7f8a9b0c-1d2e-4f3a-8b4c-6d7e8f9a0b1c + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +InvitationConsentWithoutFields: + summary: An acceptance with an empty choice of contact fields + 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: 8a9b0c1d-2e3f-4a4b-9c5d-7e8f9a0b1c2d + errors: + - in: body + pointer: /consent_c4/fields + code: invalid + message: The value does not match the contract. +InvitationConsentTextOutdated: + summary: An acceptance of a C4 text version that is no longer published + 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-8f9a0b1c2d3e + errors: + - in: body + pointer: /consent_c4/text_version + code: invalid + message: The value does not match the contract. +InvitationMissingTermsVersion: + summary: An acceptance without terms_version + 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: 0c1d2e3f-4a5b-4c6d-9e7f-9a0b1c2d3e4f + errors: + - in: body + pointer: /terms_version + code: required + message: The value is required. +InvitationStaleTerms: + summary: The acceptance named a terms version that is no longer current + description: The organization raised the salary after the candidate read the terms. Nothing changed and no consent or grant was recorded; the client reads the invitation again and shows the new terms for a new decision. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 1d2e3f4a-5b6c-4d7e-8f8a-0b1c2d3e4f5a +InvitationStaleVersion: + summary: The command carried a stale expected_version + description: The invitation changed after the client read it. Nothing changed; the client reads the invitation again. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 2e3f4a5b-6c7d-4e8f-9a9b-1c2d3e4f5a6b +InvitationNotAnswerable: + summary: The invitation no longer accepts an answer + description: For example, it was withdrawn, it expired, or the deadline has passed. + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3f4a5b6c-7d8e-4f9a-8b0c-2d3e4f5a6b7c +InvitationSalaryRaiseUsed: + summary: The upper bound of this invitation was already raised once + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4a5b6c7d-8e9f-4a0b-9c1d-3e4f5a6b7c8d +InvitationSendBlocked: + summary: The send is blocked by the pending limit of the need or the pause after a decline + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5b6c7d8e-9f0a-4b1c-8d2e-4f5a6b7c8d9e +ConsentRecordListPage: + summary: The whole consent history of a candidate on one page + description: C1 was accepted at registration and again for a newer text version, so the first record is superseded; the version c1-2026-10-05 is an illustration, since the migration publishes only c1-2026-10-01 so far. C2 was granted and revoked. C4 was given in the acceptance of one invitation with the email only; the organization name is the one the consent text showed. + value: + items: + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + purpose: c4 + state: active + text_version: c4-2026-10-01 + source: invitation_acceptance + granted_at: "2026-10-06T10:15:00Z" + revoked_at: null + revocation_source: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + fields: + - email + invitation_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + invitation_terms_version: 3 + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + purpose: c1 + state: active + text_version: c1-2026-10-05 + source: consent_settings + granted_at: "2026-10-05T12:00:00Z" + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + purpose: c2 + state: revoked + text_version: c2-2026-10-01 + source: consent_settings + granted_at: "2026-10-02T09:00:00Z" + revoked_at: "2026-10-04T18:30:00Z" + revocation_source: consent_settings + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-6f7a-7b8c-9d0e-1f2a3b4c5d50 + purpose: c1 + state: superseded + text_version: c1-2026-10-01 + source: registration + granted_at: "2026-10-01T08:00:00Z" + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + page: + has_more: false + next_cursor: null +OrganizationCreateNameOnly: + summary: A company that starts with its name only + description: Only the name is required; the card is completed later with UpdateOrganization. + value: + name: ООО Пример Платежи +OrganizationCreateCompleteCard: + summary: A company that gives its whole card at creation + description: Every contact is a company channel, and the representative is presentation only. There is no field for a role or a verification level. + value: + name: ООО Пример Платежи + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: "+74950000000" + telegram: "@payments_careers" + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору +OrganizationNameOnly: + summary: A new organization that has only a name + description: The creator is the owner of the organization, which starts at the verification level e0 on the ground of the confirmed email. The card repeats the profile as a candidate sees it. + value: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + version: 1 + name: ООО Пример Платежи + description: null + sphere: null + contacts: + website: null + email: null + phone: null + telegram: null + representatives: [] + verification: + level: e0 + basis: confirmed_email + changed_at: "2026-10-06T09:00:00Z" + candidate_card: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + description: null + sphere: null + contacts: + website: null + email: null + phone: null + telegram: null + representatives: [] + verification_level: e0 + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:00:00Z" +OrganizationCompleteCard: + summary: An organization with a complete card, still at the level e0 + description: Completing the card, adding contacts, and listing representatives did not raise the verification level, which stays e0 and changes only through a verification process of the server. + value: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + version: 2 + name: ООО Пример Платежи + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: "+74950000000" + telegram: "@payments_careers" + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору + verification: + level: e0 + basis: confirmed_email + changed_at: "2026-10-06T09:00:00Z" + candidate_card: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: "+74950000000" + telegram: "@payments_careers" + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору + verification_level: e0 + created_at: "2026-10-06T09:00:00Z" + updated_at: "2026-10-06T09:40:00Z" +OrganizationUpdateCompleteCard: + summary: The owner completes the card of the organization + description: The change carries the version that the client read and the fields to replace; contacts and representatives are replaced as a whole. The body has no role or verification field. + value: + expected_version: 1 + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: "+74950000000" + telegram: "@payments_careers" + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору +MyOrganizationListPage: + summary: The organizations of an owner who works in two companies + description: The caller has an active membership in both organizations, newest first. A third organization, where the caller left, is not listed. + value: + items: + - organization: + id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c + name: ИП Тестов Логистика + verification_level: e0 + membership: + organization_id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c + role: owner + state: active + joined_at: "2026-10-06T11:30:00Z" + - organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + verification_level: e0 + membership: + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + role: owner + state: active + joined_at: "2026-10-06T09:00:00Z" + page: + has_more: false + next_cursor: null +OrganizationUnknownField: + summary: The client sent a role together with the profile + description: A role, an owner, a verification level, and a list of members are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. + 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: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5c + errors: + - in: body + pointer: "" + code: invalid + message: The value does not match the contract. +OrganizationWebsiteNotHttps: + summary: The website is not an https URL of a host name + description: A domain rule of the server, checked after the schema. The schema already refuses a value that is not an https URL; the server also refuses a port, an IP address, and a host name without a dot. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6d + errors: + - in: body + pointer: /contacts/website + code: invalid + message: The value does not match the contract. +OrganizationNameWithWhitespace: + summary: The name has leading whitespace + 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: 3a4b5c6d-7e8f-4a9b-8c1d-2e3f4a5b6c7e + errors: + - in: body + pointer: /name + code: invalid + message: The value does not match the contract. +OrganizationMissingExpectedVersion: + summary: A change without expected_version + 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: 4b5c6d7e-8f9a-4b0c-9d2e-3f4a5b6c7d8f + errors: + - in: body + pointer: /expected_version + code: required + message: The value is required. +OrganizationStaleVersion: + summary: The change carried a stale expected_version + description: Another member changed the organization after the client read it. Nothing was changed; the client reads the organization again and reapplies its edits. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5c6d7e8f-9a0b-4c1d-8e3f-4a5b6c7d8e90 +NewCandidateProfile: + summary: A candidate who has not saved the profile yet + value: + version: 0 + full_name: + status: unknown + value: null + source: null + contacts: + email: + status: unknown + value: null + source: null + phone: + status: unknown + value: null + source: null + telegram: + status: unknown + value: null + source: null + stack: [] + roles: [] + experience: [] + experience_overlaps: [] + soft_skills: [] + projects: [] + terms: + location: + status: unknown + value: null + source: null + relocation: + status: unknown + value: null + source: null + salary_minimum: + status: unknown + value: null + source: null + confirmed_categories: [] + updated_at: null +BackendCandidateProfile: + summary: A manual Backend profile with one unconfirmed suggestion + description: >- + The candidate typed most values, so they are `manual`. The phone number + and the Kafka tag are suggestions that an imported document produced + (planned): they are `extracted`, unconfirmed, and, like every claim, + trust level 0. The candidate claims Middle in `roles`, while the only + confirmed category is Backend Junior from an assessment result; the two + are separate fields and the profile never merges them. The example + values are fictional. + value: + version: 3 + full_name: + status: confirmed + value: Anna Sokolova + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + contacts: + email: + status: confirmed + value: anna.sokolova@example.com + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + phone: + status: extracted + value: "+79000000000" + source: + origin: extracted_from_resume + trust_level: 0 + quote: "Tel.: +7 900 000-00-00" + extraction_version: resume-rules.2026-10.1 + confirmed_at: null + telegram: + status: unknown + value: null + source: null + stack: + - tag: PostgreSQL + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + - tag: Kafka + status: extracted + source: + origin: extracted_from_resume + trust_level: 0 + quote: "Event streaming with Kafka" + extraction_version: resume-rules.2026-10.1 + confirmed_at: null + roles: + - specialization: backend + self_assessed_grade: middle + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + experience: + - employer_name: Example Payments + specialization: backend + started_on: "2022-03" + ended_on: null + summary: Moved the payout service to an event model and owned its on-call rotation. + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + experience_overlaps: [] + soft_skills: + - skill: Mentoring + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + projects: + - title: Payment webhook deduplication service + description: >- + Idempotent receiver for acquirer callbacks with a unique operation + key and an outbox for retries. + stack: + - Go + - PostgreSQL + repository_url: https://github.com/example-org/payments-ledger + repository_check: + state: verified + checked_at: "2026-10-05T09:31:00Z" + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + terms: + location: + status: confirmed + value: Kazan + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + relocation: + status: confirmed + value: false + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + salary_minimum: + status: confirmed + value: + amount: 180000 + currency: RUB + period: month + tax_basis: net + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: "2026-10-05T09:30:00Z" + confirmed_categories: + - specialization: backend + grade: junior + basis: synthetic_demo + confirmed_at: "2026-10-04T18:10:00Z" + attempt_id: 0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b + updated_at: "2026-10-05T09:30:00Z" +BackendCandidateProfileUpdate: + summary: Save the Backend profile over version 2 + description: >- + The candidate keeps the phone number and the Kafka tag as unconfirmed + suggestions by sending `extracted` with exactly their stored values, and + confirms or sets everything else. The values are fictional. + value: + expected_version: 2 + full_name: + value: Anna Sokolova + status: confirmed + contacts: + email: + value: anna.sokolova@example.com + status: confirmed + phone: + value: "+79000000000" + status: extracted + telegram: null + stack: + - tag: PostgreSQL + status: confirmed + - tag: Kafka + status: extracted + roles: + - specialization: backend + self_assessed_grade: middle + status: confirmed + experience: + - employer_name: Example Payments + specialization: backend + started_on: "2022-03" + ended_on: null + summary: Moved the payout service to an event model and owned its on-call rotation. + status: confirmed + soft_skills: + - skill: Mentoring + status: confirmed + terms: + location: + value: Kazan + status: confirmed + relocation: + value: false + status: confirmed + salary_minimum: + value: + amount: 180000 + currency: RUB + period: month + tax_basis: net + status: confirmed +ProfilePhoneNotE164: + summary: The phone number is not in the E.164 format + description: A rule of the schema. The pointer names the value inside the decision, and the body never repeats the submitted number. + 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: 6d7e8f9a-0b1c-4d2e-8f4a-5b6c7d8e9f01 + errors: + - in: body + pointer: /contacts/phone/value + code: invalid + message: The value does not match the contract. +ProfileExtractedValueChanged: + summary: A decision extracted for a tag that is not a stored suggestion + description: A domain rule of the server, checked after the schema. A suggestion can stay unconfirmed only with exactly its stored value; send confirmed to set a manual value. + 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: 7e8f9a0b-1c2d-4e3f-9a5b-6c7d8e9f0a12 + errors: + - in: body + pointer: /stack/1/status + code: invalid + message: The value does not match the contract. +ProfileRepeatedRole: + summary: The same specialization appears in two roles + 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: 8f9a0b1c-2d3e-4f4a-8b6c-7d8e9f0a1b23 + errors: + - in: body + pointer: /roles/1/specialization + code: invalid + message: The value does not match the contract. +ProfileStaleVersion: + summary: The save carried a stale expected_version + description: The profile changed, for example in another tab, after the client read it. Nothing was changed; the client reads the profile again and reapplies its edits. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 9a0b1c2d-3e4f-4a5b-9c7d-8e9f0a1b2c34 +PrivacyPublishedWithoutFields: + summary: A publication without any field + 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: 3b4c5d6e-7f80-4a91-8b2c-3d4e5f6a7b8c + errors: + - in: body + pointer: /fields + code: invalid + message: A published profile needs at least one field, and a closed one none. +NewCandidatePrivacySettings: + summary: A new candidate with the profile closed + description: Nothing was ever published, announced, or hidden. Every version is 0. + value: + publication: + state: closed + closed_reason: never_published + fields: [] + consent_id: null + published_at: null + version: 0 + search_status: + value: not_looking + lapsed: false + confirmed_at: null + lapses_at: null + version: 0 + hidden_organizations_total: 0 +PublishedCandidatePrivacySettings: + summary: A published profile with a confirmed search status + value: + publication: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: "2026-10-06T09:10:00Z" + version: 1 + search_status: + value: looking + lapsed: false + confirmed_at: "2026-10-06T09:12:00Z" + lapses_at: "2026-11-05T09:12:00Z" + version: 1 + hidden_organizations_total: 1 +PublicationUpdatePublish: + summary: Publish the confirmed categories and the stack + value: + expected_version: 0 + state: published + fields: + - categories + - stack +PublicationUpdateClose: + summary: Close the publication + value: + expected_version: 1 + state: closed + fields: [] +PublishedPublication: + summary: The publication after the first publish + value: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: "2026-10-06T09:10:00Z" + version: 1 +SearchStatusUpdateLooking: + summary: Set or confirm the status looking + value: + expected_version: 0 + value: looking +LookingSearchStatus: + summary: A confirmed status that lapses after the policy interval + value: + value: looking + lapsed: false + confirmed_at: "2026-10-06T09:12:00Z" + lapses_at: "2026-11-05T09:12:00Z" + version: 1 +LapsedSearchStatus: + summary: A status that was not confirmed in time + description: The candidate set looking and did not confirm it again, so it holds as not_looking. Nothing else changed; the publication and the hidden organizations are as they were. + value: + value: not_looking + lapsed: true + confirmed_at: "2026-10-06T09:12:00Z" + lapses_at: "2026-11-05T09:12:00Z" + version: 1 +HiddenOrganizationRecord: + summary: An organization that the candidate hides the profile from + value: + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: "2026-10-06T09:20:00Z" +HiddenOrganizationListPage: + summary: One hidden organization + value: + items: + - organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: "2026-10-06T09:20:00Z" + page: + has_more: false + next_cursor: null +PublishedCardPreview: + summary: The card of a published profile with two fields + description: The fields that are not published are null. The card carries no name and no contact. + value: + state: published + fields: + - categories + - stack + card: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + categories: + - specialization: backend + grade: middle + strength: standard + basis: synthetic_demo + stack: + - postgresql + - kafka + self_assessment: null + experience_band: "1_3" + work_formats: null + salary_compatibility: null + projects: null + evidence: + items: + - skill: backend + grade: middle + trust: 1 + basis: synthetic_demo + calibration_status: uncalibrated + observed_year: 2026 + generated_at: "2026-10-06T09:30:00Z" +OrganizationAnonymousCandidateCard: + summary: An anonymous card currently visible to one organization + description: The alias is scoped to the reading organization; no contact values are included. + value: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + categories: + - specialization: backend + grade: middle + strength: standard + basis: synthetic_demo + stack: + - postgresql + - kafka + self_assessment: null + experience_band: "1_3" + work_formats: null + salary_compatibility: null + projects: null +ClosedCardPreview: + summary: The preview of a closed profile + value: + state: closed + fields: [] + card: null + evidence: null + generated_at: "2026-10-06T09:30:00Z" +PrivacyEventListPage: + summary: A publication, a hiding, and a confirmed status + value: + items: + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9f01 + kind: organization_hidden + occurred_at: "2026-10-06T09:20:00Z" + fields: null + consent_id: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e02 + kind: search_status_confirmed + occurred_at: "2026-10-06T09:12:00Z" + fields: null + consent_id: null + organization: null + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e01 + kind: publication_opened + occurred_at: "2026-10-06T09:10:00Z" + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + organization: null + page: + has_more: false + next_cursor: null +CardAccessListPage: + summary: An anonymous view and a contact read + value: + items: + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a02 + kind: contact_read + occurred_at: "2026-10-07T08:00:00Z" + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a01 + kind: card_viewed + occurred_at: "2026-10-06T12:00:00Z" + organization: null + page: + has_more: false + next_cursor: null +EvidenceFactListPage: + summary: A confirmed junior backend result with one fact and two tags of the same event + value: + items: + - id: 01928f7a-d1e2-7f3a-8b4c-5d6e7f8a9b01 + kind: measurement + source: + type: assessment_result + event_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01 + result_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01 + skills: + - backend + - go + result: + grade: junior + basis: synthetic_demo + calibration_status: uncalibrated + attribution: personal + trust: 1 + occurred_at: "2026-10-08T10:15:00Z" + visibility: visible + page: + has_more: false + next_cursor: null +OrganizationCandidateEvidence: + summary: The one supporting assessment fact of the category on the card + value: + items: + - skill: backend + grade: junior + trust: 1 + basis: synthetic_demo + calibration_status: uncalibrated + observed_year: 2026 +PrivacyStaleVersion: + summary: The change carried a stale expected_version + description: The setting changed, for example in another tab, after the client read it. Nothing was changed; the client reads the settings again and reapplies its edit. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 4c5d6e7f-8091-4ba2-9c3d-4e5f6a7b8c9d +PublicationConsentRequiredConflict: + summary: Publishing without an active C2 consent + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5d6e7f80-91a2-4cb3-8d4e-5f6a7b8c9d0e + errors: + - in: body + pointer: /state + code: consent_required + message: Publishing needs an active C2 consent of the account. +HiddenOrganizationLimitReached: + summary: The candidate hides the maximum number of organizations + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6e7f8091-a2b3-4dc4-9e5f-6a7b8c9d0e1f + errors: + - in: path + pointer: /org_id + code: limit_reached + message: The candidate already hides the maximum number of organizations. +NotificationListPage: + summary: An unread notice and a read one whose source is no longer visible + value: + items: + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: "2026-10-09T08:30:00Z" + read_at: null + content: + title: Тестовое уведомление + summary: Организация «Север» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий. + link_path: null + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f6f + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: "2026-10-08T17:05:00Z" + read_at: "2026-10-08T17:10:00Z" + content: null + page: + has_more: false + next_cursor: null +NotificationReadReceipt: + summary: The first read time of an item + value: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + read_at: "2026-10-09T08:45:00Z" diff --git a/api/core/components/examples/matches.yml b/api/core/components/examples/matches.yml new file mode 100644 index 0000000..7d7da17 --- /dev/null +++ b/api/core/components/examples/matches.yml @@ -0,0 +1,402 @@ +SearchByNeed: + summary: Search against one confirmed requirements snapshot. + description: The reference is Need.requirements_version, not Need.version. + value: + need_id: 4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11 + requirements_version: 3 + filters: + specialization: backend + +SearchByBank: + summary: Search the organization-visible bank with separate confirmed and declared filters. + value: + filters: + specialization: backend + confirmed_grade: middle + confirmed_category: + specialization: backend + grade: middle + confirmation_status: confirmed + declared_grade: junior + stack: + - go + - postgresql + conditions: + work_formats: + - remote + salary_compatibility: compatible + +ThreeGroups: + summary: Synthetic example of main, near, and unconfirmed entries. + description: >- + Illustrative contract values only; these are not measurements from real + candidates. The same organization-scoped handle has independent Backend + and Networks states. + value: + source: + kind: bank + filters: + specialization: null + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + specialization: backend + confirmation_status: confirmed + declared_grade: middle + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: standard + public_context: + stack: + - go + - postgresql + experience_band: "3_6" + work_formats: + - remote + salary_compatibility: compatible + evidence_summary: + - code: confirmed_category + state: supports + - code: required_skill_evidence + state: supports + - code: work_conditions_match + state: supports + semantic_evidence: [] + components: + fit: 0.78 + coverage: 0.72 + domain: 0.75 + semantics: 0.5 + percentile: 0.61 + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.65 + unknown_flags: [] + near: + - candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB + specialization: frontend + confirmation_status: confirmed + declared_grade: junior + category: + specialization: frontend + grade: junior + basis: synthetic_demo + strength: standard + public_context: + stack: + - docker + experience_band: null + work_formats: + - hybrid + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + - code: required_skill_evidence + state: gap + semantic_evidence: [] + components: + fit: 0.48 + coverage: 0.18 + domain: 0.5 + semantics: 0.5 + percentile: 0.42 + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.43 + unknown_flags: + - component: experience_band + reason: not_in_public_card + - component: salary_compatibility + reason: not_in_public_card + unconfirmed: + - candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + specialization: network_engineer + confirmation_status: unconfirmed + declared_grade: junior + category: null + strength: null + public_context: + stack: null + experience_band: "1_3" + work_formats: + - remote + salary_compatibility: compatible + evidence_summary: + - code: declared_grade + state: declared_only + - code: required_skill_evidence + state: partial + semantic_evidence: [] + components: + fit: 0.51 + coverage: 0.38 + unknown_flags: + - component: assessment + reason: no_confirmation_for_specialization + truncated: false + +Empty: + summary: A valid search with no eligible visible candidates. + value: + source: + kind: bank + filters: + specialization: null + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: [] + near: [] + unconfirmed: [] + truncated: false + +MLUnavailable: + summary: Semantic similarity uses the documented neutral value while ML is unavailable. + description: Synthetic example; 0.5 is the FR09 neutral value, not an inference. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC + specialization: backend + confirmation_status: confirmed + declared_grade: null + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: strong + public_context: + stack: + - go + experience_band: 3_plus + work_formats: + - remote + salary_compatibility: compatible + evidence_summary: + - code: confirmed_category + state: supports + semantic_evidence: [] + components: + fit: 0.7 + coverage: 0.6 + domain: 0.5 + semantics: 0.5 + percentile: 0.6 + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.61 + unknown_flags: + - component: semantics + reason: ml_unavailable + near: [] + unconfirmed: [] + truncated: false + +CohortBelow30: + summary: A small comparison cohort has no published percentile. + description: Synthetic example; the exact cohort size is not disclosed. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD + specialization: backend + confirmation_status: confirmed + declared_grade: middle + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: standard + public_context: + stack: + - postgresql + experience_band: "3_6" + work_formats: + - office + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + semantic_evidence: [] + components: + fit: 0.62 + coverage: 0.55 + domain: 0.5 + semantics: 0.7 + percentile: null + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.56 + unknown_flags: + - component: percentile + reason: cohort_below_30 + near: [] + unconfirmed: [] + truncated: false + +Truncated: + summary: The group limit or the card-view allowance cut the output. + description: >- + Synthetic example. The entries returned are in rank order and already + counted as card views; the flag carries no total. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE + specialization: backend + confirmation_status: confirmed + declared_grade: null + category: + specialization: backend + grade: junior + basis: synthetic_demo + strength: standard + public_context: + stack: null + experience_band: null + work_formats: null + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + semantic_evidence: [] + components: + fit: 0.5 + coverage: 0.5 + domain: 0.5 + semantics: 0.5 + percentile: null + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.45125 + unknown_flags: + - component: semantics + reason: ml_unavailable + - component: percentile + reason: cohort_below_30 + near: [] + unconfirmed: [] + truncated: true + +SemanticEvidence: + summary: A need search explains an entry with semantic evidence from published card items. + description: >- + Synthetic example. `semantics` is the calibrated cosine of the stored + vectors; each evidence item pairs one confirmed requirement of the need + with the closest published card item. The project is named only by the + title that the candidate published; the repository address never appears. + value: + source: + kind: need + need_id: 4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11 + requirements_version: 3 + groups: + main: + - candidate_handle: cv1_FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + specialization: backend + confirmation_status: confirmed + declared_grade: middle + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: standard + public_context: + stack: + - kafka + - postgresql + experience_band: "3_6" + work_formats: null + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + - code: required_skill_evidence + state: declared_only + semantic_evidence: + - requirement_kind: task + requirement_text: Make payment callbacks idempotent + item_kind: project + project_title: Payment webhook deduplication service + repository_verified: true + similarity: high + - requirement_kind: required_skill + requirement_text: Kafka + item_kind: stack + project_title: null + repository_verified: false + similarity: medium + components: + fit: 0.69 + coverage: 0.25 + domain: 0.5 + semantics: 0.92 + percentile: null + competition: 0.0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.59 + unknown_flags: + - component: percentile + reason: cohort_below_30 + - component: freshness + reason: no_freshness_history + - component: responsiveness + reason: no_response_history + - component: work_formats + reason: not_in_public_card + - component: salary_compatibility + reason: not_in_public_card + - component: domain + reason: not_in_public_card + near: [] + unconfirmed: [] + truncated: false diff --git a/api/core/components/headers.yml b/api/core/components/headers.yml new file mode 100644 index 0000000..750a842 --- /dev/null +++ b/api/core/components/headers.yml @@ -0,0 +1,55 @@ +ETag: + description: >- + Strong entity tag of the returned resource version. Send it back in + If-Match to change this version. + required: true + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: '^"[A-Za-z0-9._~-]{1,128}"$' + example: '"v7"' +RetryAfter: + description: Number of seconds to wait before retrying the request. + schema: + type: integer + format: int32 + minimum: 0 + maximum: 86400 + example: 30 +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/parameters.yml b/api/core/components/parameters.yml new file mode 100644 index 0000000..c1e7902 --- /dev/null +++ b/api/core/components/parameters.yml @@ -0,0 +1,201 @@ +IdempotencyKey: + name: Idempotency-Key + in: header + required: true + description: |- + Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + + Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect. + + Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx. + + Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new. + schema: + type: string + minLength: 1 + maxLength: 255 + pattern: "^[A-Za-z0-9._:-]+$" + example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11 +IfMatch: + name: If-Match + in: header + required: false + description: |- + Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match. + + On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: '^"[A-Za-z0-9._~-]{1,128}"$' + example: '"v7"' +PageLimit: + name: limit + in: query + required: false + description: >- + Maximum number of items in the page. The server may return fewer items + even when more remain; use `page.has_more` to detect the end. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 100 + default: 20 +PageCursor: + name: cursor + in: query + required: false + description: >- + Opaque `page.next_cursor` value from the previous page of the same listing. + Omit it to read the first page. A malformed or foreign cursor returns 400 + with code validation_failed. + schema: + type: string + minLength: 1 + maxLength: 512 + pattern: "^[A-Za-z0-9_-]+$" +AssessmentAttemptId: + name: attempt_id + in: path + required: true + description: >- + Identifier of an assessment attempt of the current candidate. An attempt + of another candidate and an unknown identifier both answer 404 + not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b +AttemptClient: + name: X-Attempt-Client + in: header + required: false + description: |- + Random identifier that one open page of the assessment attempt generates when it loads and keeps until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a one-way keyed digest bound to the attempt, never the value. + + A request that omits the header counts as one anonymous client. It is refused with 409 `state_conflict` while another page holds the work session, and it is accepted while nobody does, so a client that predates the header keeps working until a page holds the session. + schema: + type: string + minLength: 16 + maxLength: 64 + pattern: "^[A-Za-z0-9_-]+$" + example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG +AttemptClientRequired: + name: X-Attempt-Client + in: header + required: true + description: >- + The page identifier described at AttemptClient. It is required here + because the operation exists to hold or release the work session of one + page. + schema: + type: string + minLength: 16 + maxLength: 64 + pattern: "^[A-Za-z0-9_-]+$" + example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG +OrganizationId: + name: org_id + in: path + required: true + description: >- + Identifier of an organization. Access comes only from an active + membership of the session account in this organization, checked by the + server on every request; the identifier itself grants nothing. An + organization without such a membership and an unknown identifier both + answer 404 not_found, so organizations cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 +CandidateHandle: + name: candidate_handle + in: path + required: true + description: >- + Organization-scoped opaque candidate alias issued by the current visible + card projection. The server resolves it only for the organization in the + path and rechecks current membership, publication consent, and hiding on + every read. Unknown, hidden, unpublished, and suppressed candidates all + answer the same 404. + schema: + $ref: ./schemas.yml#/CandidateHandle + example: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +NeedId: + name: need_id + in: path + required: true + description: >- + Identifier of a need of the organization in the path. A need of another + organization and an unknown identifier both answer 404 not_found. + schema: + type: string + format: uuid + example: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 +SupportCaseId: + name: case_id + in: path + required: true + description: >- + Identifier of a case of the current account. A case of another account + and an unknown identifier both answer 404 not_found, so identifiers + cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d +InvitationId: + name: invitation_id + in: path + required: true + description: >- + Identifier of an invitation of the organization in the path. An + invitation of another organization and an unknown identifier both answer + 404 not_found. + schema: + type: string + format: uuid + example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f +MyInvitationId: + name: invitation_id + in: path + required: true + description: >- + Identifier of an invitation addressed to the current candidate. A draft, + an invitation addressed to another candidate, and an unknown identifier + all answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f +HiddenOrganizationId: + name: org_id + in: path + required: true + description: >- + Identifier of the organization that the current candidate hides or stops + hiding the profile from. It names the target of a candidate's own + setting and grants the candidate nothing about the organization. Hiding + answers the same 404 not_found for an organization that does not exist + and for one that the candidate cannot see, so organizations cannot be + enumerated; lifting the hiding answers 204 for any well-formed + identifier. + schema: + type: string + format: uuid + example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 +NotificationId: + name: notification_id + in: path + required: true + description: >- + Identifier of an item of the inbox of the current account in the cabinet + that the path names. An item of another account, an item of another + organization context, and an unknown identifier all answer 404 not_found, + so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml new file mode 100644 index 0000000..0296803 --- /dev/null +++ b/api/core/components/responses.yml @@ -0,0 +1,717 @@ +ValidationFailed: + description: >- + Parameters, headers, or the body do not match the contract, or the body + violates a domain rule such as salary_from <= salary_to. The body has code + validation_failed and lists the failing fields in `errors` with body or + parameter pointers. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + $ref: ./examples.yml#/ValidationFailed + domain_rule: + $ref: ./examples.yml#/DomainValidationFailed +Unauthenticated: + description: No valid session or credentials; code unauthenticated. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + unauthenticated: + $ref: ./examples.yml#/Unauthenticated +Forbidden: + description: >- + The caller is authenticated but may not perform the operation; code + forbidden. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + forbidden: + $ref: ./examples.yml#/Forbidden +NotFound: + description: >- + The object does not exist or is not visible to the caller; code + not_found. Missing and inaccessible objects are not distinguished. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + not_found: + $ref: ./examples.yml#/NotFound +IdempotencyInProgress: + description: >- + A request with the same Idempotency-Key and the same fingerprint is still + being processed; code idempotency_in_progress. Retry after the original + request completes. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +StateConflict: + description: >- + The operation conflicts with the current state of the resource, for + example a transition that is not allowed from its current status; code + state_conflict. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/StateConflict +PreconditionFailed: + description: >- + If-Match does not match the current resource version; code + version_conflict. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/VersionConflict +PayloadTooLarge: + description: The request body exceeds the operation limit; code payload_too_large. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + payload_too_large: + $ref: ./examples.yml#/PayloadTooLarge +UnprocessableContent: + description: >- + The Idempotency-Key was already used with a different request within 24 + hours; code idempotency_key_reused. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + idempotency_key_reused: + $ref: ./examples.yml#/IdempotencyKeyReused +PreconditionRequired: + description: The operation requires If-Match; code precondition_required. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + precondition_required: + $ref: ./examples.yml#/PreconditionRequired +TooManyRequests: + description: Too many requests; code rate_limited. + headers: + Retry-After: + $ref: ./headers.yml#/RetryAfter + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + rate_limited: + $ref: ./examples.yml#/RateLimited +Internal: + description: Unexpected server error; code internal. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + internal: + $ref: ./examples.yml#/Internal +NotImplemented: + description: >- + The operation is declared in the contract but not implemented yet; code + not_implemented. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + not_implemented: + $ref: ./examples.yml#/NotImplemented +ServiceUnavailable: + description: >- + The service cannot serve the request now; code service_unavailable. + Retry-After is sent when a retry after that wait can succeed, for example + when a queue is full, and omitted when a retry cannot help soon, for + example when the feature is not enabled on this server. + headers: + Retry-After: + $ref: ./headers.yml#/RetryAfter + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + service_unavailable: + summary: A queue is full. + value: + type: urn:lincodex:problem:service_unavailable + title: Service unavailable + status: 503 + code: service_unavailable +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + $ref: ./examples.yml#/ValidationFailed + not_found: + $ref: ./examples.yml#/NotFound + internal: + $ref: ./examples.yml#/Internal + not_implemented: + $ref: ./examples.yml#/NotImplemented +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 +EmailVerificationCodeFailed: + description: >- + The code does not verify the email. Code verification_token_invalid covers + every refusal in the same shape: an unknown address, an address without an + open code, a wrong code, an expired code, a wrong password, and a code that + was burned after five failed attempts. Code validation_failed means the + body does not match the contract, such as a code that is not six digits, + and carries the pointer `/code`, `/email`, or `/password`. Nothing was + changed in any case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + verification_code_invalid: + $ref: ./examples.yml#/VerificationCodeInvalid + validation_failed: + $ref: ./examples.yml#/VerificationCodeMalformed +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 +CsrfCheckFailedOrForbidden: + description: >- + The request failed cross-site request protection, code + csrf_check_failed: the X-CSRF-Token header is missing or does not belong + to the session, or the Origin is not allowed. Or the account may not + perform the operation, code forbidden. Nothing was changed in either + case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + csrf_check_failed: + $ref: ./examples.yml#/CsrfCheckFailed + forbidden: + $ref: ./examples.yml#/Forbidden +QuestionnaireValidationFailed: + description: >- + The body does not match the contract or violates a questionnaire rule: + more than two specializations, an unknown specialization, grade, or task + language, an unknown field such as confirmed_grade, a repeated + specialization, or a task language that the specialization's published + bank does not offer; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + too_many_specializations: + $ref: ./examples.yml#/QuestionnaireTooManySpecializations + unknown_grade: + $ref: ./examples.yml#/QuestionnaireUnknownGrade + repeated_specialization: + $ref: ./examples.yml#/QuestionnaireRepeatedSpecialization +QuestionnaireVersionConflict: + description: >- + `expected_version` is not the current questionnaire version; code + version_conflict. Nothing was changed; read the questionnaire again + before retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/VersionConflict +AssessmentAttemptCreateValidationFailed: + description: >- + The body does not match the contract or violates an assessment rule: an + unknown specialization, grade, or task language, an unknown field such + as mode or seed, a specialization that is not in the questionnaire, or + a task language that the published bank does not offer; code + validation_failed with body pointers. Nothing was created, and the + outcome is not stored under the Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + specialization_not_in_questionnaire: + $ref: ./examples.yml#/AssessmentSpecializationNotInQuestionnaire +AssessmentAnswerValidationFailed: + description: >- + The body does not match the contract or the answer does not fit the + item: a format other than the item format, an option, element, or line + that the item does not have, an order that is not a permutation of every + element, more selections than the item allows, a text longer than the + item allows, a language that the practice does not offer, or an unknown + field such as score or duration; code validation_failed with body + pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was stored, and the outcome is + not stored under the Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + unknown_option: + $ref: ./examples.yml#/AssessmentAnswerUnknownOption + score_sent_by_client: + $ref: ./examples.yml#/AssessmentAnswerUnknownField +AssessmentCommandConflict: + description: >- + The attempt state does not allow the answer at the current version, code + state_conflict: the attempt is terminal or past its limits, the item is + not the current item, the item already has a different answer, or the + practice has a pending or finished verdict and the submission differs. + Or a request with the same Idempotency-Key is still running, code + idempotency_in_progress. Nothing was changed in either case; read the + attempt to see its state. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentItemNotCurrent + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +AssessmentFinalizeConflict: + description: >- + The attempt state does not allow finalize at the current version, code + state_conflict: items or the main practice are unfinished, a practice + verdict is pending, or the attempt ended as expired or insufficient_bank. + If required questions are unfinished, the response includes their frozen + IDs in `pending_item_ids`; other state conflicts omit that field. Or a + request with the same Idempotency-Key is still running, code + idempotency_in_progress. Nothing was changed in either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/AssessmentFinalizeConflictProblem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentFinalizeNotReady + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +AssessmentCreateConflict: + description: >- + No attempt can start for the category now, code state_conflict: the + specialization already has an active attempt, a retry or promotion + interval or the attempt limit blocks the grade, or the bank is + insufficient. GetMyAssessmentAvailability tells which, with the date + when a blocked attempt opens. Or a request with the same Idempotency-Key + is still running, code idempotency_in_progress. Nothing was created in + either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentAttemptNotAvailable + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +AssessmentResultNotReady: + description: >- + The attempt is still active, so it has no result yet; code + state_conflict. The attempt state tells what remains to be done. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/AssessmentResultNotReady +AssessmentVersionConflict: + description: >- + `expected_version` is not the current attempt version; code + version_conflict. Nothing was changed, and the outcome is not stored + under the Idempotency-Key; read the attempt again before retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/AssessmentStaleVersion +NeedValidationFailed: + description: >- + The body does not match the contract or violates a need rule: an unknown + field such as rec_score, members, or candidate_minimum, a field sent as a + bare value instead of `{value, status}`, a list sent as null, an unknown + specialization, grade, work format, currency, period, or tax basis, a + salary bound that is not a positive multiple of 1000, a lower bound that + is not below the upper one, a range width outside 10-40% of its midpoint, + a repeated skill or task, status `extracted` with a value that is not the + stored suggestion, a vacancy that is not a vacancy of the organization, + or a missing or invalid expected_version; code validation_failed with + body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the + outcome is not stored under an Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + reversed_salary_range: + $ref: ./examples.yml#/NeedSalaryRangeReversed + equal_salary_bounds: + $ref: ./examples.yml#/NeedSalaryEqualBounds + salary_range_too_wide: + $ref: ./examples.yml#/NeedSalaryRangeTooWide + salary_without_tax_basis: + $ref: ./examples.yml#/NeedSalaryWithoutTaxBasis + extracted_value_mismatch: + $ref: ./examples.yml#/NeedExtractedValueMismatch + recommendation_score_sent_by_client: + $ref: ./examples.yml#/NeedUnknownField + missing_expected_version: + $ref: ./examples.yml#/NeedMissingExpectedVersion +NeedVersionConflict: + description: >- + `expected_version` is not the current need version; code + version_conflict. Nothing was changed; read the need again before + retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/NeedStaleVersion +SupportCaseValidationFailed: + description: >- + The body does not match the contract or violates a case rule: an empty + or blank description, including one made only of Unicode spaces, an + unknown case type, an object identifier that is not a UUID, an object + type that the + case type does not accept, a missing required field of the type, an + unknown field such as status, decision, moderator, or priority, or a + complaint reason that requires an invitation reference; code + validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was + created, and the outcome is not stored under the Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + blank_description: + $ref: ./examples.yml#/SupportCaseBlankDescription + unknown_type: + $ref: ./examples.yml#/SupportCaseUnknownType + decision_sent_by_client: + $ref: ./examples.yml#/SupportCaseUnknownField + malformed_object_id: + $ref: ./examples.yml#/SupportCaseMalformedReference + complaint_reason_needs_invitation: + $ref: ./examples.yml#/SupportCaseComplaintNeedsInvitation +SupportCaseCreateConflict: + description: >- + The referenced object does not allow this case now, code + state_conflict: the attempt of a grade appeal has no result yet, the + case referenced by a grade appeal is not a manual assessment resolved + with the outcome assessed, the attempt of an anti-cheat appeal has no + anti-cheat review decision, the attempt or the manual assessment + already has an appeal of the same type, or an open case of the same + type already exists for the category or the object. Or a request + with the same Idempotency-Key is still running, code + idempotency_in_progress. Nothing was created in either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/SupportCaseAppealExists + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +InvitationValidationFailed: + description: >- + The body does not match the contract or violates an invitation rule: a + missing term or package condition, a package condition left out instead + of `not_provided`, a salary range without its tax basis, a salary bound + that is not a positive multiple of 1000, a lower bound that is not below + the upper one, a range width outside 10-40% of its midpoint, the + `office` or `hybrid` format without a place of work, a repeated + technology, a candidate handle that the organization cannot use, a need + or requirements version that the organization does not have, a response + period other than 3, 7, or 14 days, an unknown field such as a + candidate's email address or salary minimum, or a missing or invalid + expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the outcome is not stored under an + Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + without_tax_basis: + $ref: ./examples.yml#/InvitationWithoutTaxBasis + without_communication_method: + $ref: ./examples.yml#/InvitationWithoutCommunicationMethod + package_condition_left_out: + $ref: ./examples.yml#/InvitationPackageItemMissing + salary_range_too_wide: + $ref: ./examples.yml#/InvitationSalaryRangeTooWide + location_required: + $ref: ./examples.yml#/InvitationLocationRequired + unknown_candidate: + $ref: ./examples.yml#/InvitationUnknownCandidate + candidate_data_in_body: + $ref: ./examples.yml#/InvitationCandidateDataInBody +InvitationAcceptValidationFailed: + description: >- + The body does not match the contract or violates a rule of the consent + C4: a missing `terms_version` or `expected_version`, `accepted` other + than true, an empty or repeated choice of contact fields, an unknown + field kind, a field that the candidate's profile does not hold, a + consent text version that is not the published one, or an unknown field + such as a contact value; code validation_failed with body pointers. + Nothing was changed, no consent or grant was recorded, and the outcome + is not stored under the Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + empty_field_choice: + $ref: ./examples.yml#/InvitationConsentWithoutFields + outdated_consent_text: + $ref: ./examples.yml#/InvitationConsentTextOutdated + missing_terms_version: + $ref: ./examples.yml#/InvitationMissingTermsVersion +InvitationVersionConflict: + description: >- + `expected_version` is not the current invitation version, or, for an + acceptance, `terms_version` is not the current terms version; code + version_conflict. Nothing was changed, no consent or grant was + recorded, and the outcome is not stored under an Idempotency-Key; read + the invitation again before retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + stale_terms: + $ref: ./examples.yml#/InvitationStaleTerms + stale_version: + $ref: ./examples.yml#/InvitationStaleVersion +InvitationCommandConflict: + description: >- + The state of the invitation does not allow the command, code + state_conflict: for example an acceptance of a withdrawn or expired + invitation or one past its deadline, a send of an invitation that is no + longer a draft, a send blocked by the pending limit of the need or by + the pause after a decline, or a second raise of the upper salary bound. + The invitation tells the client its state. Or a request with the same + Idempotency-Key is still running, code idempotency_in_progress. Nothing + was changed in either case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + not_answerable: + $ref: ./examples.yml#/InvitationNotAnswerable + salary_raise_used: + $ref: ./examples.yml#/InvitationSalaryRaiseUsed + send_blocked: + $ref: ./examples.yml#/InvitationSendBlocked + idempotency_in_progress: + $ref: ./examples.yml#/IdempotencyInProgress +OrganizationValidationFailed: + description: >- + The body does not match the contract or violates an organization rule: + a missing name, an unknown field such as role, verification_level, + verification, members, owner, or version, a name or sphere with + surrounding whitespace or a line break, a website that is not an https + URL of a host name, a phone number outside E.164, a Telegram username + without the leading @, a contact that has no valid form, more than ten + representatives, or a missing or invalid expected_version; code + validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the + outcome is not stored under an Idempotency-Key. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + role_sent_by_client: + $ref: ./examples.yml#/OrganizationUnknownField + website_not_https: + $ref: ./examples.yml#/OrganizationWebsiteNotHttps + name_with_surrounding_whitespace: + $ref: ./examples.yml#/OrganizationNameWithWhitespace + missing_expected_version: + $ref: ./examples.yml#/OrganizationMissingExpectedVersion +OrganizationVersionConflict: + description: >- + `expected_version` is not the current version of the organization; code + version_conflict. Nothing was changed; read the organization again + before retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/OrganizationStaleVersion +ProfileValidationFailed: + description: >- + The body does not match the contract or violates a profile rule: an + unknown field such as confirmed_grade, category, trust_level, or source, + a phone number outside E.164, a Telegram username without the leading @, + an email that is not an address, a month outside the YYYY-MM format, a + salary that is not a positive multiple of 1000, more items than a list + allows, a repeated tag, skill, or role specialization, a period that + ends before it starts or lies in the future, a decision extracted for a + value that is not a stored suggestion, an overlapping experience period + without an explicit date-pair acknowledgement, or a missing or invalid + expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed. The problem never repeats a submitted value, because the body is personal data. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + phone_not_e164: + $ref: ./examples.yml#/ProfilePhoneNotE164 + extracted_value_changed: + $ref: ./examples.yml#/ProfileExtractedValueChanged + repeated_role: + $ref: ./examples.yml#/ProfileRepeatedRole +ProfileVersionConflict: + description: >- + `expected_version` is not the current profile version; code + version_conflict. Nothing was changed; read the profile again before + retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/ProfileStaleVersion +PrivacyValidationFailed: + description: >- + The body does not match the contract or breaks a visibility rule: an + unknown field, a repeated or unknown card field, a published state with + no field, a closed state with a field, a search status other than + looking and not_looking, or a missing or invalid expected_version; code + validation_failed with body pointers. Nothing was changed. The problem + never repeats a submitted value. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + published_without_fields: + $ref: ./examples.yml#/PrivacyPublishedWithoutFields +PrivacyVersionConflict: + description: >- + `expected_version` is not the current version of the setting; code + version_conflict. Nothing was changed; read the settings again before + retrying. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + version_conflict: + $ref: ./examples.yml#/PrivacyStaleVersion +PublicationConsentRequired: + description: >- + The profile cannot be published because the account has no active, + unrevoked C2 consent; code state_conflict. Nothing was changed. The + candidate gives C2 in the consent settings first. `errors` holds the entry + `{in: body, pointer: /state, code: consent_required}`. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + state_conflict: + $ref: ./examples.yml#/PublicationConsentRequiredConflict +HiddenOrganizationLimit: + description: >- + The candidate already hides the maximum number of organizations (1000); + code state_conflict with the entry `{in: path, pointer: /org_id, code: + limit_reached}` in `errors`. Nothing was changed. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + limit_reached: + $ref: ./examples.yml#/HiddenOrganizationLimitReached diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index c9e3a15..2dd5318 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -1,3 +1,3763 @@ +Timestamp: + type: string + format: date-time + description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema. + examples: + - '2026-10-05T09:30:00Z' +PageInfo: + type: object + description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - 'null' + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. +CandidateHandle: + type: string + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Opaque reference to a candidate as one organization sees it, taken from the organization-scoped anonymous card. It is a versioned HMAC alias, not a candidate account or profile identifier; it contains no contact information and is meaningless to another organization. The server resolves it only against the current visible cohort of the organization in the path. Clients never parse or construct it. It is shared by the candidate-card read and invitations. + examples: + - cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA +AssessmentMode: + type: string + description: 'Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. + + + - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. + + - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + + - demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence. + + + Adding a value is a contract change.' + enum: + - demo_basic + - demo_express + - adaptive +AssessmentRealMode: + type: string + description: Server-selected mode available to a real category assessment. + enum: + - demo_basic + - adaptive +AssessmentAttemptKind: + type: string + description: Assessment track that distinguishes root, corrective, and training attempts. + enum: + - root + - corrective + - demo_express +AssessmentAttemptVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' + examples: + - 4 +AssessmentAttemptState: + type: string + description: 'Lifecycle state of an attempt and the commands it accepts. + + + - in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item. + + - practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part. + + - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence. + + - ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt. + + - completed: a decision was made; the result is available. + + - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. + + - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. + + + When `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate''s fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change.' + enum: + - in_progress + - practice_pending + - additional_practice_pending + - ready_to_finalize + - completed + - expired + - insufficient_bank +AssessmentVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it. +AssessmentVersions: + type: object + description: Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it. + additionalProperties: false + required: + - policy_version + - bank_version + - algorithm_version + properties: + policy_version: + type: integer + format: int32 + minimum: 1 + description: 'Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.' + bank_version: + $ref: '#/AssessmentVersionLabel' + algorithm_version: + $ref: '#/AssessmentVersionLabel' +AssessmentSessions: + type: object + description: 'Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. + + + Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them.' + additionalProperties: false + required: + - used + - max + - idle_timeout_seconds + properties: + used: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Sessions started so far, including the current one. + max: + type: integer + format: int32 + minimum: 1 + maximum: 10 + idle_timeout_seconds: + type: integer + format: int32 + minimum: 60 + maximum: 86400 + description: Inactivity after which the current session ends. +AssessmentAttemptCreate: + description: Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The required `kind` discriminator selects one of the three request shapes; `mode` remains server-selected for real assessments. + oneOf: + - $ref: '#/AssessmentQualifiedAttemptCreate' + - $ref: '#/AssessmentCorrectiveAttemptCreate' + - $ref: '#/AssessmentExpressAttemptCreate' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedAttemptCreate' + corrective: '#/AssessmentCorrectiveAttemptCreate' + demo_express: '#/AssessmentExpressAttemptCreate' +AssessmentQualifiedAttemptCreate: + type: object + description: Start a real assessment for a specialization and target grade, with the task language. The candidate comes from the session. The server chooses demo_basic or adaptive and fixes the policy, bank, and algorithm versions. Unknown fields such as `mode`, `seed`, or `score` are rejected. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + properties: + kind: + type: string + enum: + - root + description: Start a real-assessment chain and reserve one root quota slot. + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + task_language: + description: Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' +AssessmentCorrectiveAttemptCreate: + type: object + description: Start a corrective real assessment at a lower target grade in the chain rooted at root_attempt_id. The server validates that this grade is strictly below the preceding grade and that the chain remains within its existing deadline and quota. chain_deadline is derived from the root attempt and is never supplied by the client. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + - root_attempt_id + properties: + kind: + type: string + enum: + - corrective + description: Continue the existing real-assessment chain without reserving another root slot. + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + root_attempt_id: + type: string + format: uuid + description: Root real-assessment attempt whose quota and deadline this attempt shares. +AssessmentExpressAttemptCreate: + type: object + description: Explicitly start the short training run. It has no specialization or target grade, uses its separate demo policy, and does not consume a real-assessment attempt. + additionalProperties: false + required: + - kind + properties: + kind: + type: string + enum: + - demo_express + description: Explicitly request the training run; real modes cannot be selected by the client. +AssessmentAttemptSessionStart: + type: object + description: Start or resume a work session using the attempt version last read by the candidate. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' +AssessmentItemId: + type: string + format: uuid + description: Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed. +AssessmentOptionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option. +AssessmentOption: + type: object + description: Choice option or order element. Plain text. + additionalProperties: false + required: + - id + - text + properties: + id: + $ref: '#/AssessmentOptionId' + text: + type: string + minLength: 1 + maxLength: 2000 + description: Text of the option; the client shows it as text, never as HTML. +ChoiceItemContent: + type: object + description: Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are. + additionalProperties: false + required: + - format + - options + - multiple + properties: + format: + type: string + enum: + - choice + options: + type: array + minItems: 2 + maxItems: 10 + description: Options in the order of this instance. + items: + $ref: '#/AssessmentOption' + multiple: + type: boolean + description: 'Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.' +NumberItemContent: + type: object + description: Enter a number, optionally in the given unit. + additionalProperties: false + required: + - format + - unit + properties: + format: + type: string + enum: + - number + unit: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + description: Unit of the expected value, for example `ms`, or null. +StringItemContent: + type: object + description: Enter a short string, such as a command, a header name, or an address. + additionalProperties: false + required: + - format + - max_length + properties: + format: + type: string + enum: + - string + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 500 + description: Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer. +OrderItemContent: + type: object + description: Put every element into the right order. The elements arrive in the order of this instance, which is never the answer. + additionalProperties: false + required: + - format + - elements + properties: + format: + type: string + enum: + - order + elements: + type: array + minItems: 2 + maxItems: 20 + items: + $ref: '#/AssessmentOption' +CodeLine: + type: object + description: One numbered line of a code or configuration fragment. Plain text. + additionalProperties: false + required: + - number + - text + properties: + number: + type: integer + format: int32 + minimum: 1 + maximum: 500 + text: + type: string + maxLength: 1000 +FindErrorItemContent: + type: object + description: Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers. + additionalProperties: false + required: + - format + - syntax + - lines + - max_selections + properties: + format: + type: string + enum: + - find_error + syntax: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + lines: + type: array + minItems: 1 + maxItems: 500 + description: Lines numbered from 1 in order. + items: + $ref: '#/CodeLine' + max_selections: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines. +ConfigurationItemContent: + type: object + description: Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code. + additionalProperties: false + required: + - format + - syntax + - initial_config + - max_length + properties: + format: + type: string + enum: + - configuration + syntax: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + initial_config: + type: string + maxLength: 20000 + description: Starting text to edit; empty when the candidate writes it from scratch. + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 20000 + description: Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key. +PracticeExample: + type: object + description: 'Public example of the practice task: an input and its expected output. Hidden checks are never listed.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 +PracticeItemContent: + type: object + description: Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client. + additionalProperties: false + required: + - format + - languages + - public_examples + - max_source_length + properties: + format: + type: string + enum: + - practice + languages: + type: array + maxItems: 2 + uniqueItems: true + description: Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language. + items: + $ref: '#/TaskLanguage' + public_examples: + type: array + maxItems: 10 + items: + $ref: '#/PracticeExample' + max_source_length: + type: integer + format: int32 + minimum: 1 + maximum: 65536 + description: Maximum length of the solution source in characters. +ItemContent: + description: 'Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.' + oneOf: + - $ref: '#/ChoiceItemContent' + - $ref: '#/NumberItemContent' + - $ref: '#/StringItemContent' + - $ref: '#/OrderItemContent' + - $ref: '#/FindErrorItemContent' + - $ref: '#/ConfigurationItemContent' + - $ref: '#/PracticeItemContent' + - $ref: '#/LabItemContent' +AssessmentItem: + type: object + description: 'Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.' + additionalProperties: false + required: + - id + - sequence + - prompt + - content + properties: + id: + $ref: '#/AssessmentItemId' + sequence: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: Position of the item in the attempt, from 1. + prompt: + type: string + minLength: 1 + maxLength: 20000 + description: Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML. + content: + $ref: '#/ItemContent' +AssessmentProgress: + type: object + description: Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`. + additionalProperties: false + required: + - answered_items + - max_items + properties: + answered_items: + type: integer + format: int32 + minimum: 0 + maximum: 100 + max_items: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: 'Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.' +PracticeKind: + type: string + description: 'Role of a practice in the attempt. + + + - main: the practice that every attempt with practice requires before a decision. + + - additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt. + + + Adding a value is a contract change.' + enum: + - main + - additional +PracticeStatus: + type: string + description: 'State of a practice. + + + - not_started: no solution was submitted yet. + + - pending: the submitted solution is queued or running in the sandbox. + + - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed. + + - failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate''s and consumes nothing; the practice can be submitted again.' + enum: + - not_started + - pending + - finished + - failed +PracticeFailureReason: + type: string + description: 'Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.' + enum: + - sandbox_busy + - sandbox_error +PracticeGroupResult: + type: object + description: Outcome of one hidden check group. It never contains the checks themselves. + additionalProperties: false + required: + - group + - passed + properties: + group: + type: integer + format: int32 + minimum: 1 + maximum: 3 + passed: + type: boolean +PracticeVerdict: + type: object + description: 'Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.' + additionalProperties: false + required: + - score + - max_score + - groups + properties: + score: + type: integer + format: int32 + minimum: 0 + maximum: 3 + max_score: + type: integer + format: int32 + minimum: 3 + maximum: 3 + groups: + type: array + minItems: 3 + maxItems: 3 + items: + $ref: '#/PracticeGroupResult' +AssessmentPractice: + type: object + description: Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision. + additionalProperties: false + required: + - kind + - item_id + - status + - submitted_at + - verdict + - failure_reason + properties: + kind: + $ref: '#/PracticeKind' + item_id: + $ref: '#/AssessmentItemId' + status: + $ref: '#/PracticeStatus' + submitted_at: + description: Time of the latest submission, or null before the first one. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + verdict: + description: The verdict when `status` is `finished`, otherwise null. + oneOf: + - $ref: '#/PracticeVerdict' + - type: 'null' + failure_reason: + description: The reason when `status` is `failed`, otherwise null. + oneOf: + - $ref: '#/PracticeFailureReason' + - type: 'null' +AssessmentAttempt: + description: Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. The variants keep training output separate from qualification attempts. + oneOf: + - $ref: '#/AssessmentQualifiedAttempt' + - $ref: '#/AssessmentCorrectiveAttempt' + - $ref: '#/AssessmentExpressAttempt' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedAttempt' + corrective: '#/AssessmentCorrectiveAttempt' + demo_express: '#/AssessmentExpressAttempt' +AssessmentAttemptCommon: + type: object + description: Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - kind + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: '#/AssessmentAttemptVersion' + specialization: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/SpecializationCode' + - type: 'null' + target_grade: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + task_language: + description: Task language of the attempt, or null when none is selected. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + kind: + $ref: '#/AssessmentAttemptKind' + root_attempt_id: + description: Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + readOnly: true + mode: + $ref: '#/AssessmentMode' + state: + $ref: '#/AssessmentAttemptState' + versions: + $ref: '#/AssessmentVersions' + started_at: + $ref: '#/Timestamp' + expires_at: + description: Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline. + $ref: '#/Timestamp' + sessions: + description: Session limit of the attempt, or null when its policy defines none. + oneOf: + - $ref: '#/AssessmentSessions' + - type: 'null' + finished_at: + description: Time the attempt reached a terminal state, or null while it is active. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + progress: + $ref: '#/AssessmentProgress' + current_item: + description: 'Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.' + oneOf: + - $ref: '#/AssessmentItem' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Practices in the order assigned by the mode policy. The list exposes verdicts only after submission. + items: + $ref: '#/AssessmentPractice' + watermark: + $ref: '#/AssessmentWatermark' +AssessmentWorkSession: + type: object + description: The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for the attempt, not a score or a signal, and it changes no result. + additionalProperties: false + required: + - held_until + - renew_after_seconds + properties: + held_until: + $ref: '#/Timestamp' + renew_after_seconds: + type: integer + format: int32 + minimum: 1 + maximum: 3600 + description: How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed down in the background still renews before its hold expires. +AssessmentWatermark: + type: object + description: 'Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.' + additionalProperties: false + required: + - code + properties: + code: + type: string + minLength: 10 + maxLength: 11 + pattern: ^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$ + description: Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`. +AssessmentQualifiedAttempt: + allOf: + - $ref: '#/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - root + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + root_attempt_id: + type: 'null' + description: Root attempts have no parent attempt. + chain_deadline: + type: 'null' + description: A root attempt has no correction-chain deadline. + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline +AssessmentCorrectiveAttempt: + allOf: + - $ref: '#/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/Timestamp' + readOnly: true + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline +AssessmentExpressAttempt: + allOf: + - $ref: '#/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + specialization: + type: 'null' + target_grade: + type: 'null' + task_language: + type: 'null' + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - mode + - specialization + - target_grade + - task_language + - root_attempt_id + - chain_deadline +ChoiceAnswer: + type: object + description: 'Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.' + additionalProperties: false + required: + - format + - option_ids + properties: + format: + type: string + enum: + - choice + option_ids: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + $ref: '#/AssessmentOptionId' +NumberAnswer: + type: object + description: Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer. + additionalProperties: false + required: + - format + - number + properties: + format: + type: string + enum: + - number + number: + type: number + format: double + x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber +StringAnswer: + type: object + description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison. + additionalProperties: false + required: + - format + - text + properties: + format: + type: string + enum: + - string + text: + type: string + minLength: 1 + maxLength: 500 +OrderAnswer: + type: object + description: Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical. + additionalProperties: false + required: + - format + - element_ids + properties: + format: + type: string + enum: + - order + element_ids: + type: array + minItems: 2 + maxItems: 20 + uniqueItems: true + items: + $ref: '#/AssessmentOptionId' +FindErrorAnswer: + type: object + description: Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order. + additionalProperties: false + required: + - format + - line_numbers + properties: + format: + type: string + enum: + - find_error + line_numbers: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + type: integer + format: int32 + minimum: 1 + maximum: 500 +ConfigurationAnswer: + type: object + description: Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks. + additionalProperties: false + required: + - format + - config + properties: + format: + type: string + enum: + - configuration + config: + type: string + minLength: 1 + maxLength: 20000 +PracticeAnswer: + type: object + description: Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem. + additionalProperties: false + required: + - format + - language + - source_code + properties: + format: + type: string + enum: + - practice + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + source_code: + type: string + minLength: 1 + maxLength: 65536 +AssessmentAnswer: + description: 'Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.' + oneOf: + - $ref: '#/ChoiceAnswer' + - $ref: '#/NumberAnswer' + - $ref: '#/StringAnswer' + - $ref: '#/OrderAnswer' + - $ref: '#/FindErrorAnswer' + - $ref: '#/ConfigurationAnswer' + - $ref: '#/PracticeAnswer' +AssessmentAnswerSubmission: + type: object + description: Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag. + additionalProperties: false + required: + - expected_version + - item_id + - answer + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' + item_id: + $ref: '#/AssessmentItemId' + answer: + $ref: '#/AssessmentAnswer' +AssessmentFinalization: + type: object + description: Command to finalize the attempt. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' +AssessmentOutcome: + type: string + description: 'Grade decision of the attempt. + + + - confirmed: the target grade is confirmed by the rule of the recorded policy version. + + - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force. + + - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force. + + + A failed, expired, or flagged attempt never lowers a confirmed grade.' + enum: + - confirmed + - not_confirmed + - not_determined +AssessmentNotDeterminedReason: + type: string + description: 'Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot. + + + - expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + + - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot. + + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain.' + enum: + - expired + - practice_incomplete + - insufficient_bank + - sandbox_unavailable +AssessmentStrength: + type: string + description: 'Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.' + enum: + - high + - medium +CalibrationStatus: + type: string + description: 'Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.' + enum: + - uncalibrated + - calibrated +AssessmentLimitation: + type: string + description: 'Known limitation of the method behind a real-assessment result, shown with the result. + + + - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. + + - demo_bank: the result comes from the small reviewed demo bank. + + - practice_not_included: the attempt had no code practice because the sandbox was not enabled. + + - unproctored: the attempt was taken online without supervision. + + Adding a value is a contract change.' + enum: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored +AssessmentInterval: + type: object + description: Interval on the ability scale. + additionalProperties: false + required: + - low + - high + properties: + low: + type: number + format: double + high: + type: number + format: double +AssessmentUncertainty: + type: object + description: 'Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.' + additionalProperties: false + required: + - theta + - standard_error + - interval_95 + - p_grade + properties: + theta: + type: number + format: double + standard_error: + type: number + format: double + minimum: 0 + interval_95: + $ref: '#/AssessmentInterval' + p_grade: + type: number + format: double + minimum: 0 + maximum: 1 + description: Probability of reaching the threshold of the target grade. +BasicScore: + type: object + description: Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass mark comes from that policy version and never from the handler. + additionalProperties: false + required: + - points + - max_points + - pass_points + properties: + points: + type: integer + format: int32 + minimum: 0 + max_points: + type: integer + format: int32 + minimum: 1 + pass_points: + type: integer + format: int32 + minimum: 1 +AssessmentGap: + type: object + description: Domain of the specialization where the evidence was weak. + additionalProperties: false + required: + - domain + - title + properties: + domain: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9_]+$ + description: Stable domain code of the bank blueprint. + title: + type: string + minLength: 1 + maxLength: 200 + description: Display name in Russian. Plain text. +AssessmentDurations: + type: object + description: 'Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.' + additionalProperties: false + required: + - items_seconds + - practice_seconds + properties: + items_seconds: + type: integer + format: int32 + minimum: 0 + practice_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 0 + description: Time on all practices with a verdict, or null when no practice has one. +AssessmentPracticeResult: + type: object + description: Verdict of one practice of the attempt. + additionalProperties: false + required: + - kind + - verdict + properties: + kind: + $ref: '#/PracticeKind' + verdict: + $ref: '#/PracticeVerdict' +AssessmentNextAction: + type: string + description: 'Step that the candidate may take next. + + + - retake_same_grade: test the same grade again from `available_at`. + + - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval. + + - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned). + + - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy.' + enum: + - retake_same_grade + - take_lower_grade + - accept_lower_grade + - take_higher_grade +AssessmentNextStep: + type: object + description: Step that the server allows after this result, computed when it was decided. + additionalProperties: false + required: + - action + - grade + - available_at + properties: + action: + $ref: '#/AssessmentNextAction' + grade: + $ref: '#/GradeCode' + available_at: + description: First time the step is allowed, or null when it is allowed now. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +AssessmentResult: + description: Immutable result of a terminal assessment attempt. The result shape distinguishes real grade decisions from demo_express training output. + oneOf: + - $ref: '#/AssessmentQualifiedResult' + - $ref: '#/AssessmentCorrectiveResult' + - $ref: '#/AssessmentExpressResult' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedResult' + corrective: '#/AssessmentCorrectiveResult' + demo_express: '#/AssessmentExpressResult' +AssessmentRealResult: + description: A completed root or corrective result. Training-only demo_express results are excluded from qualification history. + oneOf: + - $ref: '#/AssessmentQualifiedResult' + - $ref: '#/AssessmentCorrectiveResult' + discriminator: + propertyName: kind + mapping: + root: '#/AssessmentQualifiedResult' + corrective: '#/AssessmentCorrectiveResult' +AssessmentCategoryDecisionView: + type: object + description: Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate's current category after this decision. + additionalProperties: false + required: + - status + - previous_confirmed_grade + - current_confirmed_grade + - method + - source + - calibration_status + properties: + status: + type: string + enum: + - not_eligible + - not_confirmed + - assigned + - unchanged + previous_confirmed_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + current_confirmed_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + method: + oneOf: + - type: string + enum: + - demo_basic_pass_mark + - type: 'null' + source: + oneOf: + - type: string + enum: + - synthetic_demo + - type: 'null' + calibration_status: + oneOf: + - $ref: '#/CalibrationStatus' + - type: 'null' +AssessmentResultHistoryPage: + type: object + description: Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending. Legacy v1 results omit category_decision. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 50 + items: + $ref: '#/AssessmentRealResult' + page: + $ref: '#/PageInfo' +AssessmentFinalizeConflictProblem: + type: object + description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + title: + type: string + minLength: 1 + maxLength: 200 + status: + type: integer + format: int32 + const: 409 + code: + type: string + enum: + - state_conflict + - idempotency_in_progress + detail: + type: string + maxLength: 1000 + instance: + type: string + format: uri-reference + maxLength: 2048 + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + errors: + type: array + maxItems: 100 + items: + $ref: '#/ProblemFieldError' + pending_item_ids: + type: array + maxItems: 220 + uniqueItems: true + items: + type: string + format: uuid + description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items. +AssessmentRealResultCommon: + type: object + description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: '#/SpecializationCode' + target_grade: + $ref: '#/GradeCode' + root_attempt_id: + description: Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + readOnly: true + task_language: + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + kind: + type: string + enum: + - root + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + versions: + $ref: '#/AssessmentVersions' + outcome: + $ref: '#/AssessmentOutcome' + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: '#/AssessmentNotDeterminedReason' + - type: 'null' + confirmed_grade: + description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + previous_confirmed_grade: + description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + category_decision: + $ref: '#/AssessmentCategoryDecisionView' + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: '#/AssessmentStrength' + - type: 'null' + calibration_status: + $ref: '#/CalibrationStatus' + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: '#/AssessmentLimitation' + uncertainty: + description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. + oneOf: + - $ref: '#/AssessmentUncertainty' + - type: 'null' + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: '#/BasicScore' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: '#/AssessmentPracticeResult' + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: '#/AssessmentGap' + durations: + $ref: '#/AssessmentDurations' + next_steps: + type: array + maxItems: 5 + items: + $ref: '#/AssessmentNextStep' + decided_at: + $ref: '#/Timestamp' +AssessmentQualifiedResult: + description: Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null. + allOf: + - $ref: '#/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - root_attempt_id + - chain_deadline +AssessmentCorrectiveResult: + description: Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain. + allOf: + - $ref: '#/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/Timestamp' + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline +AssessmentExpressResult: + type: object + description: Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - summary + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + type: 'null' + description: Express training does not assess a specialization. + target_grade: + type: 'null' + description: Express training does not assess a target grade. + task_language: + type: 'null' + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + versions: + $ref: '#/AssessmentVersions' + outcome: + type: string + enum: + - demonstration + not_determined_reason: + type: 'null' + confirmed_grade: + type: 'null' + description: Express training never confirms a grade. + previous_confirmed_grade: + type: 'null' + strength: + type: 'null' + calibration_status: + type: string + enum: + - uncalibrated + limitations: + type: array + minItems: 1 + maxItems: 1 + items: + type: string + enum: + - demonstration_only + uncertainty: + type: 'null' + description: Express training computes no ability estimate or percentile. + basic_score: + type: 'null' + practices: + type: array + maxItems: 0 + items: + $ref: '#/AssessmentPracticeResult' + gaps: + type: array + maxItems: 0 + items: + $ref: '#/AssessmentGap' + durations: + $ref: '#/AssessmentDurations' + next_steps: + type: array + maxItems: 0 + items: + $ref: '#/AssessmentNextStep' + summary: + type: string + minLength: 1 + maxLength: 2000 + description: Short educational feedback about this training run. + decided_at: + $ref: '#/Timestamp' +AssessmentGradeAvailabilityStatus: + type: string + description: 'Whether an attempt for the grade can start now. + + + - available: CreateMyAssessmentAttempt can start it. + + - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. + + - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it. + + - insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families.' + enum: + - available + - active_attempt + - cooldown + - insufficient_bank +AssessmentGradeAvailability: + type: object + description: Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit. + additionalProperties: false + required: + - grade + - status + - mode + - available_at + - time_limit_seconds + - max_sessions + - max_items + - practice_required + properties: + grade: + $ref: '#/GradeCode' + status: + $ref: '#/AssessmentGradeAvailabilityStatus' + mode: + description: Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here. + oneOf: + - $ref: '#/AssessmentRealMode' + - type: 'null' + available_at: + description: When the status is `cooldown`, the first time the attempt can start; otherwise null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + time_limit_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: Time from the start to `expires_at`. + max_sessions: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 10 + description: Session limit within the time limit. + max_items: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 100 + description: Item limit, as in `AssessmentProgress.max_items`. + practice_required: + type: + - boolean + - 'null' + description: Whether the attempt would include a main code practice. +AssessmentSpecializationAvailability: + type: object + description: Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals. + additionalProperties: false + required: + - specialization + - confirmed_grade + - confirmed_basis + - active_attempt_id + - grades + properties: + specialization: + $ref: '#/SpecializationCode' + confirmed_grade: + description: Currently confirmed grade of the specialization, or null. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + confirmed_basis: + description: What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` marks a demonstration category, which is not a validated measurement and must not be shown as a real confirmation. + oneOf: + - $ref: '#/EvidenceBasis' + - type: 'null' + active_attempt_id: + type: + - string + - 'null' + format: uuid + description: Identifier of the active attempt of the specialization, or null. + grades: + type: array + maxItems: 10 + description: Every grade of the scale in ascending order. + items: + $ref: '#/AssessmentGradeAvailability' +AssessmentAvailability: + type: object + description: Assessment availability for the specializations of the current candidate's questionnaire, derived at the time of the request. + additionalProperties: false + required: + - specializations + properties: + specializations: + type: array + maxItems: 2 + description: Questionnaire specializations in questionnaire order. + items: + $ref: '#/AssessmentSpecializationAvailability' +AssessmentSignalEvent: + description: One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention. + oneOf: + - $ref: '#/AssessmentFocusLossSignal' + - $ref: '#/AssessmentClipboardSignal' + - $ref: '#/AssessmentFullscreenExitSignal' + - $ref: '#/AssessmentCaptureSignal' + discriminator: + propertyName: kind + mapping: + focus_loss: '#/AssessmentFocusLossSignal' + copy: '#/AssessmentClipboardSignal' + paste: '#/AssessmentClipboardSignal' + cut: '#/AssessmentClipboardSignal' + fullscreen_exit: '#/AssessmentFullscreenExitSignal' + screenshot_key: '#/AssessmentCaptureSignal' + devtools_open: '#/AssessmentCaptureSignal' +AssessmentFocusLossSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - duration_ms + properties: + kind: + type: string + enum: + - focus_loss + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' + duration_ms: + type: integer + format: int32 + minimum: 1 + maximum: 259200000 + description: Client-measured duration away from the assessment tab or window, in milliseconds. +AssessmentClipboardSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - size_bytes + properties: + kind: + type: string + enum: + - copy + - paste + - cut + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' + size_bytes: + type: integer + format: int32 + minimum: 0 + maximum: 2147483647 + description: Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an approximate size and the selected text is not read. The server applies no conversion and treats the value as an order-of-magnitude indicator. +AssessmentFullscreenExitSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - fullscreen_exit + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' +AssessmentCaptureSignal: + type: object + description: 'A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.' + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - screenshot_key + - devtools_open + item_instance_id: + $ref: '#/AssessmentItemId' + occurred_at: + $ref: '#/Timestamp' +AssessmentSignalBatch: + type: object + description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events. + additionalProperties: false + required: + - events + properties: + events: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/AssessmentSignalEvent' +AssessmentSignalReceipt: + type: object + description: Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band. + additionalProperties: false + required: + - status + - accepted_events + - received_at + properties: + status: + type: string + enum: + - accepted + - saturated + description: '`saturated` means no event from this batch was stored because the attempt''s bounded evidence storage is full.' + accepted_events: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of events stored from this batch; zero when saturated. + received_at: + $ref: '#/Timestamp' +AssessmentSignalNoticeVersion: + type: integer + format: int32 + minimum: 1 + maximum: 2147483647 + description: Version of the notice text about the collected signals. The client shows the text of the version it knows and sends that version back when the candidate confirms; a changed text gets a new version and needs a new confirmation. +AssessmentSignalNotice: + type: object + description: State of the notice about the signals that are collected during a real assessment attempt. The acknowledgement is a record that the candidate was informed. It is not a consent, grants no purpose, and neither enables nor blocks signal storage; C3 remains the only consent that the signal operation checks. + additionalProperties: false + required: + - notice_version + - acknowledged + - acknowledged_at + properties: + notice_version: + allOf: + - $ref: '#/AssessmentSignalNoticeVersion' + description: The version the server currently requires the candidate to acknowledge. + acknowledged: + type: boolean + description: True when the candidate acknowledged `notice_version`. + acknowledged_at: + description: Server time of the first acknowledgement of this version, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +AssessmentSignalNoticeAcknowledgement: + type: object + description: The notice version the candidate was shown and acknowledged. + additionalProperties: false + required: + - notice_version + properties: + notice_version: + $ref: '#/AssessmentSignalNoticeVersion' +ProfileVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`. + examples: + - 4 +ProfileItemStatus: + type: string + description: 'Confirmation state of a profile list item, and the decision that a request sends for a field or an item. + + + - confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure. + + - extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses. + + + A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list.' + enum: + - confirmed + - extracted +ProfileClaimStatus: + type: string + description: 'Confirmation state of a single profile field. + + + - confirmed: the candidate typed the value or confirmed a suggestion. + + - extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0. + + - unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer.' + enum: + - confirmed + - extracted + - unknown +ProfileClaimOrigin: + type: string + description: 'Where the value of a profile field or item came from. The server sets it; a request never sends it. + + + - manual: the candidate typed the value in the form. `quote` and `extraction_version` are null. + + - extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume. + + - imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link. + + + Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.' + enum: + - manual + - extracted_from_resume + - imported +ProfileClaimTrustLevel: + type: integer + format: int32 + minimum: 0 + maximum: 0 + description: 'Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.' + examples: + - 0 +ProfileClaimQuote: + type: string + minLength: 1 + maxLength: 300 + description: Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML. +ProfileClaimSource: + type: object + description: 'Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.' + additionalProperties: false + required: + - origin + - trust_level + - quote + - extraction_version + - confirmed_at + properties: + origin: + $ref: '#/ProfileClaimOrigin' + trust_level: + $ref: '#/ProfileClaimTrustLevel' + quote: + description: Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt. + oneOf: + - $ref: '#/ProfileClaimQuote' + - type: 'null' + extraction_version: + description: Extractor version for an extracted or imported value, or null for a manual value. + oneOf: + - $ref: '#/NeedVersionLabel' + - type: 'null' + confirmed_at: + description: Time the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +ProfileLocationName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +ProfileSalaryMinimum: + type: object + description: 'The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.' + additionalProperties: false + required: + - amount + - currency + - period + - tax_basis + properties: + amount: + $ref: '#/RubAmount' + currency: + $ref: '#/CurrencyCode' + period: + $ref: '#/SalaryPeriod' + tax_basis: + $ref: '#/SalaryTaxBasis' +ProfileSoftSkill: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML. +ProfileEmployerName: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate's career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +ProfileExperienceSummary: + type: string + minLength: 1 + maxLength: 1000 + description: Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML. +ProfileYearMonth: + type: string + minLength: 7 + maxLength: 7 + pattern: ^[0-9]{4}-(0[1-9]|1[0-2])$ + description: Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future. + examples: + - 2024-03 +ProfileFullNameClaim: + type: object + description: Full name of the candidate with its confirmation state and provenance. The value is personal data. It is disclosed to one organization only through the contact grant of the consent C4 and never appears in an organization-visible schema. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/ContactFullName' + - type: 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfileEmailClaim: + type: object + description: 'Contact email of the candidate with its confirmation state and provenance. It is personal data. It is a contact channel that the candidate gives, not the login of the account: the two may differ, the server never sends mail to it and never verifies it. `value` and `source` are null exactly when `status` is `unknown`.' + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/EmailAddress' + - type: 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfilePhoneClaim: + type: object + description: Contact phone number of the candidate with its confirmation state and provenance. It is personal data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/ContactPhoneNumber' + - type: 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfileTelegramClaim: + type: object + description: Telegram username of the candidate with its confirmation state and provenance. It is personal data, stored with the leading @ of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/ContactTelegramUsername' + - type: 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfileLocationClaim: + type: object + description: Place of the candidate with its confirmation state and provenance. It is personal data. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/ProfileLocationName' + - type: 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfileRelocationClaim: + type: object + description: Whether the candidate is ready to relocate, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; the server never assumes an answer. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + type: + - boolean + - 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfileSalaryMinimumClaim: + type: object + description: Lowest acceptable salary with its confirmation state and provenance. It is personal data that no organization reads. `value` and `source` are null exactly when `status` is `unknown`; the server never substitutes zero or a market estimate. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/ProfileSalaryMinimum' + - type: 'null' + source: + oneOf: + - $ref: '#/ProfileClaimSource' + - type: 'null' +ProfileContacts: + type: object + description: Contact channels of the candidate. Each channel is a claim of its own, and the candidate fills in any subset. The kinds are the ones that the contact disclosure (consent C4) can pass on, with the same value formats, so a disclosure never has to convert or drop a stored value; adding a kind, such as a link to a code repository, is a contract change in both places. Contacts leave the profile only through a contact grant, never in a card or a search result. All values are personal data. + additionalProperties: false + required: + - email + - phone + - telegram + properties: + email: + $ref: '#/ProfileEmailClaim' + phone: + $ref: '#/ProfilePhoneClaim' + telegram: + $ref: '#/ProfileTelegramClaim' +ProfileTerms: + type: object + description: 'Conditions that the candidate wants: the place, readiness to relocate, and the lowest salary. Acceptable work formats are not repeated here; they are the `work_formats` of the questionnaire `WorkContext`, the only place that holds them. These are the candidate''s wishes, never the terms of an invitation, which an organization offers and which the invitation contract describes.' + additionalProperties: false + required: + - location + - relocation + - salary_minimum + properties: + location: + $ref: '#/ProfileLocationClaim' + relocation: + $ref: '#/ProfileRelocationClaim' + salary_minimum: + $ref: '#/ProfileSalaryMinimumClaim' +ProfileStackItem: + type: object + description: 'One technology tag of the candidate''s stack with its confirmation state and provenance. The profile stack is one list for the whole profile; the questionnaire holds the tags of each chosen specialization with the same `StackTag` meaning, and the two lists are independent: the server never copies one into the other. A tag is a descriptive attribute and never forms a category.' + additionalProperties: false + required: + - tag + - status + - source + properties: + tag: + $ref: '#/StackTag' + status: + $ref: '#/ProfileItemStatus' + source: + $ref: '#/ProfileClaimSource' +ProfileSoftSkillItem: + type: object + description: One soft skill of the candidate with its confirmation state and provenance. It is a claim; no assessment checks it. + additionalProperties: false + required: + - skill + - status + - source + properties: + skill: + $ref: '#/ProfileSoftSkill' + status: + $ref: '#/ProfileItemStatus' + source: + $ref: '#/ProfileClaimSource' +ProfileRoleItem: + type: object + description: 'One role of the candidate: a specialization of the catalog with the grade that the candidate claims for it. `self_assessed_grade` is a claim, the same one that the questionnaire calls `self_assessed_grade` for its at most two chosen specializations: it influences nothing but the display and never becomes a confirmed grade or a category. The questionnaire value starts the assessment and the profile value is what the profile shows; the two are saved separately and the server never copies one into the other. A confirmed grade comes only from an assessment result and appears in `confirmed_categories` of the profile, never in a role; unknown fields such as `confirmed_grade` or `category` are rejected.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - status + - source + properties: + specialization: + $ref: '#/SpecializationCode' + self_assessed_grade: + description: Grade that the candidate claims in the specialization, or null when the candidate names none. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + status: + $ref: '#/ProfileItemStatus' + source: + $ref: '#/ProfileClaimSource' +ProfileExperienceItem: + type: object + description: 'One entry of the candidate''s work history with its confirmation state and provenance. An entry describes the work by its specialization and tasks rather than by a job title, and it is a claim of trust level 0. It is different from the `CandidateExperience` of the questionnaire, which holds only the total months of commercial and academic experience of a chosen specialization as a hint for the assessment: the two are saved separately, and the server neither adds the entries up for the questionnaire nor fills the entries from it. An entry is personal data.' + additionalProperties: false + required: + - employer_name + - specialization + - started_on + - ended_on + - summary + - status + - source + properties: + employer_name: + description: Employer of the entry, or null when the candidate gives none. + oneOf: + - $ref: '#/ProfileEmployerName' + - type: 'null' + specialization: + $ref: '#/SpecializationCode' + started_on: + $ref: '#/ProfileYearMonth' + ended_on: + description: Last month of the work, or null when the candidate still works there. It is not earlier than `started_on`. + oneOf: + - $ref: '#/ProfileYearMonth' + - type: 'null' + summary: + description: Tasks and results of the entry, or null when the candidate gives none. + oneOf: + - $ref: '#/ProfileExperienceSummary' + - type: 'null' + status: + $ref: '#/ProfileItemStatus' + source: + $ref: '#/ProfileClaimSource' +ProfileProjectTitle: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Name of a project as the candidate wants an organization to read it. It has no leading or trailing whitespace and no line breaks. When the candidate publishes the `projects` card field, the title reaches the anonymous card and match explanations, so it must not contain a name, a contact, or a repository address. Plain text; clients show it as text, never as HTML. +ProfileProjectDescription: + type: string + minLength: 1 + maxLength: 500 + description: What the project does and what the candidate did in it. It may contain line breaks. When the `projects` card field is published it reaches the anonymous card. Plain text; clients show it as text, never as HTML. +ProfileRepositoryUrl: + type: string + minLength: 22 + maxLength: 160 + pattern: ^https://github\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$ + description: Address of a public GitHub repository of the project in the form https://github.com//. The server accepts only this host and form, removes a trailing slash and a `.git` suffix, and stores the canonical address. Organizations never receive the address before an accepted invitation, because the owner name can identify the candidate. + examples: + - https://github.com/example-org/payments-ledger +ProfileRepositoryCheckState: + type: string + description: 'Result of the latest server check of a project repository on the public GitHub API. The server only reads public metadata; a check never proves that the candidate wrote the code. + + + - pending: the check is scheduled and has not finished yet. + + - verified: the repository exists and is public. Match explanations may then say that the project is backed by a public repository. + + - not_found: GitHub reports no such public repository; it may be private, renamed to another owner, or deleted. + + - unavailable: GitHub could not be asked, for example because of its rate limit; the server retries later.' + enum: + - pending + - verified + - not_found + - unavailable +ProfileRepositoryCheck: + type: object + description: State of the server check of a project repository. Read-only; no request writes it. The fetched metadata itself (description, topics, languages, and a plain-text README excerpt) is used only for ranking and is never returned or shown. + additionalProperties: false + required: + - state + - checked_at + properties: + state: + $ref: '#/ProfileRepositoryCheckState' + checked_at: + description: Time of the last finished check, or null before the first one. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +ProfileProjectStack: + type: array + maxItems: 10 + description: Technology tags of the project, each tag at most once without regard to letter case. + items: + $ref: '#/StackTag' +ProfileRepositoryCheckRequest: + type: object + description: Result of a request to check the linked repositories again. + additionalProperties: false + required: + - scheduled + properties: + scheduled: + type: integer + format: int32 + minimum: 0 + maximum: 10 + description: Number of repository checks that the request scheduled. +ProfileProjectItem: + type: object + description: One project of the candidate with its confirmation state and provenance. A project is a claim of trust level 0 that the candidate types; a linked repository adds a separate server check (`repository_check`), never a higher trust level. The project reaches organizations only when the candidate publishes the `projects` card field, and then without the repository address. + additionalProperties: false + required: + - title + - description + - stack + - repository_url + - repository_check + - status + - source + properties: + title: + $ref: '#/ProfileProjectTitle' + description: + description: What the project is about, or null when the candidate gives nothing. + oneOf: + - $ref: '#/ProfileProjectDescription' + - type: 'null' + stack: + $ref: '#/ProfileProjectStack' + repository_url: + description: Canonical repository address, or null when the project links none. + oneOf: + - $ref: '#/ProfileRepositoryUrl' + - type: 'null' + repository_check: + description: The server check of the linked repository, or null when the project links none. + oneOf: + - $ref: '#/ProfileRepositoryCheck' + - type: 'null' + status: + $ref: '#/ProfileItemStatus' + source: + $ref: '#/ProfileClaimSource' +ProfileExperienceOverlapStatus: + type: string + description: Whether the candidate confirmed that two overlapping periods are genuine parallel work. + enum: + - needs_confirmation + - confirmed +ProfileExperienceOverlap: + type: object + description: One pair of work history entries whose inclusive month ranges overlap. The indices refer to the experience array in this profile version. `confirmed` records an explicit acknowledgement for this pair of dates; otherwise the pair needs confirmation before a changed profile can be saved. + additionalProperties: false + required: + - first_index + - second_index + - status + properties: + first_index: + type: integer + minimum: 0 + maximum: 19 + second_index: + type: integer + minimum: 1 + maximum: 19 + status: + $ref: '#/ProfileExperienceOverlapStatus' +ProfileExperiencePeriod: + type: object + description: The exact month range of an experience entry, copied into a confirmation. + additionalProperties: false + required: + - started_on + - ended_on + properties: + started_on: + $ref: '#/ProfileYearMonth' + ended_on: + description: Last month of work, or null when the period is open-ended. + oneOf: + - $ref: '#/ProfileYearMonth' + - type: 'null' +ProfileParallelPeriodConfirmation: + type: object + description: Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read. + additionalProperties: false + required: + - first_index + - second_index + - first_period + - second_period + properties: + first_index: + type: integer + minimum: 0 + maximum: 19 + second_index: + type: integer + minimum: 1 + maximum: 19 + first_period: + $ref: '#/ProfileExperiencePeriod' + second_period: + $ref: '#/ProfileExperiencePeriod' +ProfileConfirmedCategory: + type: object + description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that is not a validated measurement.' + additionalProperties: false + required: + - specialization + - grade + - basis + - confirmed_at + - attempt_id + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' + basis: + $ref: '#/EvidenceBasis' + confirmed_at: + $ref: '#/Timestamp' + attempt_id: + type: string + format: uuid + description: Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate. +CandidateProfile: + type: object + description: 'The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, projects, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one. + + Every value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`. + + The profile is manual by nature and complete without a file: no field requires a resume, the ML service, or an FSP account, and a candidate with none of them has the same fields. Work formats live in the questionnaire; a candidate''s assessment starts from the questionnaire, not from this profile.' + additionalProperties: false + required: + - version + - full_name + - contacts + - stack + - roles + - experience + - experience_overlaps + - soft_skills + - projects + - terms + - confirmed_categories + - updated_at + properties: + version: + $ref: '#/ProfileVersion' + full_name: + $ref: '#/ProfileFullNameClaim' + contacts: + $ref: '#/ProfileContacts' + stack: + type: array + maxItems: 30 + description: Technology tags in the order the candidate gave them, each tag at most once without regard to letter case. + items: + $ref: '#/ProfileStackItem' + roles: + type: array + maxItems: 9 + description: Roles in the order the candidate gave them, each specialization at most once. + items: + $ref: '#/ProfileRoleItem' + experience: + type: array + maxItems: 20 + description: Work history entries in the order the candidate gave them. + items: + $ref: '#/ProfileExperienceItem' + experience_overlaps: + type: array + maxItems: 190 + description: Every pair of overlapping experience periods, with its confirmation status. The indices refer to this version's experience array. + items: + $ref: '#/ProfileExperienceOverlap' + soft_skills: + type: array + maxItems: 10 + description: Soft skills in the order the candidate gave them, each skill at most once without regard to letter case. + items: + $ref: '#/ProfileSoftSkillItem' + projects: + type: array + maxItems: 10 + description: Projects in the order the candidate gave them, each repository address at most once. + items: + $ref: '#/ProfileProjectItem' + terms: + $ref: '#/ProfileTerms' + confirmed_categories: + type: array + maxItems: 9 + description: Categories that assessment results confirmed, at most one per specialization, in catalog order. Read-only and empty until an assessment confirms a grade. + items: + $ref: '#/ProfileConfirmedCategory' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +ProfileFullNameInput: + type: object + description: Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/ContactFullName' + status: + $ref: '#/ProfileItemStatus' +ProfileEmailInput: + type: object + description: Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/EmailAddress' + status: + $ref: '#/ProfileItemStatus' +ProfilePhoneInput: + type: object + description: Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/ContactPhoneNumber' + status: + $ref: '#/ProfileItemStatus' +ProfileTelegramInput: + type: object + description: Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/ContactTelegramUsername' + status: + $ref: '#/ProfileItemStatus' +ProfileLocationInput: + type: object + description: Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/ProfileLocationName' + status: + $ref: '#/ProfileItemStatus' +ProfileRelocationInput: + type: object + description: Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + type: boolean + status: + $ref: '#/ProfileItemStatus' +ProfileSalaryMinimumInput: + type: object + description: Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/ProfileSalaryMinimum' + status: + $ref: '#/ProfileItemStatus' +ProfileContactsInput: + type: object + description: 'Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed if it was set.' + additionalProperties: false + required: + - email + - phone + - telegram + properties: + email: + oneOf: + - $ref: '#/ProfileEmailInput' + - type: 'null' + phone: + oneOf: + - $ref: '#/ProfilePhoneInput' + - type: 'null' + telegram: + oneOf: + - $ref: '#/ProfileTelegramInput' + - type: 'null' +ProfileTermsInput: + type: object + description: 'Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it was set.' + additionalProperties: false + required: + - location + - relocation + - salary_minimum + properties: + location: + oneOf: + - $ref: '#/ProfileLocationInput' + - type: 'null' + relocation: + oneOf: + - $ref: '#/ProfileRelocationInput' + - type: 'null' + salary_minimum: + oneOf: + - $ref: '#/ProfileSalaryMinimumInput' + - type: 'null' +ProfileStackItemInput: + type: object + description: Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - tag + - status + properties: + tag: + $ref: '#/StackTag' + status: + $ref: '#/ProfileItemStatus' +ProfileSoftSkillItemInput: + type: object + description: Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - skill + - status + properties: + skill: + $ref: '#/ProfileSoftSkill' + status: + $ref: '#/ProfileItemStatus' +ProfileRoleItemInput: + type: object + description: 'Decision about one role in a request; see CandidateProfileUpdate for the rules of `status`. The object has no confirmed grade and no category: unknown fields are rejected.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - status + properties: + specialization: + $ref: '#/SpecializationCode' + self_assessed_grade: + description: Grade that the candidate claims, or null when the candidate names none. + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + status: + $ref: '#/ProfileItemStatus' +ProfileExperienceItemInput: + type: object + description: Decision about one work history entry in a request; see CandidateProfileUpdate for the rules of `status`. The server also requires `ended_on` not to precede `started_on` and no month to lie in the future, and answers 400 with the pointer of the month. + additionalProperties: false + required: + - employer_name + - specialization + - started_on + - ended_on + - summary + - status + properties: + employer_name: + oneOf: + - $ref: '#/ProfileEmployerName' + - type: 'null' + specialization: + $ref: '#/SpecializationCode' + started_on: + $ref: '#/ProfileYearMonth' + ended_on: + oneOf: + - $ref: '#/ProfileYearMonth' + - type: 'null' + summary: + oneOf: + - $ref: '#/ProfileExperienceSummary' + - type: 'null' + status: + $ref: '#/ProfileItemStatus' +ProfileProjectItemInput: + type: object + description: Decision about one project in a request; see CandidateProfileUpdate for the rules of `status`. The server answers 400 with the pointer of the field for a repository address that is not a GitHub repository address, a repeated repository, or a repeated stack tag. + additionalProperties: false + required: + - title + - description + - stack + - repository_url + - status + properties: + title: + $ref: '#/ProfileProjectTitle' + description: + oneOf: + - $ref: '#/ProfileProjectDescription' + - type: 'null' + stack: + $ref: '#/ProfileProjectStack' + repository_url: + oneOf: + - $ref: '#/ProfileRepositoryUrl' + - type: 'null' + status: + $ref: '#/ProfileItemStatus' +CandidateProfileUpdate: + type: object + description: 'Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list; only `projects` may be omitted, which keeps the stored projects. The body is personal data. + + Each value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category.' + additionalProperties: false + required: + - expected_version + - full_name + - contacts + - stack + - roles + - experience + - soft_skills + - terms + properties: + expected_version: + $ref: '#/ProfileVersion' + full_name: + oneOf: + - $ref: '#/ProfileFullNameInput' + - type: 'null' + contacts: + $ref: '#/ProfileContactsInput' + stack: + type: array + maxItems: 30 + description: Technology tags. The schema limits the count; the server also answers 400 with the pointer of a tag that repeats an earlier one without regard to letter case, for example `/stack/2/tag`. + items: + $ref: '#/ProfileStackItemInput' + roles: + type: array + maxItems: 9 + description: Roles. The server answers 400 with the pointer of a role whose specialization repeats an earlier one, for example `/roles/1/specialization`. + items: + $ref: '#/ProfileRoleItemInput' + experience: + type: array + maxItems: 20 + description: Work history entries. + items: + $ref: '#/ProfileExperienceItemInput' + confirmed_parallel_periods: + type: array + maxItems: 190 + description: Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and repeat the exact normalized started_on and ended_on values of those entries in this body. A changed or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected. + items: + $ref: '#/ProfileParallelPeriodConfirmation' + soft_skills: + type: array + maxItems: 10 + description: Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case. + items: + $ref: '#/ProfileSoftSkillItemInput' + projects: + type: array + maxItems: 10 + description: 'Projects. Unlike the other lists this one is optional: a body without `projects` keeps the stored projects unchanged, so a client that does not know the section never deletes it, and an array, including an empty one, replaces the stored list. A new or changed repository address schedules a server check on the public GitHub API after the save commits; the save itself never waits for GitHub.' + items: + $ref: '#/ProfileProjectItemInput' + terms: + $ref: '#/ProfileTermsInput' +DirectionCode: + type: string + description: 'Stable code of a professional direction, the group that a specialization belongs to. + + + - development: Development. + + - infrastructure: Infrastructure. + + - data: Data. + + - security: Security. + + - quality: Quality. + + + Adding a value is a contract change.' + enum: + - development + - infrastructure + - data + - security + - quality +SpecializationCode: + type: string + description: 'Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here. + + + - backend: Backend (development). + + - frontend: Frontend (development). + + - mobile: Mobile (development). + + - network_engineer: Network Engineer (infrastructure). + + - devops_sre: DevOps/SRE (infrastructure). + + - data_analyst: Data Analyst (data). + + - ds_ml: DS/ML (data). + + - information_security: Information security (security). + + - qa: QA (quality). + + + Adding a value is a contract change; renaming or removing one is a breaking change.' + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa +GradeCode: + type: string + description: 'Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.' + enum: + - intern + - junior + - middle + - senior +TaskLanguage: + type: string + description: Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate's platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change. + enum: + - python + - go +TestAvailabilityStatus: + type: string + description: Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready. + enum: + - available + - in_development +TestAvailability: + type: object + description: Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty. + additionalProperties: false + required: + - status + - grades + - task_languages + - note + properties: + status: + $ref: '#/TestAvailabilityStatus' + grades: + type: array + maxItems: 10 + uniqueItems: true + description: Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed. + items: + $ref: '#/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization. + items: + $ref: '#/TaskLanguage' + note: + type: + - string + - 'null' + minLength: 1 + maxLength: 300 + description: Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML. +CatalogSpecialization: + type: object + description: Specialization in the catalog with its assessment availability. + additionalProperties: false + required: + - code + - title + - test_availability + properties: + code: + $ref: '#/SpecializationCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + test_availability: + $ref: '#/TestAvailability' +CatalogDirection: + type: object + description: Professional direction with its specializations. Each specialization belongs to exactly one direction. + additionalProperties: false + required: + - code + - title + - specializations + properties: + code: + $ref: '#/DirectionCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + specializations: + type: array + minItems: 1 + maxItems: 20 + description: Specializations of the direction in display order. + items: + $ref: '#/CatalogSpecialization' +CatalogGrade: + type: object + description: Grade of the scale with its display name. + additionalProperties: false + required: + - code + - title + properties: + code: + $ref: '#/GradeCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. +SpecializationCatalog: + type: object + description: Catalog of directions, specializations, and the grade scale that the questionnaire and the assessment use. The catalog is reference data and identical for every caller; it contains no personal data. + additionalProperties: false + required: + - directions + - grades + properties: + directions: + type: array + minItems: 1 + maxItems: 20 + description: Directions in display order. + items: + $ref: '#/CatalogDirection' + grades: + type: array + minItems: 1 + maxItems: 10 + description: Grade scale in ascending order. + items: + $ref: '#/CatalogGrade' +ConsentPurposeCode: + type: string + description: 'One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. + + + - c1: processing of personal data, given at registration. + + - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change. + + - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. + + - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. + + - c5: import of FSP results. + + + ConsentPurpose lists the subset whose text the client may read before an account exists.' + enum: + - c1 + - c2 + - c3 + - c4 + - c5 +ConsentSettingsPurpose: + type: string + description: Consent text that an authenticated account can read and accept in settings. C4 is scoped to an invitation and organization, so it is not available through the general settings flow. + enum: + - c1 + - c2 + - c3 + - c5 +ConsentSettingsRevokePurpose: + type: string + description: Consent that can be revoked through the general settings flow. C1 uses the account deletion request, and C4 must be revoked for one organization. + enum: + - c2 + - c3 + - c5 +ConsentState: + type: string + description: 'State of a consent record, computed from the ledger. + + + - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation. + + - superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4. + + - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it.' + enum: + - active + - superseded + - revoked +ConsentSource: + type: string + description: 'Where the subject gave the consent. + + + - registration: the c1 acceptance of RegisterAccount. + + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). + + - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. + + + A c4 given when sending an application (PRD Q9) is planned as an additional value.' + enum: + - registration + - consent_settings + - invitation_acceptance +ConsentRevocationSource: + type: string + description: 'Who recorded a revocation. + + + - consent_settings: the subject revoked the consent in the product. + + - support_request: an operator recorded a revocation that the subject requested through support.' + enum: + - consent_settings + - support_request +ConsentOrganization: + type: object + description: Organization of a c4 consent as the consent recorded it. `name` is a snapshot of the name that the shown consent text carried at the time of the consent, and the stored text hash proves that text with this name; a later rename of the organization does not change it, so it can differ from the current name. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML. +ConsentRecord: + type: object + description: 'One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.' + additionalProperties: false + required: + - id + - purpose + - state + - text_version + - source + - granted_at + - revoked_at + - revocation_source + - organization + - fields + - invitation_id + - invitation_terms_version + properties: + id: + type: string + format: uuid + description: Identifier of the record. + purpose: + $ref: '#/ConsentPurposeCode' + state: + $ref: '#/ConsentState' + text_version: + description: Version of the consent text that the subject accepted. + allOf: + - $ref: '#/ConsentTextVersion' + source: + $ref: '#/ConsentSource' + granted_at: + $ref: '#/Timestamp' + revoked_at: + description: Moment of the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + revocation_source: + description: Who recorded the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/ConsentRevocationSource' + - type: 'null' + organization: + description: Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose. + oneOf: + - $ref: '#/ConsentOrganization' + - type: 'null' + fields: + type: + - array + - 'null' + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another. + items: + $ref: '#/ContactFieldKind' + invitation_id: + type: + - string + - 'null' + format: uuid + description: Invitation whose acceptance gave a c4 consent, or null for every other purpose. + invitation_terms_version: + description: Terms version that the acceptance accepted, or null for every other purpose. + oneOf: + - $ref: '#/InvitationTermsVersion' + - type: 'null' +ConsentRecordList: + type: object + description: One page of the consent ledger of the current account, newest grant first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Records of the page. + items: + $ref: '#/ConsentRecord' + page: + $ref: '#/PageInfo' +ConsentSettingsGrantRequest: + type: object + description: Accept the current published text shown by GetMyConsentText. The server checks its version again before recording the grant. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: '#/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Must be true to record an explicit acceptance. +ConsentDeletionRequest: + type: object + description: Durable request to delete the account and its personal data. The request is recorded before asynchronous processing starts; it does not mean deletion has completed. + additionalProperties: false + required: + - id + - status + - requested_at + properties: + id: + type: string + format: uuid + description: Identifier of the durable deletion request. + status: + type: string + enum: + - requested + - processing + description: Current state of the deletion request. + requested_at: + $ref: '#/Timestamp' +ContactFieldKind: + type: string + description: 'Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another. + + + - full_name: the full name from the profile. + + - email: the contact email address from the profile. + + - phone: the contact phone number from the profile. + + - telegram: the Telegram username from the profile. + + + The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change.' + enum: + - full_name + - email + - phone + - telegram +ContactConsentText: + type: object + description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger). + additionalProperties: false + required: + - text_version + - text + properties: + text_version: + $ref: '#/ConsentTextVersion' + text: + type: string + minLength: 1 + maxLength: 100000 + description: Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice. +ContactConsentOffer: + type: object + description: 'What the candidate can consent to in an acceptance: the consent text and the kinds of contact that the candidate''s profile holds now. It holds kinds only, never contact values, and nothing is preselected.' + additionalProperties: false + required: + - text + - available_fields + properties: + text: + $ref: '#/ContactConsentText' + available_fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance. + items: + $ref: '#/ContactFieldKind' +ContactConsentAcceptance: + type: object + description: 'Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization''s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.' + additionalProperties: false + required: + - text_version + - accepted + - fields + properties: + text_version: + $ref: '#/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Explicit consent. Only true is valid. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other. + items: + $ref: '#/ContactFieldKind' +ContactGrantState: + type: string + description: 'State of a contact grant. + + + - active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile. + + - revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant.' + enum: + - active + - revoked +ContactRevocationReason: + type: string + description: 'Why a contact grant was revoked, shown only to the candidate. + + + - consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed. + + - participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed. + + - visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead. + + + The withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant.' + enum: + - consent_revoked + - participation_cancelled + - visibility_closed +ContactAccessBlock: + type: string + description: 'Why an active grant does not allow a read now, shown only to the candidate. + + + - visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization.' + enum: + - visibility +ContactGrant: + type: object + description: 'Contact grant as the candidate reads it: which fields one organization may read, from which invitation and terms version, and whether it is still active. It holds kinds only, never contact values. A grant is stored apart from the invitation state, so a later change of the state does not change it unless the state is a cancellation by the candidate.' + additionalProperties: false + required: + - id + - fields + - status + - readable + - blocked_by + - terms_version + - consent_text_version + - granted_at + - revoked_at + - revocation_reason + properties: + id: + type: string + format: uuid + description: Identifier of the grant. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that the grant covers. + items: + $ref: '#/ContactFieldKind' + status: + $ref: '#/ContactGrantState' + readable: + type: boolean + description: 'Whether the organization can read the covered fields now: true only for an active grant whose current consent and visibility allow the read. The organization sees the same fact as `contact_access.status` `available`, without the reason.' + blocked_by: + description: Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has `revocation_reason` instead. + oneOf: + - $ref: '#/ContactAccessBlock' + - type: 'null' + terms_version: + description: Terms version of the invitation that the acceptance accepted. + allOf: + - $ref: '#/InvitationTermsVersion' + consent_text_version: + description: Version of the consent C4 text that the candidate accepted. + allOf: + - $ref: '#/ConsentTextVersion' + granted_at: + $ref: '#/Timestamp' + revoked_at: + description: Moment of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + revocation_reason: + description: Reason of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/ContactRevocationReason' + - type: 'null' +ContactPhoneNumber: + type: string + minLength: 8 + maxLength: 16 + pattern: ^\+[1-9][0-9]{6,14}$ + description: Phone number in the E.164 format, for example +70000000000. +ContactTelegramUsername: + type: string + minLength: 6 + maxLength: 33 + pattern: ^@[A-Za-z0-9_]{5,32}$ + description: Telegram username with the leading @. +ContactFullName: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML. +ContactDisclosure: + type: object + description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind. + additionalProperties: false + required: + - invitation_id + - grant_id + - fields + - granted_at + - full_name + - email + - phone + - telegram + properties: + invitation_id: + type: string + format: uuid + description: Invitation whose acceptance created the grant. + grant_id: + type: string + format: uuid + description: Grant that allows the read. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that the grant covers. + items: + $ref: '#/ContactFieldKind' + granted_at: + $ref: '#/Timestamp' + full_name: + oneOf: + - $ref: '#/ContactFullName' + - type: 'null' + email: + oneOf: + - $ref: '#/EmailAddress' + - type: 'null' + phone: + oneOf: + - $ref: '#/ContactPhoneNumber' + - type: 'null' + telegram: + oneOf: + - $ref: '#/ContactTelegramUsername' + - type: 'null' +EvidenceKind: + type: string + description: 'Whether a fact is a statement or an observation. + + + - claim: something the candidate stated that nothing confirmed separately. Its trust is 0. + + - measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3. + + + Assessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart.' + enum: + - claim + - measurement +EvidenceSourceType: + type: string + description: 'Where the fact comes from. + + + - assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source. + + + Adding a value is a contract change.' + enum: + - assessment_result +EvidenceAttribution: + type: string + description: 'Whose contribution the fact is. + + + - personal: the candidate''s own result. Every assessment fact is personal. + + - team_role: a team result with a confirmed role of the candidate. + + - team_unattributed: a team result without a confirmed role; it is not a personal skill. + + + Only `personal` is produced today.' + enum: + - personal + - team_role + - team_unattributed +EvidenceTrustLevel: + type: integer + format: int32 + minimum: 0 + maximum: 3 + description: 'Strength of the confirmation. + + + - 0: stated by the person, not confirmed separately. + + - 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed. + + - 2: a result tied to a confirmed identity or confirmed by an independent party. + + - 3: an in-person check with a matching confirmation. + + + A repeated statement, a sign-in, or a repeated tag of the same event never raises the level.' + examples: + - 1 +EvidenceVisibility: + type: string + description: 'Whether the fact may take part in what an organization reads. + + + - visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2. + + - hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result.' + enum: + - visible + - hidden +EvidenceSkillCode: + type: string + description: A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + - go + - postgresql + - kafka + - docker +EvidenceBasis: + type: string + description: 'What the measurement rests on. + + + - synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement.' + enum: + - synthetic_demo +EvidenceCalibrationStatus: + type: string + description: 'Calibration of the method behind the result. + + + - uncalibrated: the thresholds are initial values that no measurement has validated.' + enum: + - uncalibrated +EvidenceResult: + type: object + description: 'What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.' + additionalProperties: false + required: + - grade + - basis + - calibration_status + properties: + grade: + $ref: '#/GradeCode' + basis: + $ref: '#/EvidenceBasis' + calibration_status: + $ref: '#/EvidenceCalibrationStatus' +EvidenceSource: + type: object + description: Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt. + additionalProperties: false + required: + - type + - event_id + - result_id + properties: + type: + $ref: '#/EvidenceSourceType' + event_id: + type: string + format: uuid + description: Identifier of the source event. One event is one fact, however many skills it is tagged with. + result_id: + type: string + format: uuid + description: Identifier of the immutable result that produced the fact. +EvidenceFact: + type: object + description: One independent fact of the current candidate. `occurred_at` is when the source event ended; for an assessment it is the time of the decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their visibility, because the candidate owns them. + additionalProperties: false + required: + - id + - kind + - source + - skills + - result + - attribution + - trust + - occurred_at + - visibility + properties: + id: + type: string + format: uuid + description: Identifier of the fact. + kind: + $ref: '#/EvidenceKind' + source: + $ref: '#/EvidenceSource' + skills: + type: array + minItems: 1 + maxItems: 13 + uniqueItems: true + description: Skill tags of the event in ascending order. + items: + $ref: '#/EvidenceSkillCode' + result: + $ref: '#/EvidenceResult' + attribution: + $ref: '#/EvidenceAttribution' + trust: + $ref: '#/EvidenceTrustLevel' + occurred_at: + $ref: '#/Timestamp' + visibility: + $ref: '#/EvidenceVisibility' +EvidenceFactList: + type: object + description: One page of the facts of the current candidate, newest event first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Facts of the page. + items: + $ref: '#/EvidenceFact' + page: + $ref: '#/PageInfo' +OrganizationEvidenceFact: + type: object + description: 'The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.' + additionalProperties: false + required: + - skill + - grade + - trust + - basis + - calibration_status + - observed_year + properties: + skill: + $ref: '#/EvidenceSkillCode' + grade: + $ref: '#/GradeCode' + trust: + $ref: '#/EvidenceTrustLevel' + basis: + $ref: '#/EvidenceBasis' + calibration_status: + $ref: '#/EvidenceCalibrationStatus' + observed_year: + type: integer + format: int32 + minimum: 2000 + maximum: 9999 + description: Year (UTC) when the assessment ended. The month, day, and time stay with the candidate. + examples: + - 2026 +OrganizationEvidence: + type: object + description: 'The permitted evidence of one candidate card, ordered by skill: at most one fact for each category of the card (at most nine). The list is empty when no visible fact supports a category of the card.' + additionalProperties: false + required: + - items + properties: + items: + type: array + maxItems: 9 + description: Permitted facts, one for each supported category. + items: + $ref: '#/OrganizationEvidenceFact' HealthResponse: type: object additionalProperties: false @@ -8,3 +3768,4867 @@ 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: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. A successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step and leaves every other saved step unchanged. + + - 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: '#/ConsentPurposeCode' + 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: One-time token copied from the verification link and the password chosen for the registration that issued it. The password is never included in the link. + additionalProperties: false + required: + - token + - password + properties: + token: + $ref: '#/VerificationToken' + password: + type: string + minLength: 1 + maxLength: 128 + description: Password chosen for the registration that issued this token. It is sent in the request body and never appears in the verification link. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. +VerificationCode: + type: string + minLength: 6 + maxLength: 6 + pattern: ^[0-9]{6}$ + description: Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code. +EmailVerificationCodeRequest: + type: object + description: Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest. + additionalProperties: false + required: + - email + - code + - password + properties: + email: + $ref: '#/EmailAddress' + code: + $ref: '#/VerificationCode' + password: + type: string + minLength: 1 + maxLength: 128 + description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. +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' +InvitationVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.' + examples: + - 3 +InvitationTermsVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.' + examples: + - 2 +InvitationState: + type: string + description: 'State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`. + + + - draft: the organization prepares the terms. The candidate does not see the invitation. + + - delivered: the invitation is in the candidate''s inbox and the response deadline runs. + + - viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged. + + - counter: planned; the candidate sent the one counter offer. No MVP operation produces it. + + - accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists. + + - interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them. + + - declined: terminal; the candidate declined with a structured reason. No access arises. + + - expired: terminal; a server deadline passed, see `expiry_reason`. No access arises. + + - withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it. + + - cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked. + + + Planned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change.' + enum: + - draft + - delivered + - viewed + - counter + - accepted + - interview_scheduled + - interviewed + - negotiation + - terms_agreed + - no_deal + - declined + - expired + - withdrawn + - cancelled_by_candidate +InvitationExpiryReason: + type: string + description: 'Why an invitation expired. Set exactly when the state is `expired`, null otherwise. + + + - invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created. + + - negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it.' + enum: + - invitation_timeout + - negotiation_timeout +InvitationResponsePeriod: + type: integer + format: int32 + enum: + - 3 + - 7 + - 14 + description: 'Days the candidate has to answer, chosen by the organization in the draft from the product policy: 3, 7, or 14. The deadline starts at the first delivery and is never reset by an email, a view, or a counter offer.' + examples: + - 7 +InvitationRoleTitle: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Name of the offered role, for example "Middle Go developer in the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +InvitationTeamDescription: + type: string + minLength: 1 + maxLength: 1000 + pattern: \S + description: Description of the team the candidate would join, such as its size, roles, and way of working. It may contain line breaks and has at least one character that is not white space. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of employees or candidates. +InvitationOfferType: + type: string + description: 'Type of the offer. + + + - full_time: employment with a full working week. + + - part_time: employment with a part-time working week. + + - contract: a fixed-term or project contract outside employment. + + - internship: an internship. + + + Adding a value is a contract change.' + enum: + - full_time + - part_time + - contract + - internship +InvitationCommunicationChannel: + type: string + description: 'Channel through which the organization will contact the candidate after an acceptance. + + + - email: a letter to the email address the candidate disclosed. + + - phone: a call or a text to the phone number the candidate disclosed. + + - telegram: a message to the Telegram username the candidate disclosed. + + - video_call: an invitation to a video call, sent through one of the disclosed contacts. + + + The channel describes the organization''s plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel.' + enum: + - email + - phone + - telegram + - video_call +InvitationCommunicationMethod: + type: object + description: How the organization will contact the candidate after an acceptance. It is part of the terms, so the candidate sees it before choosing which contacts to disclose. An invitation without it cannot exist, because the terms require it. + additionalProperties: false + required: + - channel + - details + properties: + channel: + $ref: '#/InvitationCommunicationChannel' + details: + description: Optional short note, for example the first step or the expected time of the first contact, or null. Plain text without line breaks; it never contains a link or a contact of an employee. + oneOf: + - $ref: '#/InvitationCommunicationNote' + - type: 'null' +InvitationCommunicationNote: + type: string + minLength: 1 + maxLength: 300 + pattern: ^\S(?:.*\S)?$ + description: Short note on the communication method, for example "A 30-minute call with the team lead within three working days". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +InvitationPackageItemText: + type: string + minLength: 1 + maxLength: 300 + pattern: ^\S(?:.*\S)?$ + description: Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +InvitationPackageItemProvided: + type: object + description: The condition is part of the offer, with its description. + additionalProperties: false + required: + - status + - description + properties: + status: + type: string + enum: + - provided + description: + $ref: '#/InvitationPackageItemText' +InvitationPackageItemNotProvided: + type: object + description: The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description. + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - not_provided +InvitationPackageItem: + description: 'One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.' + oneOf: + - $ref: '#/InvitationPackageItemProvided' + - $ref: '#/InvitationPackageItemNotProvided' +InvitationPackage: + type: object + description: 'Required section of the package (PRD FR12): the bonus, the equipment, the training, and the voluntary health insurance (ДМС). Every field is required and is either provided with a description or explicitly not provided. The work format of the package is the required `work_formats` term, which has no "not provided" variant. Adding a required condition is a breaking change; an optional one is additive.' + additionalProperties: false + required: + - bonus + - equipment + - training + - health_insurance + properties: + bonus: + $ref: '#/InvitationPackageItem' + equipment: + $ref: '#/InvitationPackageItem' + training: + $ref: '#/InvitationPackageItem' + health_insurance: + $ref: '#/InvitationPackageItem' +InvitationTerms: + type: object + description: 'Terms of an invitation: everything the candidate sees before deciding and before any contact is disclosed. The same schema is the request field of a draft and the stored snapshot of a terms version, so a response can be sent back unchanged. Every field is required; a field that may have no value says so with an explicit variant (`location` null for a remote role, a package item `not_provided`). The terms never contain data of the candidate: no contact, no salary minimum, and no indicator derived from it. The server checks the cross-field rules after the schema and answers 400 validation_failed with the pointer of the field: the salary rules of SalaryRange with `/terms/salary/salary_to`, a missing place of work for the `office` or `hybrid` format with `/terms/location`, and a repeated technology in `tech_stack` with the pointer of the later item.' + additionalProperties: false + required: + - role_title + - specialization + - grade + - offer_type + - tasks + - team + - tech_stack + - work_formats + - location + - communication_method + - salary + - package + properties: + role_title: + $ref: '#/InvitationRoleTitle' + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' + offer_type: + $ref: '#/InvitationOfferType' + tasks: + type: array + minItems: 1 + maxItems: 20 + description: Work tasks of the role in the order given. + items: + $ref: '#/NeedTaskText' + team: + $ref: '#/InvitationTeamDescription' + tech_stack: + type: array + minItems: 1 + maxItems: 30 + uniqueItems: true + description: Technologies of the role. The server compares names without regard to letter case. + items: + $ref: '#/SkillName' + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Work formats the organization offers; the candidate may choose any of them. + items: + $ref: '#/WorkFormat' + location: + description: Place of work for the `office` or `hybrid` format, or null when the only format is `remote`. It is required with either of those formats. + oneOf: + - $ref: '#/NeedLocationName' + - type: 'null' + communication_method: + $ref: '#/InvitationCommunicationMethod' + salary: + $ref: '#/SalaryRange' + package: + $ref: '#/InvitationPackage' +InvitationNeedReference: + type: object + description: 'Need of the same organization that the invitation was built from, with the requirements version used. A direct invitation has no need. The link is informational: the invitation keeps its own terms, which may differ from the need, and a later change of the need never changes them.' + additionalProperties: false + required: + - need_id + - requirements_version + properties: + need_id: + type: string + format: uuid + description: Identifier of a need of the organization in the path. + requirements_version: + description: '`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.' + allOf: + - $ref: '#/NeedVersion' +InvitationSalaryFit: + type: string + description: 'Coarse indicator for the organization of how the salary range relates to the candidate''s hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis. + + + - within_range: the minimum is not above `B`. + + - up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`. + + - above: the minimum is more than 10% above `B`. + + - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. + + - not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis. + + + Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting. + + + The server never rejects or changes a range because of the minimum: a rejection would itself reveal it.' + enum: + - within_range + - up_to_10_percent_above + - above + - withheld + - not_available +InvitationContactAccessState: + type: string + description: 'Whether the organization may read the candidate''s contacts through GetOrganizationInvitationContacts now. + + + - not_granted: the candidate has not accepted this invitation, so no grant exists. + + - available: a grant from this invitation is active and the current consent and visibility allow the read. + + - closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate''s visibility allows the read, which only follows the candidate''s own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization.' + enum: + - not_granted + - available + - closed +InvitationContactAccess: + type: object + description: Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts. + additionalProperties: false + required: + - status + - fields + properties: + status: + $ref: '#/InvitationContactAccessState' + fields: + type: array + maxItems: 4 + uniqueItems: true + description: Kinds of contact that the read returns while `status` is `available`; empty otherwise. + items: + $ref: '#/ContactFieldKind' +InvitationOrganization: + type: object + description: Organization that sent the invitation, as the candidate sees it before deciding. The card that a candidate sees is `CandidateOrganizationCard` of the organization contract; returning it with the invitation is planned as an additive field, and this object only names the organization. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Public name of the organization. Plain text; clients show it as text, never as HTML. +InvitationDeclineReason: + type: string + description: 'Structured reason of a decline. Every reason is neutral and none requires a comment. + + + - salary: the salary range does not fit. + + - tasks: the role or the tasks do not fit. + + - stack: the technologies do not fit. + + - work_format: the work format or the place of work does not fit. + + - package: the package does not fit. + + - company: the company or its domain does not fit. + + - not_looking: the candidate is not looking for a job now. + + - other_offer: the candidate accepted another offer. + + - other: another reason ("Другое"); a comment stays optional. + + + The organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change.' + enum: + - salary + - tasks + - stack + - work_format + - package + - company + - not_looking + - other_offer + - other +InvitationDeclineComment: + type: string + minLength: 1 + maxLength: 500 + pattern: \S + description: Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML. +InvitationDeclineRecord: + type: object + description: The candidate's own decline, as the candidate reads it back. + additionalProperties: false + required: + - reason + - comment + - declined_at + properties: + reason: + $ref: '#/InvitationDeclineReason' + comment: + oneOf: + - $ref: '#/InvitationDeclineComment' + - type: 'null' + declined_at: + $ref: '#/Timestamp' +OrganizationInvitation: + type: object + description: 'Invitation as the organization reads it: the candidate handle, the current terms version, the state, the coarse salary indicator, and the contact access without contact values. It never contains the candidate''s name, email address, phone number, or other contact, the exact salary minimum, or the reason and comment of a decline.' + additionalProperties: false + required: + - id + - organization_id + - candidate_handle + - need + - state + - expiry_reason + - version + - terms_version + - terms + - response_period_days + - response_deadline_at + - salary_raise_used + - salary_fit + - contact_access + - created_at + - updated_at + - delivered_at + - viewed_at + - responded_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization_id: + type: string + format: uuid + description: Organization that owns the invitation, equal to `org_id` of the path. It never changes. + candidate_handle: + $ref: '#/CandidateHandle' + need: + description: Need the invitation was built from, or null for a direct invitation. + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/InvitationState' + expiry_reason: + description: Reason of an expiry, or null unless `state` is `expired`. + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + terms: + $ref: '#/InvitationTerms' + response_period_days: + $ref: '#/InvitationResponsePeriod' + response_deadline_at: + description: Moment when the candidate's time to answer ends, set at the first delivery to `delivered_at` plus `response_period_days`, or null for a draft. A command received at this moment or later is late. After an acceptance the deadline no longer applies. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + salary_raise_used: + type: boolean + description: Whether the one raise of the upper salary bound after sending (PRD FR13) has been used. It counts the whole history of the invitation. + salary_fit: + $ref: '#/InvitationSalaryFit' + contact_access: + $ref: '#/InvitationContactAccess' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' + delivered_at: + description: Moment of delivery to the candidate's inbox, or null for a draft. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + viewed_at: + description: Moment when the candidate first opened the terms, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + responded_at: + description: Moment of the candidate's acceptance or decline, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +OrganizationInvitationSummary: + type: object + description: 'Invitation in the organization''s list: its identity, state, versions, role, salary range, deadline, and contact access. Read the invitation for the full terms and the salary indicator.' + additionalProperties: false + required: + - id + - candidate_handle + - need + - state + - expiry_reason + - version + - terms_version + - role_title + - salary + - response_deadline_at + - contact_access + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + candidate_handle: + $ref: '#/CandidateHandle' + need: + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + role_title: + $ref: '#/InvitationRoleTitle' + salary: + $ref: '#/SalaryRange' + response_deadline_at: + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + contact_access: + $ref: '#/InvitationContactAccess' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +OrganizationInvitationList: + type: object + description: One page of the invitations of an organization, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Invitations of the page. + items: + $ref: '#/OrganizationInvitationSummary' + page: + $ref: '#/PageInfo' +OrganizationInvitationCreate: + type: object + description: New draft for one candidate. The candidate is named only by the handle from a search result of this organization, never by an email address, a phone number, or an account identifier. The terms are complete from the start, so a draft without the tax basis or the communication method cannot exist. Unknown fields are rejected, so a request cannot set the state, a version, a deadline, the salary indicator, contact access, or a candidate's minimum or contact. + additionalProperties: false + required: + - candidate_handle + - terms + properties: + candidate_handle: + $ref: '#/CandidateHandle' + need: + description: Need of the organization the invitation is built from, or null or absent for a direct invitation. + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + response_period_days: + description: Days to answer; absent means 7, the default of the product policy. + allOf: + - $ref: '#/InvitationResponsePeriod' + terms: + $ref: '#/InvitationTerms' +OrganizationInvitationUpdate: + type: object + description: 'Change of a draft over the version the client read. Each field present replaces that field as a whole and an absent field stays unchanged; `terms` is always replaced completely, never merged, and a change of the terms creates the next terms version. `need` sent as null unlinks the need. The candidate cannot change: a draft for another candidate is a new draft. Unknown fields are rejected.' + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/InvitationVersion' + need: + oneOf: + - $ref: '#/InvitationNeedReference' + - type: 'null' + response_period_days: + $ref: '#/InvitationResponsePeriod' + terms: + $ref: '#/InvitationTerms' +InvitationCommand: + type: object + description: 'Command without parameters over the invitation version the client read: send, withdraw, or cancel. Unknown fields are rejected.' + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/InvitationVersion' +InvitationSalaryRaise: + type: object + description: The one raise of the upper salary bound of a sent invitation (PRD FR13). Only `salary_to` changes; the lower bound, the currency, the period, and the tax basis stay fixed. Unknown fields are rejected, so the request cannot lower the lower bound or change the basis. + additionalProperties: false + required: + - expected_version + - salary_to + properties: + expected_version: + $ref: '#/InvitationVersion' + salary_to: + description: New upper bound, above the current one, with a width of the range from 10% to 40% of its midpoint. + allOf: + - $ref: '#/RubAmount' +CandidateInvitation: + type: object + description: 'Invitation as the addressed candidate reads it: the organization, the current terms with their version, the state and the deadline, the text and the choice of the consent C4 while an acceptance is possible, the candidate''s own decline, and the contact grant that the acceptance created. It has no candidate handle, no need, no salary indicator, and no contact value: the candidate''s own contacts and salary minimum stay in the profile.' + additionalProperties: false + required: + - id + - organization + - state + - expiry_reason + - version + - terms_version + - terms + - response_deadline_at + - delivered_at + - viewed_at + - responded_at + - updated_at + - contact_consent + - decline + - contact_grant + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization: + $ref: '#/InvitationOrganization' + state: + $ref: '#/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + terms: + $ref: '#/InvitationTerms' + response_deadline_at: + $ref: '#/Timestamp' + delivered_at: + $ref: '#/Timestamp' + viewed_at: + description: Moment of the first view recorded by ViewMyInvitation, or null when the candidate has not opened the terms. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + responded_at: + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + updated_at: + $ref: '#/Timestamp' + contact_consent: + description: 'Text and choice of the consent C4 for an acceptance, or null when an acceptance is impossible now: the state does not allow it, the deadline has passed, or the profile holds no contact to disclose. In the last case the client tells the candidate to add a contact to the profile first, because a grant must cover at least one field.' + oneOf: + - $ref: '#/ContactConsentOffer' + - type: 'null' + decline: + description: The candidate's decline, or null unless `state` is `declined`. + oneOf: + - $ref: '#/InvitationDeclineRecord' + - type: 'null' + contact_grant: + description: Contact grant that the acceptance of this invitation created, or null when the invitation was never accepted. It stays after a revocation, with its status and reason. + oneOf: + - $ref: '#/ContactGrant' + - type: 'null' +CandidateInvitationSummary: + type: object + description: 'Invitation in the candidate''s inbox: the organization, the state, the versions, the role, the salary range, and the deadline. Listing never records a view; GetMyInvitation returns the full terms, and ViewMyInvitation records the view.' + additionalProperties: false + required: + - id + - organization + - state + - expiry_reason + - version + - terms_version + - role_title + - salary + - work_formats + - response_deadline_at + - delivered_at + - viewed_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization: + $ref: '#/InvitationOrganization' + state: + $ref: '#/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/InvitationVersion' + terms_version: + $ref: '#/InvitationTermsVersion' + role_title: + $ref: '#/InvitationRoleTitle' + salary: + $ref: '#/SalaryRange' + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + response_deadline_at: + $ref: '#/Timestamp' + delivered_at: + $ref: '#/Timestamp' + viewed_at: + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + updated_at: + $ref: '#/Timestamp' +CandidateInvitationList: + type: object + description: One page of the candidate's invitations, newest first by delivery time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Invitations of the page. + items: + $ref: '#/CandidateInvitationSummary' + page: + $ref: '#/PageInfo' +InvitationAcceptance: + type: object + description: Acceptance of the current terms with the consent C4. The client sends the `version` and the `terms_version` it read and the contact fields the candidate selected; nothing is preselected or defaulted. Unknown fields are rejected, so a request cannot carry contact values, a grant, or another consent. + additionalProperties: false + required: + - expected_version + - terms_version + - consent_c4 + properties: + expected_version: + $ref: '#/InvitationVersion' + terms_version: + description: Terms version that the candidate read and accepts. A version that is not the current one answers 412 version_conflict. + allOf: + - $ref: '#/InvitationTermsVersion' + consent_c4: + $ref: '#/ContactConsentAcceptance' +InvitationDeclineRequest: + type: object + description: 'Structured decline: a reason and an optional comment. Unknown fields are rejected.' + additionalProperties: false + required: + - expected_version + - reason + properties: + expected_version: + $ref: '#/InvitationVersion' + reason: + $ref: '#/InvitationDeclineReason' + comment: + description: Optional comment for any reason, including `other`; absent or null means none. + oneOf: + - $ref: '#/InvitationDeclineComment' + - type: 'null' +AssessmentLabNodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address. +AssessmentLabNodeKind: + type: string + description: 'What the console of a node shows. + + + - mikrotik: a MikroTik router with the RouterOS console. + + - ubuntu: a small Ubuntu server with a Linux login. + + + Adding a value is a contract change.' + enum: + - mikrotik + - ubuntu +AssessmentLabNode: + type: object + description: A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/AssessmentLabNodeName' + kind: + $ref: '#/AssessmentLabNodeKind' +LabItemContent: + type: object + description: 'Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.' + additionalProperties: false + required: + - format + - nodes + - time_limit_seconds + properties: + format: + type: string + enum: + - lab + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the lab in the order of the statement. + items: + $ref: '#/AssessmentLabNode' + time_limit_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline. +LabAnswer: + type: object + description: 'Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.' + additionalProperties: false + required: + - format + - lab_id + properties: + format: + type: string + enum: + - lab + lab_id: + type: string + format: uuid + description: The lab of this item that the candidate worked in. +AssessmentLabState: + type: string + description: 'State of a lab of an attempt item. + + + - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. + + - ready: the consoles can be opened until `expires_at`. + + - checking: the answer was accepted; the consoles are closed and the server checks the nodes. + + - submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct. + + - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab. + + - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current. + + + Adding a value is a contract change.' + enum: + - provisioning + - ready + - checking + - submitted + - expired + - failed +AssessmentLabFailureReason: + type: string + description: 'Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a check that could not reach a node. It never depends on the candidate and is never a failed check.' + enum: + - lab_error +AssessmentLab: + type: object + description: Candidate view of the lab of one attempt item. It contains no node address, MAC address, port, password, key, token, seed, checker state, criteria, score, or infrastructure name. + additionalProperties: false + required: + - id + - item_id + - state + - nodes + - created_at + - ready_at + - expires_at + - finished_at + - failure_reason + properties: + id: + type: string + format: uuid + description: Identifier of the lab. + item_id: + $ref: '#/AssessmentItemId' + state: + $ref: '#/AssessmentLabState' + nodes: + type: array + minItems: 1 + maxItems: 8 + items: + $ref: '#/AssessmentLabNode' + created_at: + $ref: '#/Timestamp' + ready_at: + description: Time the lab became `ready`, or null before. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + expires_at: + description: 'Time the lab ends unless it was submitted before: the earlier of the lifetime of the item and the attempt deadline. It never moves.' + $ref: '#/Timestamp' + finished_at: + description: Time the lab reached `submitted`, `expired`, or `failed`, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + failure_reason: + description: '`lab_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/AssessmentLabFailureReason' + - type: 'null' +AssessmentLabCreate: + type: object + description: Start the lab of the current lab item. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + properties: + item_id: + $ref: '#/AssessmentItemId' +AssessmentLabConsoleSessionCreate: + type: object + description: Open a console of one node of a ready lab. Unknown fields are rejected. + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/AssessmentLabNodeName' +AssessmentLabConsoleSession: + type: object + description: A console session of one node. The client opens a WebSocket to `websocket_path` on the same origin before `expires_at`; the session cookie and the Origin check authorize the upgrade, so no secret travels in the path, the body, or a query string. A session can be attached once and ends with the lab. + additionalProperties: false + required: + - id + - node + - websocket_path + - expires_at + properties: + id: + type: string + format: uuid + description: Identifier of the console session; it is not a secret. + node: + $ref: '#/AssessmentLabNodeName' + websocket_path: + type: string + maxLength: 128 + pattern: ^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$ + description: Same-origin path of the console WebSocket. + expires_at: + description: Time by which the WebSocket must be opened. + $ref: '#/Timestamp' +AssessmentLabSubmission: + type: object + description: Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request cannot send a score or a correctness flag. + additionalProperties: false + required: + - expected_version + - answer + properties: + expected_version: + $ref: '#/AssessmentAttemptVersion' + answer: + $ref: '#/LabAnswer' +MatchConfirmationStatus: + type: string + description: Confirmation state for this specialization only. A result for one specialization never changes the state of another specialization. + enum: + - confirmed + - unconfirmed +MatchGradeFilter: + type: object + description: A confirmed category filter, never a candidate declaration. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' +MatchSearchStackTag: + type: string + description: A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence. + enum: + - go + - postgresql + - kafka + - docker +MatchSearchConditions: + type: object + description: Filters against safe, coarse card conditions. No candidate location, salary amount, salary minimum, or salary range is accepted. + additionalProperties: false + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + salary_compatibility: + $ref: '#/CandidateSalaryCompatibility' +MatchSearchFilters: + type: object + description: Optional filters over the current organization-visible bank. An empty object means no additional filter. Confirmed and declared grades are separate fields; a declaration never satisfies a confirmed-grade or category filter. Conditions use only the safe, coarse card fields. + additionalProperties: false + properties: + specialization: + $ref: '#/SpecializationCode' + confirmed_grade: + description: Match only candidates with this currently confirmed grade in the selected specialization. It never matches a declared grade. + $ref: '#/GradeCode' + confirmed_category: + $ref: '#/MatchGradeFilter' + confirmation_status: + $ref: '#/MatchConfirmationStatus' + declared_grade: + description: Candidate-declared grade filter. This is a separate claim and cannot satisfy `confirmed_grade` or `confirmed_category`. + $ref: '#/GradeCode' + stack: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + items: + $ref: '#/MatchSearchStackTag' + conditions: + $ref: '#/MatchSearchConditions' +MatchSearchByNeed: + type: object + description: Search one immutable set of confirmed requirements. `requirements_version` is the Need.requirements_version, not the general Need.version; text-only or suggestion-only edits do not change this search basis. + additionalProperties: false + required: + - need_id + - requirements_version + properties: + need_id: + type: string + format: uuid + description: Need owned by the organization in the path. + requirements_version: + $ref: '#/NeedVersion' + filters: + $ref: '#/MatchSearchFilters' +MatchSearchByBank: + type: object + description: Search the current organization-visible bank. An empty `filters` object includes all otherwise eligible specializations as separate entries. + additionalProperties: false + required: + - filters + properties: + filters: + $ref: '#/MatchSearchFilters' +MatchSearchRequest: + oneOf: + - $ref: '#/MatchSearchByNeed' + - $ref: '#/MatchSearchByBank' + description: Search either a Need.requirements_version snapshot or the whole organization-visible bank with explicit filters. Unknown fields are rejected by both closed request variants. +MatchSearchNeedSource: + type: object + description: The immutable need requirements snapshot used by this result. + additionalProperties: false + required: + - kind + - need_id + - requirements_version + properties: + kind: + type: string + enum: + - need + need_id: + type: string + format: uuid + requirements_version: + $ref: '#/NeedVersion' +MatchAppliedConditions: + type: object + description: Conditions echoed as a complete snapshot; null means no filter. + additionalProperties: false + required: + - work_formats + - salary_compatibility + properties: + work_formats: + oneOf: + - type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + - type: 'null' + salary_compatibility: + oneOf: + - $ref: '#/CandidateSalaryCompatibility' + - type: 'null' +MatchAppliedFilters: + type: object + description: A normalized response snapshot of the bank filters. Each key is present; null means the corresponding request filter was omitted. This keeps a search result tied to its exact filter basis. + additionalProperties: false + required: + - specialization + - confirmed_grade + - confirmed_category + - confirmation_status + - declared_grade + - stack + - conditions + properties: + specialization: + oneOf: + - $ref: '#/SpecializationCode' + - type: 'null' + confirmed_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + confirmed_category: + oneOf: + - $ref: '#/MatchGradeFilter' + - type: 'null' + confirmation_status: + oneOf: + - $ref: '#/MatchConfirmationStatus' + - type: 'null' + declared_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + stack: + oneOf: + - type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + items: + $ref: '#/MatchSearchStackTag' + - type: 'null' + conditions: + oneOf: + - $ref: '#/MatchAppliedConditions' + - type: 'null' +MatchSearchBankSource: + type: object + description: The normalized filters used for a bank search. + additionalProperties: false + required: + - kind + - filters + properties: + kind: + type: string + enum: + - bank + filters: + $ref: '#/MatchAppliedFilters' +MatchSearchSource: + oneOf: + - $ref: '#/MatchSearchNeedSource' + - $ref: '#/MatchSearchBankSource' + description: Search basis echoed with the response so the displayed result remains tied to its need requirements version or bank filters. +MatchStrength: + type: string + description: Coarse strength of a confirmed assessment for this specialization. + enum: + - standard + - strong +MatchCategory: + type: object + description: A confirmed category. Its specialization must equal the enclosing match entry's specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation. + additionalProperties: false + required: + - specialization + - grade + - basis + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' + basis: + $ref: '#/EvidenceBasis' +MatchScore: + type: number + format: double + minimum: 0 + maximum: 1 + description: A normalized FR09 ranking component from 0 to 1. +MatchNullableScore: + description: A score from a versioned ranking component, or null when it is not available. Any null component has a matching bounded entry in `unknown_flags`. + oneOf: + - type: number + format: double + minimum: 0 + maximum: 1 + - type: 'null' +MatchUnknownComponent: + type: string + description: Ranking or public-card component whose value is unknown. + enum: + - semantics + - percentile + - assessment + - freshness + - responsiveness + - experience_band + - work_formats + - salary_compatibility + - domain +MatchUnknownReason: + type: string + description: Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5. + enum: + - ml_unavailable + - cohort_below_30 + - no_confirmation_for_specialization + - not_in_public_card + - need_field_unconfirmed + - no_freshness_history + - no_response_history + - percentile_not_computed +MatchUnknownFlag: + type: object + description: A safe, bounded explanation for one unavailable component. + additionalProperties: false + required: + - component + - reason + properties: + component: + $ref: '#/MatchUnknownComponent' + reason: + $ref: '#/MatchUnknownReason' +MatchUnknownFlags: + type: array + maxItems: 9 + items: + $ref: '#/MatchUnknownFlag' +MatchEvidenceCode: + type: string + description: Template code for an explanation derived from allowed evidence. It carries no free text, raw answer, or reason for withheld FSP data. + enum: + - confirmed_category + - required_skill_evidence + - desired_skill_evidence + - domain_alignment + - task_alignment + - work_conditions_match + - salary_compatibility + - declared_grade +MatchEvidenceState: + type: string + enum: + - supports + - partial + - gap + - declared_only +MatchEvidenceSummaryItem: + type: object + description: A templated, non-text evidence explanation. + additionalProperties: false + required: + - code + - state + properties: + code: + $ref: '#/MatchEvidenceCode' + state: + $ref: '#/MatchEvidenceState' +MatchEvidenceSummary: + type: array + maxItems: 12 + items: + $ref: '#/MatchEvidenceSummaryItem' +MatchRequirementKind: + type: string + description: Kind of the need requirement that an explanation item answers. + enum: + - required_skill + - desired_skill + - task +MatchSemanticItemKind: + type: string + description: 'Kind of the published card item that matched a requirement. + + + - project: one published project; `project_title` names it. + + - stack: the recognized technology codes of the card. + + - roles: the specializations and grades that the card shows.' + enum: + - project + - stack + - roles +MatchSimilarityBand: + type: string + description: Coarse band of the cosine similarity between the requirement and the matched item under the versioned policy thresholds. `high` and `medium` are the only values; a weaker similarity produces no item. The band is a computed similarity of two texts, not a judgement of the candidate. + enum: + - high + - medium +MatchSemanticEvidence: + type: object + description: 'Why the entry is in the result: one confirmed requirement of the need and the published card item with the highest semantic similarity to it. The server computes it from stored vectors and the versioned thresholds; no model writes text into it. `requirement_text` is the confirmed text of the organization''s own need. `project_title` is the title the candidate published with the `projects` card field and is null for other kinds. No repository address, owner, or fetched repository text is ever part of it.' + additionalProperties: false + required: + - requirement_kind + - requirement_text + - item_kind + - project_title + - repository_verified + - similarity + properties: + requirement_kind: + $ref: '#/MatchRequirementKind' + requirement_text: + type: string + minLength: 1 + maxLength: 300 + description: Confirmed skill name or task text of the need. Plain text; show it as text, never as HTML. + item_kind: + $ref: '#/MatchSemanticItemKind' + project_title: + description: Published project title for `project`, otherwise null. Plain text; show it as text, never as HTML. + oneOf: + - type: string + minLength: 1 + maxLength: 100 + - type: 'null' + repository_verified: + type: boolean + description: True only for a project whose linked repository the latest server check found public on GitHub ("backed by a public repository"). It does not prove authorship. + similarity: + $ref: '#/MatchSimilarityBand' +MatchSemanticEvidenceList: + type: array + description: 'Semantic explanation items in a stable order: `high` before `medium`, then by similarity, then by the order of the requirements in the need. At most the versioned per-entry limit is returned. It is empty for a bank search, while vectors are not ready, when ML is unavailable, and when no requirement reaches a band; `unknown_flags` names `ml_unavailable` when the semantic component itself is unknown.' + maxItems: 12 + items: + $ref: '#/MatchSemanticEvidence' +MatchPublicStack: + type: array + maxItems: 4 + uniqueItems: true + items: + $ref: '#/MatchSearchStackTag' +MatchPublicContext: + type: object + description: Safe anonymous-card context only. A null value means that the value is not in the public card or is not present; the response does not reveal which. It contains no contact, candidate location, or salary amount. + additionalProperties: false + required: + - stack + - experience_band + - work_formats + - salary_compatibility + properties: + stack: + oneOf: + - $ref: '#/MatchPublicStack' + - type: 'null' + experience_band: + oneOf: + - $ref: '#/CandidateExperienceBand' + - type: 'null' + work_formats: + oneOf: + - type: array + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + - type: 'null' + salary_compatibility: + oneOf: + - $ref: '#/CandidateSalaryCompatibility' + - type: 'null' +MatchConfirmedComponents: + type: object + description: Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`. + additionalProperties: false + required: + - fit + - coverage + - domain + - semantics + - percentile + - competition + - freshness + - responsiveness + - rank_score + properties: + fit: + $ref: '#/MatchScore' + coverage: + $ref: '#/MatchScore' + domain: + $ref: '#/MatchScore' + semantics: + $ref: '#/MatchScore' + percentile: + $ref: '#/MatchNullableScore' + competition: + $ref: '#/MatchScore' + freshness: + $ref: '#/MatchScore' + responsiveness: + $ref: '#/MatchScore' + rank_score: + $ref: '#/MatchScore' +MatchUnconfirmedComponents: + type: object + description: Unconfirmed entries are ordered only by Fit and coverage. This strict component object has no theta, T, P, test percentile, or confirmed assessment score. + additionalProperties: false + required: + - fit + - coverage + properties: + fit: + type: number + format: double + minimum: 0 + maximum: 1 + description: Job fit for this specialization, never an assessment score. + coverage: + type: number + format: double + minimum: 0 + maximum: 1 + description: Coverage of confirmed need skills by allowed public evidence. +MatchConfirmedCandidate: + type: object + description: One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization. + additionalProperties: false + required: + - candidate_handle + - specialization + - confirmation_status + - declared_grade + - category + - strength + - public_context + - evidence_summary + - semantic_evidence + - components + - unknown_flags + properties: + candidate_handle: + $ref: '#/CandidateHandle' + specialization: + $ref: '#/SpecializationCode' + confirmation_status: + type: string + enum: + - confirmed + declared_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + description: Candidate-declared grade for this specialization, never a confirmation. + category: + $ref: '#/MatchCategory' + strength: + $ref: '#/MatchStrength' + public_context: + $ref: '#/MatchPublicContext' + evidence_summary: + $ref: '#/MatchEvidenceSummary' + semantic_evidence: + $ref: '#/MatchSemanticEvidenceList' + components: + $ref: '#/MatchConfirmedComponents' + unknown_flags: + $ref: '#/MatchUnknownFlags' +MatchUnconfirmedCandidate: + type: object + description: One specialization with no confirmed category. `category` and `strength` remain present and null. A confirmation in another specialization never changes this entry. The schema intentionally has no assessment measurement fields. + additionalProperties: false + required: + - candidate_handle + - specialization + - confirmation_status + - declared_grade + - category + - strength + - public_context + - evidence_summary + - semantic_evidence + - components + - unknown_flags + properties: + candidate_handle: + $ref: '#/CandidateHandle' + specialization: + $ref: '#/SpecializationCode' + confirmation_status: + type: string + enum: + - unconfirmed + declared_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + description: Candidate-declared grade, separate from assessment confirmation. + category: + type: 'null' + description: There is no confirmed category for this specialization. + strength: + type: 'null' + description: Assessment strength is not measured for this specialization. + public_context: + $ref: '#/MatchPublicContext' + evidence_summary: + $ref: '#/MatchEvidenceSummary' + semantic_evidence: + $ref: '#/MatchSemanticEvidenceList' + components: + $ref: '#/MatchUnconfirmedComponents' + unknown_flags: + $ref: '#/MatchUnknownFlags' +MatchSearchGroups: + type: object + description: Separate ranking groups. Confirmed categories appear in main and near; unconfirmed specializations appear only in the lower unconfirmed group. + additionalProperties: false + required: + - main + - near + - unconfirmed + properties: + main: + type: array + items: + $ref: '#/MatchConfirmedCandidate' + near: + type: array + items: + $ref: '#/MatchConfirmedCandidate' + unconfirmed: + type: array + items: + $ref: '#/MatchUnconfirmedCandidate' +MatchSearchResponse: + type: object + description: Anonymous search result grouped by specialization state. Repeated organization-scoped handles are allowed when the same candidate has different specialization entries; entries never transfer confirmation between specializations. + additionalProperties: false + required: + - source + - groups + - truncated + properties: + source: + $ref: '#/MatchSearchSource' + groups: + $ref: '#/MatchSearchGroups' + truncated: + type: boolean + description: 'True when the groups are not the whole ranked result: a group exceeded the versioned per-group limit, or the organization''s card-view allowance ended while the entries were being revealed. The entries returned are in rank order and already counted as card views. It carries no total, so it does not reveal how many candidates match.' +NeedVersion: + type: integer + format: int64 + minimum: 1 + description: Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version. + examples: + - 2 +NeedTitle: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +NeedSourceText: + type: string + minLength: 1 + maxLength: 10000 + description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.' +NeedValueStatus: + type: string + description: 'Confirmation state of one need field. + + + - confirmed: a member of the organization entered the value or confirmed it. Only confirmed values feed readiness, category recommendations, search, and invitations. + + - extracted: the server proposed the value from the need text or an import, and nobody has confirmed it yet. It is a suggestion: it never feeds search or recommendations and never counts as an answer in readiness. + + - unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a Senior grade, the remote format, or a zero salary.' + enum: + - confirmed + - extracted + - unknown +NeedItemStatus: + type: string + description: 'Confirmation state of a list item, and the decision that a request sends for a field or an item: `confirmed` or `extracted`, with the meaning of NeedValueStatus. A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value. An item is never `unknown`; a list with no confirmed item is what readiness reports as missing.' + enum: + - confirmed + - extracted +NeedValueOrigin: + type: string + description: 'Where the value of a field or item came from. The server sets it; a request never sends it. + + + - manual: a member of the organization typed the value in the form. `quote`, `extraction_version`, and `extracted_in_version` are null. + + - extracted_from_text: the server extracted the value from `source_text`, with the deterministic rules and dictionary or, planned, with the ML service. `extraction_version` names the extractor version. + + - imported: planned; the value was copied from a linked vacancy or an import. No MVP operation produces it. + + + Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change.' + enum: + - manual + - extracted_from_text + - imported +NeedSourceQuote: + type: string + minLength: 1 + maxLength: 300 + description: Exact excerpt of the `source_text` that the value was extracted from, so a reviewer can check it. It may contain line breaks. Plain text; clients show it as text, never as HTML. +NeedVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it. +NeedValueSource: + type: object + description: 'Provenance of a value: its origin, the quote it was extracted from, the need version whose text the quote belongs to, and the extractor version. Read-only; the server derives it and a request cannot set it.' + additionalProperties: false + required: + - origin + - quote + - extracted_in_version + - extraction_version + properties: + origin: + $ref: '#/NeedValueOrigin' + quote: + description: Excerpt of the need text that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt. + oneOf: + - $ref: '#/NeedSourceQuote' + - type: 'null' + extracted_in_version: + description: Need version whose `source_text` the value was extracted from and the quote is an excerpt of, or null for a manual value. A confirmed value keeps it after the text changes, so its quote may be absent from the current `source_text`. + oneOf: + - $ref: '#/NeedVersion' + - type: 'null' + extraction_version: + description: Extractor version for an extracted or imported value, or null for a manual value. + oneOf: + - $ref: '#/NeedVersionLabel' + - type: 'null' +SkillName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML. +SkillTaxonomyCode: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9][a-z0-9_.+#-]*$ + description: Code of a skill in the platform skill taxonomy, for example `postgresql`. The server assigns it from the taxonomy; clients never send it and never derive it from the name. +NeedTaskText: + type: string + minLength: 1 + maxLength: 300 + pattern: ^\S(?:.*\S)?$ + description: One work task of the team, for example "Move the payout service to an event model". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +NeedDomainName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Business domain of the work, for example payments or logistics, as free text. Plain text without line breaks; clients show it as text, never as HTML. +NeedLocationName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Place of work for the office or hybrid format, for example a city, as free text. It describes the employer's office, never a candidate's address. Plain text without line breaks; clients show it as text, never as HTML. +RubAmount: + type: integer + format: int64 + minimum: 1000 + maximum: 100000000 + multipleOf: 1000 + description: Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final. + examples: + - 120000 +CurrencyCode: + type: string + description: ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change. + enum: + - RUB +SalaryPeriod: + type: string + description: Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change. + enum: + - month +SalaryTaxBasis: + type: string + description: 'Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.' + enum: + - net + - gross +SalaryRange: + type: object + description: 'Salary range `[A; B]` in whole rubles with its base: the currency, the pay period, and the tax basis (PRD FR13). The schema requires every field, bounds that are positive multiples of 1000, and the known currency, period, and basis. The server checks the cross-field rules in integer arithmetic: `salary_from < salary_to`, and a width `(B - A) / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B`. A violation answers 400 validation_failed with the pointer of `salary_to` in the request, for example `/salary/value/salary_to`. For example, `[95000; 105000]` has a width of exactly 10% and `[80000; 120000]` exactly 40%; both are accepted. The rules are the same for a need and an invitation.' + additionalProperties: false + required: + - salary_from + - salary_to + - currency + - period + - tax_basis + properties: + salary_from: + $ref: '#/RubAmount' + salary_to: + $ref: '#/RubAmount' + currency: + $ref: '#/CurrencyCode' + period: + $ref: '#/SalaryPeriod' + tax_basis: + $ref: '#/SalaryTaxBasis' +NeedSpecialization: + type: object + description: Target specialization of the need with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/NeedValueStatus' + value: + oneOf: + - $ref: '#/SpecializationCode' + - type: 'null' + source: + oneOf: + - $ref: '#/NeedValueSource' + - type: 'null' +NeedGrade: + type: object + description: Target grade of the need with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; a text that names no grade leaves the grade unknown instead of assuming one. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/NeedValueStatus' + value: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' + source: + oneOf: + - $ref: '#/NeedValueSource' + - type: 'null' +NeedDomain: + type: object + description: Business domain of the need with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/NeedValueStatus' + value: + oneOf: + - $ref: '#/NeedDomainName' + - type: 'null' + source: + oneOf: + - $ref: '#/NeedValueSource' + - type: 'null' +NeedWorkFormats: + type: object + description: Work formats that the employer offers, with their confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; a known value lists one to three formats. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/NeedValueStatus' + value: + type: + - array + - 'null' + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + source: + oneOf: + - $ref: '#/NeedValueSource' + - type: 'null' +NeedLocation: + type: object + description: Place of work with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. Readiness requires a confirmed place only when the confirmed work formats include `office` or `hybrid`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/NeedValueStatus' + value: + oneOf: + - $ref: '#/NeedLocationName' + - type: 'null' + source: + oneOf: + - $ref: '#/NeedValueSource' + - type: 'null' +NeedSalary: + type: object + description: Salary range that the employer offers, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. A text without a salary leaves it unknown; the server never substitutes zero, a market estimate, or a range from another need. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/NeedValueStatus' + value: + oneOf: + - $ref: '#/SalaryRange' + - type: 'null' + source: + oneOf: + - $ref: '#/NeedValueSource' + - type: 'null' +NeedSkill: + type: object + description: 'One required or desired skill of the need. `taxonomy_code` is null for a skill that the platform taxonomy does not know: the server keeps the name as given, never maps it to a guessed code, and counts it as not covered in category recommendations.' + additionalProperties: false + required: + - name + - taxonomy_code + - status + - source + properties: + name: + $ref: '#/SkillName' + taxonomy_code: + oneOf: + - $ref: '#/SkillTaxonomyCode' + - type: 'null' + status: + $ref: '#/NeedItemStatus' + source: + $ref: '#/NeedValueSource' +NeedTask: + type: object + description: One work task of the team with its confirmation state and provenance. + additionalProperties: false + required: + - text + - status + - source + properties: + text: + $ref: '#/NeedTaskText' + status: + $ref: '#/NeedItemStatus' + source: + $ref: '#/NeedValueSource' +NeedSpecializationInput: + type: object + description: Decision about the specialization in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/SpecializationCode' + status: + $ref: '#/NeedItemStatus' +NeedGradeInput: + type: object + description: Decision about the grade in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/GradeCode' + status: + $ref: '#/NeedItemStatus' +NeedDomainInput: + type: object + description: Decision about the domain in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/NeedDomainName' + status: + $ref: '#/NeedItemStatus' +NeedWorkFormatsInput: + type: object + description: Decision about the work formats in a request; see NeedUpdate for the rules of `status`. Formats are compared as a set. + additionalProperties: false + required: + - value + - status + properties: + value: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/WorkFormat' + status: + $ref: '#/NeedItemStatus' +NeedLocationInput: + type: object + description: Decision about the place of work in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/NeedLocationName' + status: + $ref: '#/NeedItemStatus' +NeedSalaryInput: + type: object + description: Decision about the salary range in a request; see NeedUpdate for the rules of `status` and SalaryRange for the rules of the range, whose pointers are under `/salary/value`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/SalaryRange' + status: + $ref: '#/NeedItemStatus' +NeedSkillInput: + type: object + description: 'One skill of a list in a request. A name that equals, without regard to letter case, a skill of the current version in either skill list refers to that skill and keeps its origin, quote, and taxonomy code; this is how an extracted skill is confirmed or moved between the required and desired lists. Any other name is a new manual skill. `status` follows the rules of NeedUpdate: `extracted` for a name that is not a stored suggestion answers 400 validation_failed with the pointer of that `status`, for example `/required_skills/2/status`. A name repeated within or across the two skill lists answers 400 with the pointer of the later `name`.' + additionalProperties: false + required: + - name + - status + properties: + name: + $ref: '#/SkillName' + status: + $ref: '#/NeedItemStatus' +NeedTaskInput: + type: object + description: One task of the list in a request. A text equal to a task of the current version refers to that task and keeps its origin and quote; any other text is a new manual task. `status` and repeated texts follow the rules of NeedSkillInput. + additionalProperties: false + required: + - text + - status + properties: + text: + $ref: '#/NeedTaskText' + status: + $ref: '#/NeedItemStatus' +NeedRequirementSet: + type: object + description: Requirements of one need version, each with its confirmation state and provenance. Read-only; requests change them through the fields of NeedCreate and NeedUpdate. + additionalProperties: false + required: + - specialization + - grade + - required_skills + - desired_skills + - tasks + - domain + - work_formats + - location + - salary + properties: + specialization: + $ref: '#/NeedSpecialization' + grade: + $ref: '#/NeedGrade' + required_skills: + type: array + maxItems: 30 + description: Required skills; each has weight 2 in skill coverage. Only confirmed skills count. + items: + $ref: '#/NeedSkill' + desired_skills: + type: array + maxItems: 30 + description: Desired skills; each has weight 1 in skill coverage. Only confirmed skills count. + items: + $ref: '#/NeedSkill' + tasks: + type: array + maxItems: 20 + description: Work tasks of the team in the order given. + items: + $ref: '#/NeedTask' + domain: + $ref: '#/NeedDomain' + work_formats: + $ref: '#/NeedWorkFormats' + location: + $ref: '#/NeedLocation' + salary: + $ref: '#/NeedSalary' +NeedFieldName: + type: string + description: Name of a need field, equal to its property name in NeedRequirementSet and in the request bodies. Adding a value is a contract change. + enum: + - specialization + - grade + - required_skills + - desired_skills + - tasks + - domain + - work_formats + - location + - salary +NeedMissingReason: + type: string + description: 'Why a critical field is missing: `unknown`, the field has no value, or `unconfirmed`, it has only an extracted value or, for required skills, only extracted items that wait for confirmation.' + enum: + - unknown + - unconfirmed +NeedMissingField: + type: object + description: One critical field that has no confirmed value, with a specific question that the client shows next to the field. + additionalProperties: false + required: + - field + - reason + - question + properties: + field: + $ref: '#/NeedFieldName' + reason: + $ref: '#/NeedMissingReason' + question: + type: string + minLength: 1 + maxLength: 300 + description: Specific Russian question about the missing value, for example which grade is needed. Plain text; the client shows it as text, never as HTML. +NeedReadinessStatus: + type: string + description: '`complete` when every critical field has a confirmed value, otherwise `incomplete`.' + enum: + - complete + - incomplete +NeedReadinessReport: + type: object + description: Completeness of the critical fields, computed by the server for the current version. The critical fields are `specialization`, `grade`, `required_skills` (at least one confirmed skill), `work_formats`, `salary`, and `location` when the confirmed work formats include `office` or `hybrid`. An incomplete need is still a valid saved need; each later operation, such as search or an invitation, states which readiness it requires. + additionalProperties: false + required: + - status + - missing_fields + properties: + status: + $ref: '#/NeedReadinessStatus' + missing_fields: + type: array + maxItems: 9 + description: Critical fields without a confirmed value, each at most once, in the order of NeedFieldName. Empty exactly when `status` is `complete`. + items: + $ref: '#/NeedMissingField' +NeedRecommendationStatus: + type: string + description: 'State of the category recommendations of the current requirements version. + + + - computed: `categories` holds the recommendations computed from the confirmed requirements of `requirements_version`. + + - pending: the computation for the current requirements version has not finished yet; `categories` is empty. Read the need again later. + + - not_available: the current requirements have no confirmed required or desired skill to compute from; `categories` is empty.' + enum: + - computed + - pending + - not_available +NeedSkillOverlap: + type: object + description: 'Skill coverage of a category: the weighted share of the confirmed skills of the need that the category taxonomy covers, with weight 2 for a required and 1 for a desired skill.' + additionalProperties: false + required: + - share + - covered_skills + - uncovered_skills + properties: + share: + type: number + format: double + minimum: 0 + maximum: 1 + description: Weighted share from 0 to 1, rounded to two decimals. + covered_skills: + type: array + maxItems: 60 + description: Confirmed skills of the need that the category covers. + items: + $ref: '#/SkillName' + uncovered_skills: + type: array + maxItems: 60 + description: Confirmed skills of the need that the category does not cover, including skills without a taxonomy code. + items: + $ref: '#/SkillName' +NeedMoneyStatus: + type: string + description: 'How the salary component of a recommendation was obtained. + + + - computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given. + + - insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null. + + - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null. + + - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null. + + + An unknown candidate minimum never counts as zero.' + enum: + - computed + - insufficient_data + - no_salary + - withheld +NeedMoneyFit: + type: object + description: Salary component of a recommendation. It is an aggregate over at least five candidates and never reveals a minimum of any candidate. + additionalProperties: false + required: + - status + - share + properties: + status: + $ref: '#/NeedMoneyStatus' + share: + type: + - number + - 'null' + format: double + minimum: 0 + maximum: 1 + description: 'Share of those candidates whose minimum is not above the upper bound of the range, rounded down to a multiple of 0.25 (one of 0, 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The score and the ranking use this rounded value, never the exact share. A quarter step gives five levels: each probe of a new upper bound tells at most which quarter of the group accepts it, and in the smallest allowed group of five candidates a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept.' +NeedSupplyBand: + type: string + description: 'Number of available candidates of the category in the allowed detail: `fewer_than_5`, `from_5_to_29`, or `30_or_more`. Smaller groups are never counted exactly.' + enum: + - fewer_than_5 + - from_5_to_29 + - 30_or_more +NeedCategoryRecommendation: + type: object + description: 'One recommended category, a specialization with a grade, with its score and the reasons for it. The score is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` (PRD FR08) computed from the published components: the exact skill overlap, the money share rounded down to a quarter or the neutral 0.5, and `Supply = min(1, active / 30)` when at least five candidates are available. For a group of fewer than five, Supply enters the ranking as 0, the same for every such group, so neither the score nor the order reveals the exact size of a group below five.' + additionalProperties: false + required: + - specialization + - grade + - score + - skill_overlap + - money + - supply + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' + score: + type: + - number + - 'null' + format: double + minimum: 0 + maximum: 1 + description: Recommendation score from 0 to 1, rounded half up to two decimals, or null when `supply` is `fewer_than_5`. Read-only; no request can set it. + skill_overlap: + $ref: '#/NeedSkillOverlap' + money: + $ref: '#/NeedMoneyFit' + supply: + $ref: '#/NeedSupplyBand' +NeedCategoryRecommendations: + type: object + description: 'Category recommendations computed by the server from the confirmed requirements of `requirements_version` with a versioned policy (PRD FR08). Read-only: no request can set a recommendation, a score, or one of its components. The server may recompute them for the same requirements version, for example for a new policy or a changed pool of available candidates, without a new need version; `computed_at` and `policy_version` then change. The policy version and the candidate group used are stored with each computation, so a later policy never rewrites it.' + additionalProperties: false + required: + - status + - requirements_version + - policy_version + - algorithm_version + - computed_at + - categories + properties: + status: + $ref: '#/NeedRecommendationStatus' + requirements_version: + $ref: '#/NeedVersion' + policy_version: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: Number of the policy version whose weights were applied, or null unless `status` is `computed`. + algorithm_version: + description: Version of the recommendation algorithm, or null unless `status` is `computed`. + oneOf: + - $ref: '#/NeedVersionLabel' + - type: 'null' + computed_at: + description: Time of the computation, or null unless `status` is `computed`. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + categories: + type: array + maxItems: 10 + description: Recommended categories, best first by the score described in NeedCategoryRecommendation. Empty unless `status` is `computed`. + items: + $ref: '#/NeedCategoryRecommendation' +Need: + type: object + description: 'Hiring need of an organization: what the team needs, independent of any published vacancy. It holds the current version of the requirements with their provenance, the readiness of the critical fields, and the category recommendations. It never contains membership data, a candidate''s personal data, or a candidate''s salary minimum.' + additionalProperties: false + required: + - id + - organization_id + - vacancy_id + - title + - source_text + - version + - requirements_version + - requirements + - readiness + - recommendations + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the need. + organization_id: + type: string + format: uuid + description: Organization that owns the need, equal to `org_id` of the path. It never changes. + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Linked vacancy of the same organization, or null. A need never requires a vacancy. + title: + $ref: '#/NeedTitle' + source_text: + description: Text the requirements were extracted from, or null. + oneOf: + - $ref: '#/NeedSourceText' + - type: 'null' + version: + $ref: '#/NeedVersion' + requirements_version: + description: Need version in which the current confirmed requirements were last changed, at most `version`. A change that confirms, changes, or removes a requirement makes it equal to the new `version`. A change of the title, the vacancy link, or the text, or of suggestions only, creates a new `version` but keeps `requirements_version`, so it invalidates neither the recommendations nor search results and selection snapshots. Search runs and selection snapshots (PRD FR10) refer to `(need id, requirements_version)`, and a new selection snapshot is due only when it changes. + allOf: + - $ref: '#/NeedVersion' + requirements: + $ref: '#/NeedRequirementSet' + readiness: + $ref: '#/NeedReadinessReport' + recommendations: + $ref: '#/NeedCategoryRecommendations' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +NeedSummary: + type: object + description: 'Need in a list: its identity, current version, target category fields, and readiness. Read the need for the requirements and the recommendations.' + additionalProperties: false + required: + - id + - vacancy_id + - title + - version + - specialization + - grade + - readiness + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the need. + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Linked vacancy, or null. + title: + $ref: '#/NeedTitle' + version: + $ref: '#/NeedVersion' + specialization: + $ref: '#/NeedSpecialization' + grade: + $ref: '#/NeedGrade' + readiness: + $ref: '#/NeedReadinessReport' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +NeedList: + type: object + description: One page of the needs of an organization, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Needs of the page. + items: + $ref: '#/NeedSummary' + page: + $ref: '#/PageInfo' +NeedCreate: + type: object + description: New need. Only `title` is required, so a need can start from a title, from a text, or from form fields, and with or without a vacancy. A field or list item given here must have `status` `confirmed` and becomes a confirmed manual value; `extracted` answers 400 with the pointer of that `status`, such as `/grade/status`, because a new need has no stored suggestion. A field that is absent is extracted from `source_text` when the text is given and is left unknown or empty otherwise. A nullable field sent as null, and a skill or task list sent as an empty list, stays unknown or empty and is not extracted; an empty `work_formats` value fails `minItems`. Unknown fields are rejected, so a request cannot set membership, a role, a status of the need, a provenance, readiness, a recommendation or its score, or a candidate's salary minimum. + additionalProperties: false + required: + - title + properties: + title: + $ref: '#/NeedTitle' + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Vacancy of the same organization to link, or null or absent for a need without a vacancy. + source_text: + oneOf: + - $ref: '#/NeedSourceText' + - type: 'null' + specialization: + oneOf: + - $ref: '#/NeedSpecializationInput' + - type: 'null' + grade: + oneOf: + - $ref: '#/NeedGradeInput' + - type: 'null' + required_skills: + type: array + maxItems: 30 + items: + $ref: '#/NeedSkillInput' + desired_skills: + type: array + maxItems: 30 + items: + $ref: '#/NeedSkillInput' + tasks: + type: array + maxItems: 20 + items: + $ref: '#/NeedTaskInput' + domain: + oneOf: + - $ref: '#/NeedDomainInput' + - type: 'null' + work_formats: + oneOf: + - $ref: '#/NeedWorkFormatsInput' + - type: 'null' + location: + oneOf: + - $ref: '#/NeedLocationInput' + - type: 'null' + salary: + oneOf: + - $ref: '#/NeedSalaryInput' + - type: 'null' +NeedUpdate: + type: object + description: 'Change of a need over the version the client read. Each field present in the body replaces that field as a whole; an absent field stays unchanged. Nested objects and lists are not merged: a field decision and each list are replaced entirely, and a stored item missing from a sent list is deleted. A nullable field sent as null becomes unknown, or unlinked for `vacancy_id`; a skill or task list sent empty deletes every item; a list sent as null fails validation. A field decision `{value, status}` and a list item follow the same rules: `confirmed` with the stored value confirms it and keeps its origin and quote, and `confirmed` with another value sets a confirmed manual value; `extracted` keeps a stored suggestion unconfirmed and is allowed only with exactly the stored suggested value, otherwise it answers 400 with the pointer of that `status`, such as `/grade/status` or `/required_skills/0/status`. A client that sends back an unchanged form therefore confirms nothing by accident: + it sends each suggestion with `extracted`, or leaves the field out. Sending a different `source_text` extracts again: new suggestions replace only the `extracted` values and items of fields not named in this body; confirmed values are never overwritten, a suggested skill whose name is already in either skill list is skipped, and a suggestion that a member deleted is not proposed again for this need. Unknown fields are rejected, so a request cannot set membership, a role, a provenance, readiness, a recommendation or its score, or a candidate''s salary minimum.' + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/NeedVersion' + title: + $ref: '#/NeedTitle' + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Vacancy of the same organization to link, or null to unlink. + source_text: + oneOf: + - $ref: '#/NeedSourceText' + - type: 'null' + specialization: + oneOf: + - $ref: '#/NeedSpecializationInput' + - type: 'null' + grade: + oneOf: + - $ref: '#/NeedGradeInput' + - type: 'null' + required_skills: + type: array + maxItems: 30 + items: + $ref: '#/NeedSkillInput' + desired_skills: + type: array + maxItems: 30 + items: + $ref: '#/NeedSkillInput' + tasks: + type: array + maxItems: 20 + items: + $ref: '#/NeedTaskInput' + domain: + oneOf: + - $ref: '#/NeedDomainInput' + - type: 'null' + work_formats: + oneOf: + - $ref: '#/NeedWorkFormatsInput' + - type: 'null' + location: + oneOf: + - $ref: '#/NeedLocationInput' + - type: 'null' + salary: + oneOf: + - $ref: '#/NeedSalaryInput' + - type: 'null' +NotificationKind: + type: string + description: 'Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. + + + - invitation_delivered: an invitation reached the candidate''s inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit. + + - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. + + + Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content.' + enum: + - invitation_delivered + - synthetic +NotificationContent: + type: object + description: The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment. + additionalProperties: false + required: + - title + - summary + - link_path + properties: + title: + type: string + minLength: 1 + maxLength: 120 + description: Short heading in Russian. + summary: + type: string + minLength: 1 + maxLength: 500 + description: One or two sentences in Russian. Plain text, never markup. + link_path: + type: + - string + - 'null' + maxLength: 256 + pattern: ^/[A-Za-z0-9/_-]{0,255}$ + description: Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router. + examples: + - /candidate/invitations +Notification: + type: object + description: One item of the inbox of the current account. Its identity, kind, organization, delivery time, and read state are stored; its content is resolved from the current source on every read. + additionalProperties: false + required: + - id + - kind + - organization_id + - delivered_at + - read_at + - content + properties: + id: + type: string + format: uuid + description: Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item. + kind: + $ref: '#/NotificationKind' + organization_id: + type: string + format: uuid + description: 'The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.' + delivered_at: + $ref: '#/Timestamp' + read_at: + description: When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + content: + description: The current content, or null when the source is gone or the recipient may not see it now. A client then shows a generic line such as "The content is no longer available" and never an old copy. The item stays in the list and can be marked read. + oneOf: + - $ref: '#/NotificationContent' + - type: 'null' +NotificationList: + type: object + description: One page of the inbox, newest delivery first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Items of the page. + items: + $ref: '#/Notification' + page: + $ref: '#/PageInfo' +NotificationReadReceipt: + type: object + description: The read state of one item after a mark. It carries no content, so marking never reads the source. + additionalProperties: false + required: + - id + - read_at + properties: + id: + type: string + format: uuid + description: Identifier of the marked item. + read_at: + $ref: '#/Timestamp' +OrganizationVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of the profile of an organization. Creation makes version 1, and every committed change of the profile advances it by exactly one. A change carries the version the client read as `expected_version`. Only the profile has a version: the memberships and the verification level of the organization do not advance it.' + examples: + - 2 +OrganizationName: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:[^\n\r]*\S)?$ + description: Public name of the organization, for example the legal name that a candidate knows. It has no leading or trailing whitespace and no line breaks, and it is at most 200 characters because consent records keep a copy of it. Plain text; clients show it as text, never as HTML. A later rename never changes the copy that a consent record holds. + examples: + - ООО Пример Платежи +OrganizationDescription: + type: string + minLength: 1 + maxLength: 2000 + description: What the organization does, written for candidates. It may contain line breaks; the server stores CRLF as LF, and it refuses leading and trailing whitespace and any other control character. Plain text; clients show it as text, never as HTML. + examples: + - Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. +OrganizationSphere: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Field of business of the organization as free text, for example "Платежи и финансовые сервисы". It has no leading or trailing whitespace and no line breaks. The product has no sphere taxonomy yet; a taxonomy code would be an additive field. Plain text; clients show it as text, never as HTML. + examples: + - Платежи и финансовые сервисы +OrganizationWebsite: + type: string + minLength: 9 + maxLength: 300 + pattern: ^https://[^\s/?#@]+(?:[/?#][^\s]*)?$ + description: 'Public website of the organization: an https URL with a host name, without credentials. The server also refuses a port, an IP address, a host name without a dot, and `localhost`. It never fetches the address.' + examples: + - https://payments.example.com +OrganizationContactChannels: + type: object + description: Public contacts of the organization, the ones a candidate sees on its card. They are company channels, such as a careers mailbox, the website, a company phone, or a company Telegram account, and never the personal email address, phone, or messenger of an employee; personal contacts of the people of the organization stay out of this object. The server cannot tell a company address from a personal one, so the owner answers for the content, and a candidate can complain about an organization through a support case. The object is the request field and the stored value alike, so a response can be sent back unchanged; every field is required and null means not set. A change replaces the whole object, never a single field of it. + additionalProperties: false + required: + - website + - email + - phone + - telegram + properties: + website: + oneOf: + - $ref: '#/OrganizationWebsite' + - type: 'null' + email: + description: Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given. + oneOf: + - $ref: '#/EmailAddress' + - type: 'null' + phone: + description: Public phone number of the organization, or null. + oneOf: + - $ref: '#/ContactPhoneNumber' + - type: 'null' + telegram: + description: Public Telegram account of the organization, or null. + oneOf: + - $ref: '#/ContactTelegramUsername' + - type: 'null' +OrganizationRepresentative: + type: object + description: 'A person that speaks for the organization to candidates, as the owner presents them on the card. It is presentation only: a representative is not a member of the organization, has no account link, and gains no right from being listed, and a member does not become a representative by joining. It holds no contact of the person; reaching the organization goes through its public contacts. The name is personal data of an employee that the owner publishes, so the owner must have the right to do it; see the open questions in the organization section of the API guide.' + additionalProperties: false + required: + - name + - job_title + properties: + name: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Name of the person as the card shows it. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + job_title: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Position of the person in the organization, for example "Руководитель по подбору". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. +OrganizationVerificationLevel: + type: string + description: 'Trust level of an organization (PRD FR07). It limits the quotas of the organization and, in a planned mode, the access of candidates under 18; it never replaces the consent of a candidate. + + + - e0: the confirmed email of the account that created the organization. Every new organization starts here. + + - e1: a corporate email, a verified domain, and a link with the organization. + + - e2: a check of the requisites and of the authority of the person. + + - e3: a manual check or a partner status. + + + The server reports e1, e2, or e3 only after a verification process has recorded it for the organization. No request of this contract sets or raises a level, and neither does an edit of the profile, the size of the profile, the number of members, or the domain of an email address. The first slice of the product uses e0 and e1; the processes for e1, e2, and e3 do not exist yet, so a client treats every level other than e0 as unavailable until they do. Adding a level is a contract change.' + enum: + - e0 + - e1 + - e2 + - e3 +OrganizationVerificationBasis: + type: string + description: 'Ground of the current verification level, the reason a cabinet can show next to it. + + + - confirmed_email: the confirmed email of the creating account (e0). + + - corporate_domain: a corporate email and a verified domain (e1). + + - requisites_and_authority: a check of the requisites and of the authority (e2). + + - manual_review: a manual check by the platform (e3). + + - partner_status: a partner status (e3). + + + Each level has its own bases, so a level and a basis that do not belong together never occur. Adding a value is a contract change.' + enum: + - confirmed_email + - corporate_domain + - requisites_and_authority + - manual_review + - partner_status +OrganizationVerification: + type: object + description: 'Verification level of an organization with its ground and the time it was set. It is read-only everywhere in this contract: the server sets it, and no request carries it. The scope of the check and the history of changes (PRD FR07) are planned as additive fields and a separate history with the first verification process.' + additionalProperties: false + required: + - level + - basis + - changed_at + properties: + level: + $ref: '#/OrganizationVerificationLevel' + basis: + $ref: '#/OrganizationVerificationBasis' + changed_at: + description: Moment the level was set to its current value; for a new organization, the creation time. + allOf: + - $ref: '#/Timestamp' +CandidateOrganizationCard: + type: object + description: 'The card of an organization as a candidate sees it: what an invitation shows before the candidate decides. The server builds it from the profile and the verification level and returns it to the owner as the preview of PRD FR07 ("through the eyes of the candidate"); a client never sends it. It holds no membership, no role, no account, no version, and no ground of the verification: a member''s email address, the number of members, and the history of the organization stay out of it. The card is the same object that the candidate side will return (planned in the invitation contract). Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the open question about publishing the names of representatives is decided (152-FZ). The server may leave `representatives` out, and a card without them means that the representatives are not published, not that the organization has none.' + additionalProperties: false + required: + - id + - name + - description + - sphere + - contacts + - verification_level + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + $ref: '#/OrganizationName' + description: + description: Description of the organization, or null. + oneOf: + - $ref: '#/OrganizationDescription' + - type: 'null' + sphere: + description: Field of business of the organization, or null. + oneOf: + - $ref: '#/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/OrganizationContactChannels' + representatives: + type: + - array + - 'null' + maxItems: 10 + description: Representatives in the order the owner gave them. Absent or null means that they are not published on this card, which says nothing about whether the organization has any. + items: + $ref: '#/OrganizationRepresentative' + verification_level: + $ref: '#/OrganizationVerificationLevel' +Organization: + type: object + description: 'Organization as its members read it: the profile that the owner edits, the verification level that only the server sets, and the card that a candidate sees. It never contains a role, a membership, the members of the organization, or an account identifier, so no field of it can raise a right: the role of the caller is in `OrganizationMembership` and comes only from the membership held by the server. The profile fields repeat in `candidate_card`, which is the candidate''s view of them; the client reads the profile fields for the form and `candidate_card` for the preview.' + additionalProperties: false + required: + - id + - version + - name + - description + - sphere + - contacts + - representatives + - verification + - candidate_card + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the organization, the `org_id` of every organization-scoped path. It never changes. + version: + $ref: '#/OrganizationVersion' + name: + $ref: '#/OrganizationName' + description: + description: Description of the organization, or null. + oneOf: + - $ref: '#/OrganizationDescription' + - type: 'null' + sphere: + description: Field of business of the organization, or null. + oneOf: + - $ref: '#/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/OrganizationContactChannels' + representatives: + type: array + maxItems: 10 + description: Representatives in the order the owner gave them. + items: + $ref: '#/OrganizationRepresentative' + verification: + $ref: '#/OrganizationVerification' + candidate_card: + $ref: '#/CandidateOrganizationCard' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +OrganizationCreate: + type: object + description: New organization. Only `name` is required, so a company can start with its name and complete the card later. The creating account becomes the owner of the organization; the body has no field for a role, a membership, an owner, a verification level, or a version, and unknown fields are rejected, so a request cannot set any of them. An absent `description` or `sphere`, and one sent as null, stay unset; an absent `contacts` has every contact unset; an absent `representatives` is an empty list. + additionalProperties: false + required: + - name + properties: + name: + $ref: '#/OrganizationName' + description: + oneOf: + - $ref: '#/OrganizationDescription' + - type: 'null' + sphere: + oneOf: + - $ref: '#/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/OrganizationContactChannels' + representatives: + type: array + maxItems: 10 + items: + $ref: '#/OrganizationRepresentative' +OrganizationUpdate: + type: object + description: Change of the profile of an organization over the version the client read. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged, and a representative left out of a sent list is removed. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. The body can change the profile only. It has no field for a role, a membership, an owner, a verification level, a basis, or a card, and unknown fields are rejected, so editing the profile can neither raise a right nor raise the trust level of the organization; both change only through processes of the server. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/OrganizationVersion' + name: + $ref: '#/OrganizationName' + description: + oneOf: + - $ref: '#/OrganizationDescription' + - type: 'null' + sphere: + oneOf: + - $ref: '#/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/OrganizationContactChannels' + representatives: + type: array + maxItems: 10 + items: + $ref: '#/OrganizationRepresentative' +OrganizationRole: + type: string + description: 'Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile. + + + - owner: manages the organization and its members, and acts on behalf of the company. + + - recruiter: leads the selection of candidates for all needs. + + - hiring_manager: acts on the needs assigned to the member. + + - technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations. + + + In the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change.' + enum: + - owner + - recruiter + - hiring_manager + - technical_expert +MembershipState: + type: string + description: 'State of a membership. Only `active` gives access: every other state answers as if the account were no member. + + + - active: the member works in the organization with the role. + + - suspended: access is stopped, and the owner or the platform may restore it. + + - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management. + + - left: the member ended the membership. + + + One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change.' + enum: + - active + - suspended + - removed + - left +OrganizationMembership: + type: object + description: The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them. + additionalProperties: false + required: + - organization_id + - role + - state + - joined_at + properties: + organization_id: + type: string + format: uuid + description: Identifier of the organization. + role: + $ref: '#/OrganizationRole' + state: + $ref: '#/MembershipState' + joined_at: + description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`). + allOf: + - $ref: '#/Timestamp' +OrganizationSummary: + type: object + description: 'An organization in the list of the caller''s organizations: what a switcher needs to name it. The profile, the contacts, and the representatives are in `Organization`.' + additionalProperties: false + required: + - id + - name + - verification_level + properties: + id: + type: string + format: uuid + description: Identifier of the organization, the `org_id` of its paths. + name: + $ref: '#/OrganizationName' + verification_level: + $ref: '#/OrganizationVerificationLevel' +MyOrganization: + type: object + description: An organization available to the caller together with the caller's membership in it. + additionalProperties: false + required: + - organization + - membership + properties: + organization: + $ref: '#/OrganizationSummary' + membership: + $ref: '#/OrganizationMembership' +MyOrganizationList: + type: object + description: One page of the organizations available to the caller, newest membership first. It holds only organizations where the caller has an `active` membership, so it is also the list of contexts the caller can work in; it never names an organization the caller cannot enter. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Organizations of the page. + items: + $ref: '#/MyOrganization' + page: + $ref: '#/PageInfo' +PracticeRunTest: + type: object + description: 'One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 +PracticeRunCreate: + type: object + description: Debug run of a practice solution against the public examples of the task and up to ten tests of the candidate. It never runs a hidden check and never changes the practice state, the verdict, or the attempt version. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + - language + - source_code + properties: + item_id: + $ref: '#/AssessmentItemId' + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: '#/TaskLanguage' + - type: 'null' + source_code: + type: string + minLength: 1 + maxLength: 65536 + tests: + type: array + maxItems: 10 + description: Tests of the candidate, run after the public examples. + items: + $ref: '#/PracticeRunTest' +PracticeRunState: + type: string + description: 'State of a debug run. + + + - queued: the run waits in the sandbox queue. + + - running: the sandbox runs it. + + - finished: `result` holds the outcome of the public examples and the tests of the candidate. + + - failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run. + + + Adding a value is a contract change.' + enum: + - queued + - running + - finished + - failed +PracticeRunOutcome: + type: string + description: Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error +PracticeRunTestSource: + type: string + description: 'Where a test of a debug run comes from: a public example of the task or a test of the candidate.' + enum: + - example + - candidate +PracticeRunTestResult: + type: object + description: Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed. + additionalProperties: false + required: + - source + - index + - outcome + - time_ms + - memory_kb + - diagnostic + properties: + source: + $ref: '#/PracticeRunTestSource' + index: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Position of the test in its source, from 1. + outcome: + $ref: '#/PracticeRunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + diagnostic: + description: Truncated error output of a failed test, or null. + oneOf: + - type: string + maxLength: 2048 + - type: 'null' +PracticeRunResult: + type: object + description: Result of a debug run on the public examples and the tests of the candidate. It never contains a hidden check, its outcome, or the score. + additionalProperties: false + required: + - outcome + - compile_diagnostic + - tests + properties: + outcome: + $ref: '#/PracticeRunOutcome' + compile_diagnostic: + description: The compiler message when `outcome` is `compile_error`, otherwise null. + oneOf: + - type: string + maxLength: 4096 + - type: 'null' + tests: + type: array + maxItems: 20 + items: + $ref: '#/PracticeRunTestResult' +PracticeRun: + type: object + description: Debug run of a practice solution. It shows only the public examples and the tests of the candidate; hidden checks are never run, listed, or scored by a debug run. + additionalProperties: false + required: + - id + - item_id + - state + - created_at + - finished_at + - failure_reason + - result + properties: + id: + type: string + format: uuid + description: Identifier of the run. + item_id: + $ref: '#/AssessmentItemId' + state: + $ref: '#/PracticeRunState' + created_at: + $ref: '#/Timestamp' + finished_at: + description: Time the run reached `finished` or `failed`, or null. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + failure_reason: + description: '`sandbox_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/PracticeFailureReason' + - type: 'null' + result: + description: The result when `state` is `finished`, otherwise null. + oneOf: + - $ref: '#/PracticeRunResult' + - type: 'null' +PublicationVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale. + examples: + - 2 +SearchStatusVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`. + examples: + - 3 +CardField: + type: string + description: 'A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. + + + - categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`. + + - self_assessment: the candidate''s declared specialization and grade, separate from confirmed categories. + + - stack: only recognized technology codes from the server''s closed taxonomy. + + - experience: a coarse total-experience band, without employers, periods, or descriptions. + + - work_formats: explicitly selected work formats from the private questionnaire. + + - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. + + - projects: the projects of the profile with their title, description, stack tags, and whether a linked repository is a public GitHub repository. The titles and descriptions are text that the candidate writes and may identify them; the repository address and its owner never reach an organization through the card. Published projects are also the text that semantic ranking reads and that match explanations name. + + - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card. + + + Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. + + + Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own.' + enum: + - categories + - salary_compatibility + - self_assessment + - stack + - experience + - soft_skills + - location + - relocation + - work_formats + - projects +CardFieldSet: + type: array + minItems: 0 + maxItems: 10 + uniqueItems: true + description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays. + items: + $ref: '#/CardField' +PublicationState: + type: string + description: 'Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked. + + + - closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked. + + - published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid.' + enum: + - closed + - published +PublicationClosedReason: + type: string + description: 'Why a closed profile is closed, shown only to the candidate. + + + - never_published: the candidate has never published the profile. + + - closed_by_candidate: the candidate closed the publication. + + - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record.' + enum: + - never_published + - closed_by_candidate + - consent_revoked +Publication: + type: object + description: 'Publication setting of the candidate card. It is separate from the consent: the C2 consent in the ledger proves that the candidate accepted the publication text, and this setting records whether and which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, whatever the stored setting says, so a revocation closes the card at once. The state, the fields, and the times belong to the history that the C2 consent record does not carry.' + additionalProperties: false + required: + - state + - closed_reason + - fields + - consent_id + - published_at + - version + properties: + state: + $ref: '#/PublicationState' + closed_reason: + description: Why the profile is closed, or null while it is published. + oneOf: + - $ref: '#/PublicationClosedReason' + - type: 'null' + fields: + description: Card fields that organizations may read. Empty exactly when `state` is `closed`. + allOf: + - $ref: '#/CardFieldSet' + consent_id: + description: Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published. + oneOf: + - type: string + format: uuid + - type: 'null' + published_at: + description: Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + version: + $ref: '#/PublicationVersion' +PublicationUpdate: + type: object + description: 'The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account''s current unrevoked C2 record, and a client can neither supply nor forge one.' + additionalProperties: false + required: + - expected_version + - state + - fields + properties: + expected_version: + $ref: '#/PublicationVersion' + state: + $ref: '#/PublicationState' + fields: + $ref: '#/CardFieldSet' +SearchStatusValue: + type: string + description: 'Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations. + + + - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`. + + - not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls.' + enum: + - looking + - not_looking +SearchStatus: + type: object + description: 'Search status of the candidate as it holds now. The status `looking` stores the moment of its confirmation and lapses when the confirmation interval of the product policy passes without a new confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public state, and a lapse never changes the publication or the hidden organizations. It needs no stored change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms again explicitly.' + additionalProperties: false + required: + - value + - lapsed + - confirmed_at + - lapses_at + - version + properties: + value: + description: 'The status that holds now: `looking` only while the confirmation has not lapsed.' + allOf: + - $ref: '#/SearchStatusValue' + lapsed: + type: boolean + description: True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` is `not_looking`. False otherwise, including a status the candidate cleared. + confirmed_at: + description: Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared it. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + lapses_at: + description: Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` section of the product policy version in force then, or null when `confirmed_at` is null. A later policy change does not move it; it stays in the past for a lapsed status. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + version: + $ref: '#/SearchStatusVersion' +SearchStatusUpdate: + type: object + description: 'The complete new search status. `looking` is also the confirmation of a status that still holds or has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy version; the server takes them from the effective product policy.' + additionalProperties: false + required: + - expected_version + - value + properties: + expected_version: + $ref: '#/SearchStatusVersion' + value: + $ref: '#/SearchStatusValue' +PrivacyOrganization: + type: object + description: Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Current name of the organization. Plain text; clients show it as text, never as HTML. +HiddenOrganization: + type: object + description: 'One organization that the candidate hides the profile from. The record belongs to the candidate: no organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not published.' + additionalProperties: false + required: + - organization + - hidden_at + properties: + organization: + $ref: '#/PrivacyOrganization' + hidden_at: + $ref: '#/Timestamp' +HiddenOrganizationList: + type: object + description: One page of the organizations that the candidate hides the profile from, newest first with the organization identifier as the tie-breaker. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Hidden organizations of the page. + items: + $ref: '#/HiddenOrganization' + page: + $ref: '#/PageInfo' +PrivacySettings: + type: object + description: 'The visibility settings of the current candidate in one read: the publication, the search status, and the number of hidden organizations. The three are independent: each has its own version and its own operation, and a change of one leaves the others as they were. A new account reads a closed profile, `not_looking`, and no hidden organization.' + additionalProperties: false + required: + - publication + - search_status + - hidden_organizations_total + properties: + publication: + $ref: '#/Publication' + search_status: + $ref: '#/SearchStatus' + hidden_organizations_total: + type: integer + minimum: 0 + maximum: 1000 + description: Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`. +CardCategory: + type: object + description: A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation. + additionalProperties: false + required: + - specialization + - grade + - strength + - basis + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' + strength: + type: string + enum: + - standard + - strong + description: Coarse strength of the authoritative confirmation. + basis: + $ref: '#/EvidenceBasis' +CardSelfAssessment: + type: object + description: Candidate-declared specialization and optional grade. This is never an assessment result. + additionalProperties: false + required: + - specialization + - confirmation_status + properties: + specialization: + $ref: '#/SpecializationCode' + confirmation_status: + type: string + enum: + - confirmed + - unconfirmed + declared_grade: + oneOf: + - $ref: '#/GradeCode' + - type: 'null' +CandidateExperienceBand: + type: string + description: Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they are returned. + enum: + - '0_1' + - '1_3' + - '3_6' + - 6_plus + - '0_3' + - 3_plus +CandidateWorkFormat: + type: string + enum: + - remote + - office + - hybrid +CandidateSalaryCompatibility: + type: string + description: A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card. + enum: + - compatible + - not_compatible +CardProject: + type: object + description: One published project as the card shows it. It never carries the repository address, the repository owner, or any text fetched from the repository. + additionalProperties: false + required: + - title + - description + - stack + - repository_verified + properties: + title: + type: string + minLength: 1 + maxLength: 100 + description: Project title as the candidate published it. Plain text; show it as text, never as HTML. + description: + description: Published project description, or null. Plain text; show it as text, never as HTML. + oneOf: + - type: string + minLength: 1 + maxLength: 500 + - type: 'null' + stack: + type: array + maxItems: 10 + description: Published technology tags of the project. + items: + $ref: '#/StackTag' + repository_verified: + type: boolean + description: True when the latest server check found the linked repository on GitHub and it is public. It does not prove that the candidate wrote the code. +AnonymousCardContent: + type: object + description: 'The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The one free-text exception is `projects`: the candidate writes it and publishes it by a separate explicit choice, the card never adds the repository address or owner to it, and the client warns that a project title can identify its author. The search ranking + and the full card of an organization''s search result are defined by the search contract, which reuses this content.' + additionalProperties: false + required: + - pseudonym + - categories + - stack + - self_assessment + - experience_band + - work_formats + - salary_compatibility + - projects + properties: + pseudonym: + type: string + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations. + categories: + type: + - array + - 'null' + maxItems: 9 + description: Categories confirmed by assessment results, or null. + items: + $ref: '#/CardCategory' + stack: + type: + - array + - 'null' + maxItems: 4 + description: Recognized confirmed technology codes only, or null. + items: + type: string + enum: + - go + - postgresql + - kafka + - docker + self_assessment: + type: + - array + - 'null' + maxItems: 9 + description: Candidate-declared specialization and grade, separate from categories. + items: + $ref: '#/CardSelfAssessment' + experience_band: + oneOf: + - $ref: '#/CandidateExperienceBand' + - type: 'null' + description: Coarse total work-experience bucket, or null. + work_formats: + type: + - array + - 'null' + maxItems: 3 + description: Explicitly opted-in work formats, or null. + items: + $ref: '#/CandidateWorkFormat' + salary_compatibility: + oneOf: + - $ref: '#/CandidateSalaryCompatibility' + - type: 'null' + description: Nullable compatibility result with no salary values. + projects: + type: + - array + - 'null' + maxItems: 10 + description: 'Published projects in the candidate''s order, or null. Cohort generalization never changes them: they are text the candidate chose to publish, so publishing them can make the card unique.' + items: + $ref: '#/CardProject' +CardPreview: + type: object + description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed. + additionalProperties: false + required: + - state + - fields + - card + - evidence + - generated_at + properties: + state: + $ref: '#/PublicationState' + fields: + $ref: '#/CardFieldSet' + card: + oneOf: + - $ref: '#/AnonymousCardContent' + - type: 'null' + evidence: + oneOf: + - $ref: '#/OrganizationEvidence' + - type: 'null' + generated_at: + $ref: '#/Timestamp' +PrivacyEventKind: + type: string + description: 'Kind of a change of the visibility settings that the history records. + + + - publication_opened: the candidate published a closed profile. + + - publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record. + + - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here. + + - search_status_confirmed: the candidate set or confirmed `looking`. + + - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. + + - organization_hidden: the candidate hid the profile from an organization. + + - organization_unhidden: the candidate lifted the hiding for an organization.' + enum: + - publication_opened + - publication_changed + - publication_closed + - search_status_confirmed + - search_status_cleared + - organization_hidden + - organization_unhidden +PrivacyEvent: + type: object + description: One recorded change of the visibility settings of the current candidate, as evidence of what was published, hidden, or announced and when. The history is append-only and returns only the caller's own records. A publication event carries the published fields and the C2 record behind them; an organization event names the organization; the other properties are null. + additionalProperties: false + required: + - id + - kind + - occurred_at + - fields + - consent_id + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the event. + kind: + $ref: '#/PrivacyEventKind' + occurred_at: + $ref: '#/Timestamp' + fields: + description: Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind. + oneOf: + - $ref: '#/CardFieldSet' + - type: 'null' + consent_id: + description: C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null. + oneOf: + - type: string + format: uuid + - type: 'null' + organization: + description: Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved when the history is read (the event stores only the identifier), or null. + oneOf: + - $ref: '#/PrivacyOrganization' + - type: 'null' +PrivacyEventList: + type: object + description: One page of the settings history of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Events of the page. + items: + $ref: '#/PrivacyEvent' + page: + $ref: '#/PageInfo' +CardAccessKind: + type: string + description: 'How an organization reached the candidate. + + + - card_viewed: an organization read the permitted anonymous card. + + - contact_read: an organization read the contacts through the contact grant of an accepted invitation.' + enum: + - card_viewed + - contact_read +CardAccess: + type: object + description: One access of an organization to the card or the contacts of the current candidate. A retained access permits the candidate to see the organization's identifier and current name and to hide their profile from it. `organization` is null when the organization cannot be presented. Earlier permitted accesses remain after hiding. The record carries no employee identity, query, ranking, or search filter of the organization. + additionalProperties: false + required: + - id + - kind + - occurred_at + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the access record. + kind: + $ref: '#/CardAccessKind' + occurred_at: + $ref: '#/Timestamp' + organization: + oneOf: + - $ref: '#/PrivacyOrganization' + - type: 'null' +CardAccessList: + type: object + description: One page of the accesses to the card of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Accesses of the page. + items: + $ref: '#/CardAccess' + page: + $ref: '#/PageInfo' +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + + - 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, or an `expected_version` field in the request body, does not match the current version; nothing was changed. + + - 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. + + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later.' + 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 + - service_unavailable +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie +QuestionnaireVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one. + examples: + - 3 +StackTag: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: 'Free technology tag of the candidate''s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.' +WorkFormat: + type: string + description: 'Acceptable work format: `remote`, `office`, or `hybrid`.' + enum: + - remote + - office + - hybrid +WorkContext: + type: object + description: 'Working context of the candidate''s search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.' + additionalProperties: false + required: + - work_formats + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Acceptable work formats. + items: + $ref: '#/WorkFormat' +CandidateExperience: + type: object + description: 'Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.' + additionalProperties: false + required: + - commercial_months + - academic_months + properties: + commercial_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of commercial work in the specialization. + academic_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of study, internships, or academic projects in the specialization. +QuestionnaireSpecialization: + type: object + description: 'One specialization chosen by the candidate with the candidate''s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - task_languages + - stack + - experience + properties: + specialization: + $ref: '#/SpecializationCode' + self_assessed_grade: + $ref: '#/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language. + items: + $ref: '#/TaskLanguage' + stack: + type: array + maxItems: 20 + uniqueItems: true + description: Technology tags of the candidate in this specialization. + items: + $ref: '#/StackTag' + experience: + description: Stated experience, or null when the candidate did not state it. + oneOf: + - $ref: '#/CandidateExperience' + - type: 'null' +CandidateQuestionnaire: + type: object + description: 'Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the working context. It never contains a confirmed grade or a category; those come only from assessment results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and null `work_context` and `updated_at`.' + additionalProperties: false + required: + - version + - specializations + - work_context + - updated_at + properties: + version: + $ref: '#/QuestionnaireVersion' + specializations: + type: array + maxItems: 2 + description: Chosen specializations in the order the candidate gave them, each specialization at most once. Each one is assessed independently. + items: + $ref: '#/QuestionnaireSpecialization' + work_context: + description: Working context, or null before the first save. + oneOf: + - $ref: '#/WorkContext' + - type: 'null' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' +CandidateQuestionnaireUpdate: + type: object + description: Complete new state of the questionnaire. It replaces the stored specializations and working context as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - specializations + - work_context + properties: + expected_version: + $ref: '#/QuestionnaireVersion' + specializations: + type: array + minItems: 1 + maxItems: 2 + description: One or two chosen specializations. The schema limits the count; the server also requires each specialization to appear at most once and answers a repeated one with 400 validation_failed and the pointer of the repeated item's `specialization`, for example `/specializations/1/specialization`. + items: + $ref: '#/QuestionnaireSpecialization' + work_context: + $ref: '#/WorkContext' +SupportCaseNumber: + type: string + minLength: 14 + maxLength: 18 + pattern: ^SC-[0-9]{4}-[0-9]{6,10}$ + description: 'Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.' + examples: + - SC-2026-000123 +SupportCaseType: + type: string + description: 'Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case. + + + - support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts. + + - complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts. + + - grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts. + + - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts. + + - manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts.' + enum: + - support + - complaint + - grade_appeal + - anticheat_appeal + - manual_assessment +SupportCaseStatus: + type: string + description: 'Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value. + + + - submitted: the case was accepted and waits in its queue. + + - in_review: support or a moderator works on it. + + - waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status. + + - waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time. + + - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. + + - closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why.' + enum: + - submitted + - in_review + - waiting_for_user + - waiting_expert + - resolved + - closed +SupportCaseObjectType: + type: string + description: 'Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis. + + + - assessment_attempt: an assessment attempt of the caller. + + - organization: an organization that the caller can see. + + - invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found. + + - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes.' + enum: + - assessment_attempt + - organization + - invitation + - support_case +SupportCaseObjectReference: + type: object + description: Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person's object exists. The case keeps only the type and the identifier, never a copy of the object. + additionalProperties: false + required: + - type + - id + properties: + type: + $ref: '#/SupportCaseObjectType' + id: + type: string + format: uuid + description: Identifier of the object. +SupportCaseAttemptReference: + type: object + description: Reference to an assessment attempt of the caller. Any other object type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + id: + type: string + format: uuid + description: Identifier of an assessment attempt of the caller. +SupportCaseGradeAppealReference: + type: object + description: 'Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + - support_case + id: + type: string + format: uuid + description: Identifier of the attempt or the case. +SupportCaseComplaintReference: + type: object + description: 'Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - organization + - invitation + id: + type: string + format: uuid + description: Identifier of the organization or the invitation. +SupportCaseAssessmentTarget: + type: object + description: 'Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.' + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/SpecializationCode' + grade: + $ref: '#/GradeCode' +SupportCaseComplaintReason: + type: string + description: 'Ground of a complaint (PRD FR18). + + + - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. + + - offer_content: misleading or discriminatory content of an offer. Requires an invitation reference. + + - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference. + + - data_disclosure: a disclosure of the caller''s personal data beyond what the caller granted. + + - other: another ground, explained in the description.' + enum: + - organization_conduct + - offer_content + - salary_terms_violation + - data_disclosure + - other +SupportCaseDescription: + type: string + minLength: 1 + maxLength: 4000 + pattern: \S + description: 'What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people''s contact data into it. Generated + Zod validators count UTF-16 code units, so the server stays authoritative for the length.' + examples: + - Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. +SupportCasePublicText: + type: string + minLength: 1 + maxLength: 4000 + description: 'Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.' +SupportCaseCreateSupport: + type: object + description: New support case. Both the object reference and the assessment target are optional context; omit what does not apply. + additionalProperties: false + required: + - type + - description + properties: + type: + type: string + enum: + - support + description: + $ref: '#/SupportCaseDescription' + object: + $ref: '#/SupportCaseObjectReference' + assessment_target: + $ref: '#/SupportCaseAssessmentTarget' +SupportCaseCreateComplaint: + type: object + description: New complaint about an organization or an offer. + additionalProperties: false + required: + - type + - description + - complaint_reason + - object + properties: + type: + type: string + enum: + - complaint + description: + $ref: '#/SupportCaseDescription' + complaint_reason: + $ref: '#/SupportCaseComplaintReason' + object: + $ref: '#/SupportCaseComplaintReference' +SupportCaseCreateGradeAppeal: + type: object + description: 'New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.' + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - grade_appeal + description: + $ref: '#/SupportCaseDescription' + object: + $ref: '#/SupportCaseGradeAppealReference' +SupportCaseCreateAnticheatAppeal: + type: object + description: New appeal of an anti-cheat review decision on an own assessment attempt. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - anticheat_appeal + description: + $ref: '#/SupportCaseDescription' + object: + $ref: '#/SupportCaseAttemptReference' +SupportCaseCreateManualAssessment: + type: object + description: 'New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.' + additionalProperties: false + required: + - type + - description + - assessment_target + properties: + type: + type: string + enum: + - manual_assessment + description: + $ref: '#/SupportCaseDescription' + assessment_target: + $ref: '#/SupportCaseAssessmentTarget' + object: + $ref: '#/SupportCaseAttemptReference' +SupportCaseCreate: + description: 'New case, selected by `type`. Each type fixes its required fields and the object types it accepts. The body carries only what the user states: the request has no status, decision, outcome, priority, response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown fields, so a client cannot set any of them. The user and the account come only from the session.' + oneOf: + - $ref: '#/SupportCaseCreateSupport' + - $ref: '#/SupportCaseCreateComplaint' + - $ref: '#/SupportCaseCreateGradeAppeal' + - $ref: '#/SupportCaseCreateAnticheatAppeal' + - $ref: '#/SupportCaseCreateManualAssessment' +SupportResponseTarget: + type: object + description: 'Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.' + additionalProperties: false + required: + - kind + - business_days + - due_at + - answered_at + - late + - policy_version + properties: + kind: + type: string + enum: + - operational_goal + description: Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline. + business_days: + type: integer + format: int32 + minimum: 1 + maximum: 60 + description: Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal. + due_at: + $ref: '#/Timestamp' + answered_at: + description: Time the target was met, or null while it is not. + oneOf: + - $ref: '#/Timestamp' + - type: 'null' + late: + type: boolean + description: 'Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.' + policy_version: + type: integer + format: int32 + minimum: 1 + description: Number of the `product` policy version that fixed the target. +SupportCaseDecisionOutcome: + type: string + description: 'Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. + + + - upheld: the appeal or the complaint is upheld in full. + + - partially_upheld: the appeal or the complaint is upheld in part. + + - not_upheld: the appeal or the complaint is not upheld. + + - answered: a support case was answered. + + - assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case.' + enum: + - upheld + - partially_upheld + - not_upheld + - answered + - assessed +SupportCaseDecision: + type: object + description: 'Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.' + additionalProperties: false + required: + - outcome + - reason + - decided_at + properties: + outcome: + $ref: '#/SupportCaseDecisionOutcome' + reason: + $ref: '#/SupportCasePublicText' + decided_at: + $ref: '#/Timestamp' +SupportCaseActorKind: + type: string + description: 'Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change. + + + - user: the author of the case. + + - support: a person of the support, moderation, or expert staff. + + - system: the server, for example on creation or when it routes the case.' + enum: + - user + - support + - system +SupportCaseEventKind: + type: string + description: 'Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value. + + + - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. + + - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. + + - reply: support replied; `message` holds the reply and `status` is null. + + - decision: a decision was made; `status` is `resolved` and `message` holds the public reason.' + enum: + - created + - status_changed + - reply + - decision +SupportCaseEvent: + type: object + description: One public event of the case history. Internal notes, assignments, evidence requests, and risk signals are never history events. + additionalProperties: false + required: + - sequence + - kind + - actor + - occurred_at + - status + - message + properties: + sequence: + type: integer + format: int32 + minimum: 1 + description: Position of the event in the history, starting at 1 and increasing by one. + kind: + $ref: '#/SupportCaseEventKind' + actor: + $ref: '#/SupportCaseActorKind' + occurred_at: + $ref: '#/Timestamp' + status: + description: Status of the case after the event, or null for a reply. + oneOf: + - $ref: '#/SupportCaseStatus' + - type: 'null' + message: + description: Public text of the event, or null. + oneOf: + - $ref: '#/SupportCasePublicText' + - type: 'null' +SupportCase: + type: object + description: Case of the current account. It contains what the author sent, the public processing state, and the public history. It never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of another person. Fields that do not apply to the type are null. + additionalProperties: false + required: + - id + - number + - type + - status + - description + - object + - assessment_target + - complaint_reason + - rubric_version + - response_target + - decision + - history + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/SupportCaseNumber' + type: + $ref: '#/SupportCaseType' + status: + $ref: '#/SupportCaseStatus' + description: + $ref: '#/SupportCaseDescription' + object: + description: Object that the case is about, as sent on creation, or null when the case has none. + oneOf: + - $ref: '#/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of a manual assessment, the optional category of a support case, or null. + oneOf: + - $ref: '#/SupportCaseAssessmentTarget' + - type: 'null' + complaint_reason: + description: Ground of a complaint, or null for other types. + oneOf: + - $ref: '#/SupportCaseComplaintReason' + - type: 'null' + rubric_version: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: For a manual assessment, the version of the grading policy pinned by the server at creation. The exact reviewed category opening and rubric manifest are retained privately so the expert can use the same rubric as automated assessment. Null for other types and for a manual assessment without one unique current reviewed category; the case still waits in `waiting_expert`. + response_target: + $ref: '#/SupportResponseTarget' + decision: + description: Decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/SupportCaseDecision' + - type: 'null' + history: + type: array + minItems: 1 + maxItems: 200 + description: 'Every public event in the order it happened, starting with `created`; the list is never truncated. The server keeps a case within 200 events: it rejects a staff reply or status change that would leave no room for the terminal event, so a case always fits and can always be resolved or closed. Further correspondence goes into a new case that references this one as `support_case`.' + items: + $ref: '#/SupportCaseEvent' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +SupportCaseSummary: + type: object + description: 'Case in a list: the fields that a list of cases shows, without the description and the history. GetMySupportCase returns the full case.' + additionalProperties: false + required: + - id + - number + - type + - status + - object + - assessment_target + - response_target + - decision_outcome + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/SupportCaseNumber' + type: + $ref: '#/SupportCaseType' + status: + $ref: '#/SupportCaseStatus' + object: + description: Object that the case is about, or null. + oneOf: + - $ref: '#/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of the case, or null. + oneOf: + - $ref: '#/SupportCaseAssessmentTarget' + - type: 'null' + response_target: + $ref: '#/SupportResponseTarget' + decision_outcome: + description: Outcome of the decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/SupportCaseDecisionOutcome' + - type: 'null' + created_at: + $ref: '#/Timestamp' + updated_at: + $ref: '#/Timestamp' +SupportCaseList: + type: object + description: One page of the cases of the current account, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Case summaries of the page. + items: + $ref: '#/SupportCaseSummary' + page: + $ref: '#/PageInfo' diff --git a/api/core/components/schemas/assessment_schemas.yml b/api/core/components/schemas/assessment_schemas.yml new file mode 100644 index 0000000..4d5030d --- /dev/null +++ b/api/core/components/schemas/assessment_schemas.yml @@ -0,0 +1,1943 @@ +schemas: + AssessmentMode: + type: string + description: |- + Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. + + - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. + - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + - demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence. + + Adding a value is a contract change. + enum: + - demo_basic + - demo_express + - adaptive + AssessmentRealMode: + type: string + description: Server-selected mode available to a real category assessment. + enum: + - demo_basic + - adaptive + AssessmentAttemptKind: + type: string + description: Assessment track that distinguishes root, corrective, and training attempts. + enum: + - root + - corrective + - demo_express + AssessmentAttemptVersion: + type: integer + format: int64 + minimum: 1 + description: >- + Version of an assessment attempt. A new attempt has version 1, and each + committed change advances it by exactly one: an accepted answer, a + practice submission or resubmission, a verdict, a decision of + finalize, an explicit work-session start, and a server-side transition + such as expiry or automatic finalization. Reads never change the + attempt. A rejected command and a repeat that stores nothing leave it + unchanged. Commands send the version they read as `expected_version`. + examples: + - 4 + AssessmentAttemptState: + type: string + description: |- + Lifecycle state of an attempt and the commands it accepts. + + - in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item. + - practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part. + - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence. + - ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt. + - completed: a decision was made; the result is available. + - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. + - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. + + When `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. + enum: + - in_progress + - practice_pending + - additional_practice_pending + - ready_to_finalize + - completed + - expired + - insufficient_bank + AssessmentVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Opaque identifier of a published version, for example + `backend-demo.2026-10.1`. Clients show it as text and never parse it. + AssessmentVersions: + type: object + description: >- + Versions fixed when the attempt was created. They never change during + the attempt, and a result is always reproduced from the stored answers + with these versions; a later policy, bank, or algorithm version does + not rewrite it. + additionalProperties: false + required: + - policy_version + - bank_version + - algorithm_version + properties: + policy_version: + type: integer + format: int32 + minimum: 1 + description: >- + Number of the `product` policy version whose assessment rules + apply: thresholds, stop rules, item limits, time and session + limits, and retry intervals. + bank_version: + $ref: "#/schemas/AssessmentVersionLabel" + algorithm_version: + $ref: "#/schemas/AssessmentVersionLabel" + AssessmentSessions: + type: object + description: |- + Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. + + Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them. + additionalProperties: false + required: + - used + - max + - idle_timeout_seconds + properties: + used: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Sessions started so far, including the current one. + max: + type: integer + format: int32 + minimum: 1 + maximum: 10 + idle_timeout_seconds: + type: integer + format: int32 + minimum: 60 + maximum: 86400 + description: Inactivity after which the current session ends. + AssessmentAttemptCreate: + description: >- + Start a real assessment, a corrective attempt in an existing chain, or + an explicit training run. The required `kind` discriminator selects + one of the three request shapes; `mode` remains server-selected for + real assessments. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedAttemptCreate" + - $ref: "#/schemas/AssessmentCorrectiveAttemptCreate" + - $ref: "#/schemas/AssessmentExpressAttemptCreate" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedAttemptCreate" + corrective: "#/schemas/AssessmentCorrectiveAttemptCreate" + demo_express: "#/schemas/AssessmentExpressAttemptCreate" + AssessmentQualifiedAttemptCreate: + type: object + description: >- + Start a real assessment for a specialization and target grade, with + the task language. The candidate comes from the session. The server + chooses demo_basic or adaptive and fixes the policy, bank, and + algorithm versions. Unknown fields such as `mode`, `seed`, + or `score` are rejected. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + properties: + kind: + type: string + enum: + - root + description: Start a real-assessment chain and reserve one root quota slot. + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_language: + description: >- + Task language of the attempt, one of the `task_languages` of the + published bank, or null when the bank offers no choice of + language. The questionnaire choice is the value the client offers + first. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + AssessmentCorrectiveAttemptCreate: + type: object + description: >- + Start a corrective real assessment at a lower target grade in the + chain rooted at root_attempt_id. The server validates that this grade + is strictly below the preceding grade and that the chain remains + within its existing deadline and quota. chain_deadline is derived + from the root attempt and is never supplied by the client. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + - root_attempt_id + properties: + kind: + type: string + enum: + - corrective + description: Continue the existing real-assessment chain without reserving another root slot. + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + root_attempt_id: + type: string + format: uuid + description: Root real-assessment attempt whose quota and deadline this attempt shares. + AssessmentExpressAttemptCreate: + type: object + description: >- + Explicitly start the short training run. It has no specialization or + target grade, uses its separate demo policy, and does not consume a + real-assessment attempt. + additionalProperties: false + required: + - kind + properties: + kind: + type: string + enum: + - demo_express + description: Explicitly request the training run; real modes cannot be selected by the client. + AssessmentAttemptSessionStart: + type: object + description: Start or resume a work session using the attempt version last read by the candidate. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/AssessmentAttemptVersion" + AssessmentItemId: + type: string + format: uuid + description: >- + Identifier of an item instance in one attempt. It identifies the fixed + variant served to this candidate and reveals neither the task family, + its version, nor the variant seed. + AssessmentOptionId: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[A-Za-z0-9_-]+$" + description: >- + Opaque identifier of a choice option or an order element within one + item instance. It is unrelated to the position or correctness of the + option. + AssessmentOption: + type: object + description: Choice option or order element. Plain text. + additionalProperties: false + required: + - id + - text + properties: + id: + $ref: "#/schemas/AssessmentOptionId" + text: + type: string + minLength: 1 + maxLength: 2000 + description: Text of the option; the client shows it as text, never as HTML. + ChoiceItemContent: + type: object + description: >- + Choose one option, or several when `multiple` is true. The content + never says which options are correct or how many are. + additionalProperties: false + required: + - format + - options + - multiple + properties: + format: + type: string + enum: + - choice + options: + type: array + minItems: 2 + maxItems: 10 + description: Options in the order of this instance. + items: + $ref: "#/schemas/AssessmentOption" + multiple: + type: boolean + description: >- + Whether more than one option may be selected. It is a property of + the task family, fixed for every variant, and never derived from + the key: a multiple-choice variant may have a single correct + option. + NumberItemContent: + type: object + description: Enter a number, optionally in the given unit. + additionalProperties: false + required: + - format + - unit + properties: + format: + type: string + enum: + - number + unit: + type: + - string + - "null" + minLength: 1 + maxLength: 32 + description: Unit of the expected value, for example `ms`, or null. + StringItemContent: + type: object + description: Enter a short string, such as a command, a header name, or an address. + additionalProperties: false + required: + - format + - max_length + properties: + format: + type: string + enum: + - string + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 500 + description: >- + Maximum length of the answer in characters. It is an input limit + of the task family, never derived from the key, so it does not + reveal the length of the correct answer. + OrderItemContent: + type: object + description: >- + Put every element into the right order. The elements arrive in the + order of this instance, which is never the answer. + additionalProperties: false + required: + - format + - elements + properties: + format: + type: string + enum: + - order + elements: + type: array + minItems: 2 + maxItems: 20 + items: + $ref: "#/schemas/AssessmentOption" + CodeLine: + type: object + description: One numbered line of a code or configuration fragment. Plain text. + additionalProperties: false + required: + - number + - text + properties: + number: + type: integer + format: int32 + minimum: 1 + maximum: 500 + text: + type: string + maxLength: 1000 + FindErrorItemContent: + type: object + description: >- + Find the lines with the error in a code or configuration fragment and + select up to `max_selections` line numbers. + additionalProperties: false + required: + - format + - syntax + - lines + - max_selections + properties: + format: + type: string + enum: + - find_error + syntax: + type: + - string + - "null" + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9_+-]+$" + description: Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + lines: + type: array + minItems: 1 + maxItems: 500 + description: Lines numbered from 1 in order. + items: + $ref: "#/schemas/CodeLine" + max_selections: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: >- + Maximum number of lines the answer may select. It is a limit of + the task family, fixed for every variant and never derived from the + key; it is not the number of wrong lines. + ConfigurationItemContent: + type: object + description: >- + Write or fix a configuration. The server checks the submitted text + with the computed key or reference check of the task family; it never + executes it as code. + additionalProperties: false + required: + - format + - syntax + - initial_config + - max_length + properties: + format: + type: string + enum: + - configuration + syntax: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9_+-]+$" + description: Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + initial_config: + type: string + maxLength: 20000 + description: Starting text to edit; empty when the candidate writes it from scratch. + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 20000 + description: >- + Maximum length of the submitted configuration in characters, an + input limit of the task family that is never derived from the key. + PracticeExample: + type: object + description: >- + Public example of the practice task: an input and its expected output. + Hidden checks are never listed. + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeItemContent: + type: object + description: >- + Code practice. The candidate submits one final solution, which runs in + the isolated sandbox against three groups of hidden checks. The content + lists only the statement, the allowed languages, and public examples; + hidden checks, their inputs, and seeds never reach the client. + additionalProperties: false + required: + - format + - languages + - public_examples + - max_source_length + properties: + format: + type: string + enum: + - practice + languages: + type: array + maxItems: 2 + uniqueItems: true + description: >- + Languages the solution may use. Empty when the task does not offer + a choice; the submission then sends a null language. + items: + $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + public_examples: + type: array + maxItems: 10 + items: + $ref: "#/schemas/PracticeExample" + max_source_length: + type: integer + format: int32 + minimum: 1 + maximum: 65536 + description: Maximum length of the solution source in characters. + ItemContent: + description: >- + Format-specific part of an item, selected by `format`. It holds only + what the candidate needs to answer: never an answer key, a correct + option, a score, a family or variant identifier, a seed, or a hidden + check. Limits such as `multiple`, `max_selections`, and `max_length` + belong to the format or the task family and never reveal the key. + oneOf: + - $ref: "#/schemas/ChoiceItemContent" + - $ref: "#/schemas/NumberItemContent" + - $ref: "#/schemas/StringItemContent" + - $ref: "#/schemas/OrderItemContent" + - $ref: "#/schemas/FindErrorItemContent" + - $ref: "#/schemas/ConfigurationItemContent" + - $ref: "#/schemas/PracticeItemContent" + - $ref: "./lab_schemas.yml#/schemas/LabItemContent" + AssessmentItem: + type: object + description: >- + Item instance served to the candidate. The variant is fixed when it is + first served: a reload, a retried request, or a resumed session returns + the same instance with the same text and option order. The item never + says whether an earlier answer was correct, and seed items, which are + not scored, are indistinguishable from scored ones. + additionalProperties: false + required: + - id + - sequence + - prompt + - content + properties: + id: + $ref: "#/schemas/AssessmentItemId" + sequence: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: Position of the item in the attempt, from 1. + prompt: + type: string + minLength: 1 + maxLength: 20000 + description: >- + Statement in Russian. Plain text with line breaks; the client shows + it as text, never as HTML. + content: + $ref: "#/schemas/ItemContent" + AssessmentProgress: + type: object + description: >- + Progress of the item part. It counts seed items like scored ones, so it + does not reveal which items are scored. An adaptive attempt may end its + item part before `max_items` by its stop rule. A finalize refused as + premature does not list the unfinished parts; the client reads them + here, in `current_item`, and in `practices`. + additionalProperties: false + required: + - answered_items + - max_items + properties: + answered_items: + type: integer + format: int32 + minimum: 0 + maximum: 100 + max_items: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: >- + Item limit of the attempt: the form size in demo_basic, or the + policy limit of scored and seed items together in adaptive. + PracticeKind: + type: string + description: |- + Role of a practice in the attempt. + + - main: the practice that every attempt with practice requires before a decision. + - additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt. + + Adding a value is a contract change. + enum: + - main + - additional + PracticeStatus: + type: string + description: |- + State of a practice. + + - not_started: no solution was submitted yet. + - pending: the submitted solution is queued or running in the sandbox. + - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed. + - failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate's and consumes nothing; the practice can be submitted again. + enum: + - not_started + - pending + - finished + - failed + PracticeFailureReason: + type: string + description: >- + Why the sandbox infrastructure returned no verdict: `sandbox_busy` + when its queue was full, `sandbox_error` for an infrastructure failure + such as a broken executor. Neither depends on the solution; a + solution that fails to compile, crashes, or exceeds a limit gets a + `finished` verdict instead, so a failure never acts as an oracle for + hidden checks. + enum: + - sandbox_busy + - sandbox_error + PracticeGroupResult: + type: object + description: Outcome of one hidden check group. It never contains the checks themselves. + additionalProperties: false + required: + - group + - passed + properties: + group: + type: integer + format: int32 + minimum: 1 + maximum: 3 + passed: + type: boolean + PracticeVerdict: + type: object + description: >- + Verdict of a practice solution on the hidden checks: the score 0-3, + one point for each passed group. The hidden checks, their inputs and + outputs, error output, and seeds are never returned. + additionalProperties: false + required: + - score + - max_score + - groups + properties: + score: + type: integer + format: int32 + minimum: 0 + maximum: 3 + max_score: + type: integer + format: int32 + minimum: 3 + maximum: 3 + groups: + type: array + minItems: 3 + maxItems: 3 + items: + $ref: "#/schemas/PracticeGroupResult" + AssessmentPractice: + type: object + description: >- + Practice of the attempt. Its verdict is shown only after the + submission; the solution time is kept as a separate label and never + enters the ability estimate or the grade decision. + additionalProperties: false + required: + - kind + - item_id + - status + - submitted_at + - verdict + - failure_reason + properties: + kind: + $ref: "#/schemas/PracticeKind" + item_id: + $ref: "#/schemas/AssessmentItemId" + status: + $ref: "#/schemas/PracticeStatus" + submitted_at: + description: Time of the latest submission, or null before the first one. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + verdict: + description: The verdict when `status` is `finished`, otherwise null. + oneOf: + - $ref: "#/schemas/PracticeVerdict" + - type: "null" + failure_reason: + description: The reason when `status` is `failed`, otherwise null. + oneOf: + - $ref: "#/schemas/PracticeFailureReason" + - type: "null" + AssessmentAttempt: + description: >- + Candidate view of a real assessment, a corrective real assessment, or + a demo_express training run. The variants keep training output separate + from qualification attempts. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedAttempt" + - $ref: "#/schemas/AssessmentCorrectiveAttempt" + - $ref: "#/schemas/AssessmentExpressAttempt" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedAttempt" + corrective: "#/schemas/AssessmentCorrectiveAttempt" + demo_express: "#/schemas/AssessmentExpressAttempt" + AssessmentAttemptCommon: + type: object + description: >- + Common state of an assessment attempt. Real assessments have a + specialization and target grade; demo_express has neither. The + attempt shows its fixed versions, server deadlines, session limit, + progress, current item, and practices. It never contains answer keys, + answer correctness, item scores, family or variant identifiers, + seeds, hidden checks, or anti-cheat signals. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - kind + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: "#/schemas/AssessmentAttemptVersion" + specialization: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + - type: "null" + target_grade: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + task_language: + description: Task language of the attempt, or null when none is selected. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + kind: + $ref: "#/schemas/AssessmentAttemptKind" + root_attempt_id: + description: >- + Present only for a corrective real assessment. It identifies the + root attempt whose quota and chain deadline this attempt shares. + oneOf: + - type: string + format: uuid + - type: "null" + readOnly: true + chain_deadline: + description: >- + Present only for a corrective real assessment. It is the immutable + deadline derived from the root attempt and is not extended by a + lower target grade. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + readOnly: true + mode: + $ref: "#/schemas/AssessmentMode" + state: + $ref: "#/schemas/AssessmentAttemptState" + versions: + $ref: "#/schemas/AssessmentVersions" + started_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + expires_at: + description: >- + Server deadline. For demo_express it is 180 to 300 seconds after + started_at; for a corrective assessment it does not exceed + chain_deadline. + $ref: "./common_schemas.yml#/schemas/Timestamp" + sessions: + description: Session limit of the attempt, or null when its policy defines none. + oneOf: + - $ref: "#/schemas/AssessmentSessions" + - type: "null" + finished_at: + description: Time the attempt reached a terminal state, or null while it is active. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + progress: + $ref: "#/schemas/AssessmentProgress" + current_item: + description: >- + Item to answer now: a test item in `in_progress`, the practice item + to submit in `practice_pending` or `additional_practice_pending` + while that practice is `not_started` or `failed`, and null + otherwise. + oneOf: + - $ref: "#/schemas/AssessmentItem" + - type: "null" + practices: + type: array + maxItems: 5 + description: >- + Practices in the order assigned by the mode policy. The list + exposes verdicts only after submission. + items: + $ref: "#/schemas/AssessmentPractice" + watermark: + $ref: "#/schemas/AssessmentWatermark" + AssessmentWorkSession: + type: object + description: >- + The work session of a real attempt that the calling page holds. It is a + one-page-at-a-time rule for the attempt, not a score or a signal, and it + changes no result. + additionalProperties: false + required: + - held_until + - renew_after_seconds + properties: + held_until: + $ref: "./common_schemas.yml#/schemas/Timestamp" + renew_after_seconds: + type: integer + format: int32 + minimum: 1 + maximum: 3600 + description: >- + How often the page repeats the hold. It is well below the hold time, + so a page whose timer is slowed down in the background still renews + before its hold expires. + AssessmentWatermark: + type: object + description: >- + Visible mark of a real attempt. The client shows `code` with the current + time as a faint tile over the task screen, so that a screenshot or a photo + of the screen can be traced back to the attempt by an operator. The code + is a keyed pseudonym derived on the server: it carries no name, contact, + or identifier of the account, and it cannot be computed without the server + secret. The task text of such an attempt also carries an invisible mark + and interchangeable wordings chosen by the same secret; they change + neither the meaning of a task nor its reference answer, and the client + keeps the invisible characters out of the accessibility tree. Training + runs (`demo_express`) carry no watermark. It is evidence for a manual + review and an appeal, never an automatic decision. + additionalProperties: false + required: + - code + properties: + code: + type: string + minLength: 10 + maxLength: 11 + pattern: "^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$" + description: Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`. + AssessmentQualifiedAttempt: + allOf: + - $ref: "#/schemas/AssessmentAttemptCommon" + - type: object + properties: + kind: + type: string + enum: + - root + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + root_attempt_id: + type: "null" + description: Root attempts have no parent attempt. + chain_deadline: + type: "null" + description: A root attempt has no correction-chain deadline. + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentCorrectiveAttempt: + allOf: + - $ref: "#/schemas/AssessmentAttemptCommon" + - type: object + properties: + kind: + type: string + enum: + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: "./common_schemas.yml#/schemas/Timestamp" + readOnly: true + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentExpressAttempt: + allOf: + - $ref: "#/schemas/AssessmentAttemptCommon" + - type: object + properties: + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + specialization: + type: "null" + target_grade: + type: "null" + task_language: + type: "null" + root_attempt_id: + type: "null" + chain_deadline: + type: "null" + required: + - kind + - mode + - specialization + - target_grade + - task_language + - root_attempt_id + - chain_deadline + ChoiceAnswer: + type: object + description: >- + Selected options of a choice item: exactly one unless the item allows + several. Two answers are equal when they select the same set of + options, in any order. + additionalProperties: false + required: + - format + - option_ids + properties: + format: + type: string + enum: + - choice + option_ids: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + $ref: "#/schemas/AssessmentOptionId" + NumberAnswer: + type: object + description: >- + Numeric answer in the unit of the item. Two answers are equal when + their decoded values are numerically equal, so 254 and 254.0 are the + same answer. + additionalProperties: false + required: + - format + - number + properties: + format: + type: string + enum: + - number + number: + type: number + format: double + x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber + StringAnswer: + type: object + description: >- + String answer, at most the `max_length` of the item. Two answers are + equal only when their texts are identical; no trimming, case folding, + or Unicode normalization applies to that comparison. + additionalProperties: false + required: + - format + - text + properties: + format: + type: string + enum: + - string + text: + type: string + minLength: 1 + maxLength: 500 + OrderAnswer: + type: object + description: >- + Every element of the item exactly once, in the chosen order. Two + answers are equal only when the sequences are identical. + additionalProperties: false + required: + - format + - element_ids + properties: + format: + type: string + enum: + - order + element_ids: + type: array + minItems: 2 + maxItems: 20 + uniqueItems: true + items: + $ref: "#/schemas/AssessmentOptionId" + FindErrorAnswer: + type: object + description: >- + Selected line numbers, at most the `max_selections` of the item. Two + answers are equal when they select the same set of lines, in any + order. + additionalProperties: false + required: + - format + - line_numbers + properties: + format: + type: string + enum: + - find_error + line_numbers: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + type: integer + format: int32 + minimum: 1 + maximum: 500 + ConfigurationAnswer: + type: object + description: >- + Submitted configuration text, at most the `max_length` of the item. + Two answers are equal only when their texts are identical, including + whitespace and line breaks. + additionalProperties: false + required: + - format + - config + properties: + format: + type: string + enum: + - configuration + config: + type: string + minLength: 1 + maxLength: 20000 + PracticeAnswer: + type: object + description: >- + Practice solution. It runs in the isolated sandbox without network + access, secrets, or business data. Two submissions are equal only when + the language is the same and the source texts are identical. The + source is never echoed in a response or a problem. + additionalProperties: false + required: + - format + - language + - source_code + properties: + format: + type: string + enum: + - practice + language: + description: >- + One of the `languages` of the practice item, or null when the item + offers none. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + source_code: + type: string + minLength: 1 + maxLength: 65536 + AssessmentAnswer: + description: >- + Candidate answer, selected by `format`, which must equal the format of + the answered item. It carries only the answer: no score, duration, + correctness flag, or seed. The server records the times itself and + scores the answer with the key of the fixed item instance. Each format + defines when two answers are equal, which decides whether a repeated + submission is the same answer. + oneOf: + - $ref: "#/schemas/ChoiceAnswer" + - $ref: "#/schemas/NumberAnswer" + - $ref: "#/schemas/StringAnswer" + - $ref: "#/schemas/OrderAnswer" + - $ref: "#/schemas/FindErrorAnswer" + - $ref: "#/schemas/ConfigurationAnswer" + - $ref: "#/schemas/PracticeAnswer" + AssessmentAnswerSubmission: + type: object + description: >- + Answer to one item of the attempt. Unknown fields are rejected, so a + request cannot send a score, a duration, or a correctness flag. + additionalProperties: false + required: + - expected_version + - item_id + - answer + properties: + expected_version: + $ref: "#/schemas/AssessmentAttemptVersion" + item_id: + $ref: "#/schemas/AssessmentItemId" + answer: + $ref: "#/schemas/AssessmentAnswer" + AssessmentFinalization: + type: object + description: Command to finalize the attempt. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/AssessmentAttemptVersion" + AssessmentOutcome: + type: string + description: |- + Grade decision of the attempt. + + - confirmed: the target grade is confirmed by the rule of the recorded policy version. + - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force. + - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force. + + A failed, expired, or flagged attempt never lowers a confirmed grade. + enum: + - confirmed + - not_confirmed + - not_determined + AssessmentNotDeterminedReason: + type: string + description: |- + Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot. + + - expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot. + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain. + enum: + - expired + - practice_incomplete + - insufficient_bank + - sandbox_unavailable + AssessmentStrength: + type: string + description: >- + Strength of an adaptive confirmation: `high` or `medium`, by the + probability bands of the recorded policy version. + enum: + - high + - medium + CalibrationStatus: + type: string + description: >- + Whether the thresholds of the recorded policy version are empirically + calibrated. `uncalibrated` results are provisional: their thresholds + come from expert judgement, and their probabilities are not claimed to + be calibrated. + enum: + - uncalibrated + - calibrated + AssessmentLimitation: + type: string + description: |- + Known limitation of the method behind a real-assessment result, shown with the result. + + - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. + - demo_bank: the result comes from the small reviewed demo bank. + - practice_not_included: the attempt had no code practice because the sandbox was not enabled. + - unproctored: the attempt was taken online without supervision. + Adding a value is a contract change. + enum: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored + AssessmentInterval: + type: object + description: Interval on the ability scale. + additionalProperties: false + required: + - low + - high + properties: + low: + type: number + format: double + high: + type: number + format: double + AssessmentUncertainty: + type: object + description: >- + Ability estimate of an adaptive attempt and its uncertainty: the EAP + estimate on the specialization scale, its standard error, the 95% + interval, and the probability of reaching the target grade threshold. + The interval is reported but is not a separate stop condition. + additionalProperties: false + required: + - theta + - standard_error + - interval_95 + - p_grade + properties: + theta: + type: number + format: double + standard_error: + type: number + format: double + minimum: 0 + interval_95: + $ref: "#/schemas/AssessmentInterval" + p_grade: + type: number + format: double + minimum: 0 + maximum: 1 + description: Probability of reaching the threshold of the target grade. + BasicScore: + type: object + description: >- + Raw score of a demo_basic attempt and the pass mark of the recorded + basic grading policy. The pass mark comes from that policy version and + never from the handler. + additionalProperties: false + required: + - points + - max_points + - pass_points + properties: + points: + type: integer + format: int32 + minimum: 0 + max_points: + type: integer + format: int32 + minimum: 1 + pass_points: + type: integer + format: int32 + minimum: 1 + AssessmentGap: + type: object + description: Domain of the specialization where the evidence was weak. + additionalProperties: false + required: + - domain + - title + properties: + domain: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z0-9_]+$" + description: Stable domain code of the bank blueprint. + title: + type: string + minLength: 1 + maxLength: 200 + description: Display name in Russian. Plain text. + AssessmentDurations: + type: object + description: >- + Working time recorded by the server. It is a separate label: it never + enters the ability estimate or the grade decision. + additionalProperties: false + required: + - items_seconds + - practice_seconds + properties: + items_seconds: + type: integer + format: int32 + minimum: 0 + practice_seconds: + type: + - integer + - "null" + format: int32 + minimum: 0 + description: >- + Time on all practices with a verdict, or null when no practice has + one. + AssessmentPracticeResult: + type: object + description: Verdict of one practice of the attempt. + additionalProperties: false + required: + - kind + - verdict + properties: + kind: + $ref: "#/schemas/PracticeKind" + verdict: + $ref: "#/schemas/PracticeVerdict" + AssessmentNextAction: + type: string + description: |- + Step that the candidate may take next. + + - retake_same_grade: test the same grade again from `available_at`. + - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval. + - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned). + - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy. + enum: + - retake_same_grade + - take_lower_grade + - accept_lower_grade + - take_higher_grade + AssessmentNextStep: + type: object + description: Step that the server allows after this result, computed when it was decided. + additionalProperties: false + required: + - action + - grade + - available_at + properties: + action: + $ref: "#/schemas/AssessmentNextAction" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + available_at: + description: First time the step is allowed, or null when it is allowed now. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + AssessmentResult: + description: >- + Immutable result of a terminal assessment attempt. The result shape + distinguishes real grade decisions from demo_express training output. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedResult" + - $ref: "#/schemas/AssessmentCorrectiveResult" + - $ref: "#/schemas/AssessmentExpressResult" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedResult" + corrective: "#/schemas/AssessmentCorrectiveResult" + demo_express: "#/schemas/AssessmentExpressResult" + AssessmentRealResult: + description: >- + A completed root or corrective result. Training-only demo_express + results are excluded from qualification history. + oneOf: + - $ref: "#/schemas/AssessmentQualifiedResult" + - $ref: "#/schemas/AssessmentCorrectiveResult" + discriminator: + propertyName: kind + mapping: + root: "#/schemas/AssessmentQualifiedResult" + corrective: "#/schemas/AssessmentCorrectiveResult" + AssessmentCategoryDecisionView: + type: object + description: >- + Category decision captured when this result was stored. It is absent + from legacy v1 results because their current grade cannot be inferred + later. It never exposes review identifiers, private answers, or the + candidate's current category after this decision. + additionalProperties: false + required: + - status + - previous_confirmed_grade + - current_confirmed_grade + - method + - source + - calibration_status + properties: + status: + type: string + enum: + - not_eligible + - not_confirmed + - assigned + - unchanged + previous_confirmed_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + current_confirmed_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + method: + oneOf: + - type: string + enum: + - demo_basic_pass_mark + - type: "null" + source: + oneOf: + - type: string + enum: + - synthetic_demo + - type: "null" + calibration_status: + oneOf: + - $ref: "#/schemas/CalibrationStatus" + - type: "null" + AssessmentResultHistoryPage: + type: object + description: >- + Owner-only immutable root and corrective results ordered by decided_at + and attempt_id descending. Legacy v1 results omit category_decision. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 50 + items: + $ref: "#/schemas/AssessmentRealResult" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + AssessmentFinalizeConflictProblem: + type: object + description: >- + A finalize state conflict. `pending_item_ids` is present only when the + attempt still has required questions without answers; it is omitted for + other state conflicts and idempotency conflicts. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + title: + type: string + minLength: 1 + maxLength: 200 + status: + type: integer + format: int32 + const: 409 + code: + type: string + enum: + - state_conflict + - idempotency_in_progress + detail: + type: string + maxLength: 1000 + instance: + type: string + format: uri-reference + maxLength: 2048 + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + errors: + type: array + maxItems: 100 + items: + $ref: "./problem_schemas.yml#/schemas/ProblemFieldError" + pending_item_ids: + type: array + maxItems: 220 + uniqueItems: true + items: + type: string + format: uuid + description: >- + Frozen item IDs still unanswered when finalize is rejected for an + incomplete attempt. Omitted when the conflict is unrelated to + unanswered items. + AssessmentRealResultCommon: + type: object + description: >- + Immutable result of a real assessment, visible only to its candidate. + It records the method, versions, decision, uncertainty, and + limitations. A corrective result also carries root_attempt_id and + chain_deadline from the same chain. Later policy, bank, or algorithm + versions never change it. It never contains answers, per-item + correctness, keys, seeds, hidden checks, or anti-cheat signals. + Fields the method does not compute are null, never zero. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + target_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + root_attempt_id: + description: >- + Root attempt of a corrective check, or null when this is not a + corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: "null" + readOnly: true + chain_deadline: + description: >- + Immutable deadline shared by a corrective chain, or null when + this result is not from a corrective check. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + readOnly: true + task_language: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + kind: + type: string + enum: + - root + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + versions: + $ref: "#/schemas/AssessmentVersions" + outcome: + $ref: "#/schemas/AssessmentOutcome" + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: "#/schemas/AssessmentNotDeterminedReason" + - type: "null" + confirmed_grade: + description: >- + Grade that this attempt confirmed, the target grade, or null when + it confirmed none. Together with the specialization it forms the + category. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + previous_confirmed_grade: + description: >- + Confirmed grade of the specialization before this attempt, or null. + When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + category_decision: + $ref: "#/schemas/AssessmentCategoryDecisionView" + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: "#/schemas/AssessmentStrength" + - type: "null" + calibration_status: + $ref: "#/schemas/CalibrationStatus" + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: "#/schemas/AssessmentLimitation" + uncertainty: + description: >- + Ability estimate and uncertainty of an adaptive attempt with a + decision; null for demo_basic, which computes none, and for an + attempt without a decision. + oneOf: + - $ref: "#/schemas/AssessmentUncertainty" + - type: "null" + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: "#/schemas/BasicScore" + - type: "null" + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: "#/schemas/AssessmentPracticeResult" + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: "#/schemas/AssessmentGap" + durations: + $ref: "#/schemas/AssessmentDurations" + next_steps: + type: array + maxItems: 5 + items: + $ref: "#/schemas/AssessmentNextStep" + decided_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + AssessmentQualifiedResult: + description: >- + Result of a real assessment that is not a corrective attempt. The + correction-chain fields are explicitly null. + allOf: + - $ref: "#/schemas/AssessmentRealResultCommon" + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: "null" + chain_deadline: + type: "null" + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentCorrectiveResult: + description: >- + Result of a corrective real assessment. Both chain fields are present + and identify the same immutable correction chain. + allOf: + - $ref: "#/schemas/AssessmentRealResultCommon" + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: "./common_schemas.yml#/schemas/Timestamp" + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentExpressResult: + type: object + description: >- + Immutable educational result of a demo_express run. It includes a + short summary but cannot report a category, percentile, uncertainty, + grade, strength, or qualification evidence. The result belongs only + to the training mode and does not consume a real-assessment quota. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - summary + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + type: "null" + description: Express training does not assess a specialization. + target_grade: + type: "null" + description: Express training does not assess a target grade. + task_language: + type: "null" + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + versions: + $ref: "#/schemas/AssessmentVersions" + outcome: + type: string + enum: + - demonstration + not_determined_reason: + type: "null" + confirmed_grade: + type: "null" + description: Express training never confirms a grade. + previous_confirmed_grade: + type: "null" + strength: + type: "null" + calibration_status: + type: string + enum: + - uncalibrated + limitations: + type: array + minItems: 1 + maxItems: 1 + items: + type: string + enum: + - demonstration_only + uncertainty: + type: "null" + description: Express training computes no ability estimate or percentile. + basic_score: + type: "null" + practices: + type: array + maxItems: 0 + items: + $ref: "#/schemas/AssessmentPracticeResult" + gaps: + type: array + maxItems: 0 + items: + $ref: "#/schemas/AssessmentGap" + durations: + $ref: "#/schemas/AssessmentDurations" + next_steps: + type: array + maxItems: 0 + items: + $ref: "#/schemas/AssessmentNextStep" + summary: + type: string + minLength: 1 + maxLength: 2000 + description: Short educational feedback about this training run. + decided_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + AssessmentGradeAvailabilityStatus: + type: string + description: |- + Whether an attempt for the grade can start now. + + - available: CreateMyAssessmentAttempt can start it. + - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. + - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it. + - insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families. + enum: + - available + - active_attempt + - cooldown + - insufficient_bank + AssessmentGradeAvailability: + type: object + description: >- + Availability of an attempt for one grade of a specialization, with the + limits that an attempt would have, so the client can show them before + the start. The limit fields are null when the status is + `insufficient_bank` or the policy defines no such limit. + additionalProperties: false + required: + - grade + - status + - mode + - available_at + - time_limit_seconds + - max_sessions + - max_items + - practice_required + properties: + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + status: + $ref: "#/schemas/AssessmentGradeAvailabilityStatus" + mode: + description: >- + Real-assessment mode that the server would use, or null when the + status is `insufficient_bank`. `demo_express` is not a category + assessment and is never returned here. + oneOf: + - $ref: "#/schemas/AssessmentRealMode" + - type: "null" + available_at: + description: When the status is `cooldown`, the first time the attempt can start; otherwise null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + time_limit_seconds: + type: + - integer + - "null" + format: int32 + minimum: 1 + description: Time from the start to `expires_at`. + max_sessions: + type: + - integer + - "null" + format: int32 + minimum: 1 + maximum: 10 + description: Session limit within the time limit. + max_items: + type: + - integer + - "null" + format: int32 + minimum: 1 + maximum: 100 + description: Item limit, as in `AssessmentProgress.max_items`. + practice_required: + type: + - boolean + - "null" + description: Whether the attempt would include a main code practice. + AssessmentSpecializationAvailability: + type: object + description: >- + Assessment state of one questionnaire specialization. Specializations + are assessed independently, with independent retry intervals. + additionalProperties: false + required: + - specialization + - confirmed_grade + - confirmed_basis + - active_attempt_id + - grades + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmed_grade: + description: Currently confirmed grade of the specialization, or null. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + confirmed_basis: + description: >- + What the confirmed grade rests on, or null exactly when + `confirmed_grade` is null. `synthetic_demo` marks a demonstration + category, which is not a validated measurement and must not be shown + as a real confirmation. + oneOf: + - $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" + - type: "null" + active_attempt_id: + type: + - string + - "null" + format: uuid + description: Identifier of the active attempt of the specialization, or null. + grades: + type: array + maxItems: 10 + description: Every grade of the scale in ascending order. + items: + $ref: "#/schemas/AssessmentGradeAvailability" + AssessmentAvailability: + type: object + description: >- + Assessment availability for the specializations of the current + candidate's questionnaire, derived at the time of the request. + additionalProperties: false + required: + - specializations + properties: + specializations: + type: array + maxItems: 2 + description: Questionnaire specializations in questionnaire order. + items: + $ref: "#/schemas/AssessmentSpecializationAvailability" diff --git a/api/core/components/schemas/assessment_signal_schemas.yml b/api/core/components/schemas/assessment_signal_schemas.yml new file mode 100644 index 0000000..a9ab9a0 --- /dev/null +++ b/api/core/components/schemas/assessment_signal_schemas.yml @@ -0,0 +1,208 @@ +schemas: + AssessmentSignalEvent: + description: >- + One client-reported event bound to an item instance of the attempt. The + timestamp is untrusted input and is used only as event metadata; server + receipt time is authoritative for limits and retention. + oneOf: + - $ref: "#/schemas/AssessmentFocusLossSignal" + - $ref: "#/schemas/AssessmentClipboardSignal" + - $ref: "#/schemas/AssessmentFullscreenExitSignal" + - $ref: "#/schemas/AssessmentCaptureSignal" + discriminator: + propertyName: kind + mapping: + focus_loss: "#/schemas/AssessmentFocusLossSignal" + copy: "#/schemas/AssessmentClipboardSignal" + paste: "#/schemas/AssessmentClipboardSignal" + cut: "#/schemas/AssessmentClipboardSignal" + fullscreen_exit: "#/schemas/AssessmentFullscreenExitSignal" + screenshot_key: "#/schemas/AssessmentCaptureSignal" + devtools_open: "#/schemas/AssessmentCaptureSignal" + AssessmentFocusLossSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - duration_ms + properties: + kind: + type: string + enum: + - focus_loss + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + duration_ms: + type: integer + format: int32 + minimum: 1 + maximum: 259200000 + description: Client-measured duration away from the assessment tab or window, in milliseconds. + AssessmentClipboardSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - size_bytes + properties: + kind: + type: string + enum: + - copy + - paste + - cut + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + size_bytes: + type: integer + format: int32 + minimum: 0 + maximum: 2147483647 + description: >- + Size only; clipboard and selection contents are never transmitted or + retained. For `paste` it is the UTF-8 byte count of the pasted plain + text plus the byte size of pasted files, counted on the device from + the paste event. For `copy` and `cut` it is the selection length in + UTF-16 code units taken from the selection offsets of a form field, + or zero when the field offsets are unavailable; it is an approximate + size and the selected text is not read. The server applies no + conversion and treats the value as an order-of-magnitude indicator. + AssessmentFullscreenExitSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - fullscreen_exit + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + AssessmentCaptureSignal: + type: object + description: >- + A hint that the screen may be captured or inspected. `screenshot_key` + is a key or key combination that the browser saw and that usually takes + a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); + `devtools_open` is the result of a heuristic that guesses that the + developer tools are open (a docked panel changes the window size, or the + console reads an object). Both are weak: a browser does not see every + screenshot, an operating system can take one without a key the page + sees, a phone photo is invisible to the page, and the heuristic gives + false positives. They lead to attention in a manual review at most, + never to a score change, and they carry no measurement. + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - screenshot_key + - devtools_open + item_instance_id: + $ref: "#/schemas/AssessmentItemId" + occurred_at: + $ref: "#/schemas/Timestamp" + AssessmentSignalBatch: + type: object + description: >- + A bounded batch of client event metadata. The raw request body is limited + to 32 KiB before decoding and the batch contains at most 50 events. + additionalProperties: false + required: + - events + properties: + events: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: "#/schemas/AssessmentSignalEvent" + AssessmentSignalReceipt: + type: object + description: >- + Receipt for the submitted batch. It contains no signal details, score, + review decision, threshold, or result band. + additionalProperties: false + required: + - status + - accepted_events + - received_at + properties: + status: + type: string + enum: + - accepted + - saturated + description: >- + `saturated` means no event from this batch was stored because the + attempt's bounded evidence storage is full. + accepted_events: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of events stored from this batch; zero when saturated. + received_at: + $ref: "#/schemas/Timestamp" + AssessmentSignalNoticeVersion: + type: integer + format: int32 + minimum: 1 + maximum: 2147483647 + description: >- + Version of the notice text about the collected signals. The client + shows the text of the version it knows and sends that version back when + the candidate confirms; a changed text gets a new version and needs a + new confirmation. + AssessmentSignalNotice: + type: object + description: >- + State of the notice about the signals that are collected during a real + assessment attempt. The acknowledgement is a record that the candidate + was informed. It is not a consent, grants no purpose, and neither + enables nor blocks signal storage; C3 remains the only consent that + the signal operation checks. + additionalProperties: false + required: + - notice_version + - acknowledged + - acknowledged_at + properties: + notice_version: + allOf: + - $ref: "#/schemas/AssessmentSignalNoticeVersion" + description: The version the server currently requires the candidate to acknowledge. + acknowledged: + type: boolean + description: True when the candidate acknowledged `notice_version`. + acknowledged_at: + description: Server time of the first acknowledgement of this version, or null. + oneOf: + - $ref: "#/schemas/Timestamp" + - type: "null" + AssessmentSignalNoticeAcknowledgement: + type: object + description: The notice version the candidate was shown and acknowledged. + additionalProperties: false + required: + - notice_version + properties: + notice_version: + $ref: "#/schemas/AssessmentSignalNoticeVersion" diff --git a/api/core/components/schemas/candidate_schemas.yml b/api/core/components/schemas/candidate_schemas.yml new file mode 100644 index 0000000..9e837f3 --- /dev/null +++ b/api/core/components/schemas/candidate_schemas.yml @@ -0,0 +1,1212 @@ +schemas: + ProfileVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the candidate profile. A candidate who has not saved the + profile has version 0; every save that changes the profile advances it + by one. The client sends the version it read as `expected_version`. + examples: + - 4 + ProfileItemStatus: + type: string + description: |- + Confirmation state of a profile list item, and the decision that a request sends for a field or an item. + + - confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure. + - extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses. + + A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list. + enum: + - confirmed + - extracted + ProfileClaimStatus: + type: string + description: |- + Confirmation state of a single profile field. + + - confirmed: the candidate typed the value or confirmed a suggestion. + - extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0. + - unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer. + enum: + - confirmed + - extracted + - unknown + ProfileClaimOrigin: + type: string + description: |- + Where the value of a profile field or item came from. The server sets it; a request never sends it. + + - manual: the candidate typed the value in the form. `quote` and `extraction_version` are null. + - extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume. + - imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link. + + Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change. + enum: + - manual + - extracted_from_resume + - imported + ProfileClaimTrustLevel: + type: integer + format: int32 + minimum: 0 + maximum: 0 + description: >- + Trust level of a profile claim. Every claim of the profile has trust + level 0, whatever its origin: a manual value, an imported value, and + a value that the candidate confirmed are all unverified statements. + Confirming a suggestion changes its status, never its trust level. + Higher levels belong to evidence, such as an assessment result or a + confirmation by a third party, which are separate resources and never + write a level into a profile claim. + examples: + - 0 + ProfileClaimQuote: + type: string + minLength: 1 + maxLength: 300 + description: >- + Exact excerpt of the imported document that the value was extracted + from, so the candidate can check it. It may contain personal data of + the candidate. It may contain line breaks. Plain text; clients show it + as text, never as HTML. + ProfileClaimSource: + type: object + description: >- + Provenance and confirmation of one profile value: its origin, the + trust level, the excerpt it was extracted from, the extractor version, + and the time the candidate confirmed it. Read-only; the server derives + it and a request cannot set it. The imported document or source itself + is not referenced: the profile never requires a file, the ML service, + or an FSP account, and a later link to them is an additive field. + additionalProperties: false + required: + - origin + - trust_level + - quote + - extraction_version + - confirmed_at + properties: + origin: + $ref: "#/schemas/ProfileClaimOrigin" + trust_level: + $ref: "#/schemas/ProfileClaimTrustLevel" + quote: + description: >- + Excerpt of the imported document that supports the value, or null + for a manual value and for an extracted value that the extractor + did not tie to one excerpt. + oneOf: + - $ref: "#/schemas/ProfileClaimQuote" + - type: "null" + extraction_version: + description: >- + Extractor version for an extracted or imported value, or null for + a manual value. + oneOf: + - $ref: "./need_schemas.yml#/schemas/NeedVersionLabel" + - type: "null" + confirmed_at: + description: >- + Time the candidate typed or confirmed the value, or null while the + value is an unconfirmed suggestion. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + ProfileLocationName: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + City or region where the candidate lives or wants to work, as free + text. It is personal data of the candidate and never a street + address. It has no leading or trailing whitespace and no line breaks. + Plain text; clients show it as text, never as HTML. + ProfileSalaryMinimum: + type: object + description: >- + The lowest salary that the candidate accepts, in whole rubles with its + base: the currency, the pay period, and the tax basis. It is private + to the candidate: no organization reads it, and the invitation only + shows a compatibility indicator that the server derives from it. It + is personal data. The amount is a positive multiple of 1000. + additionalProperties: false + required: + - amount + - currency + - period + - tax_basis + properties: + amount: + $ref: "./need_schemas.yml#/schemas/RubAmount" + currency: + $ref: "./need_schemas.yml#/schemas/CurrencyCode" + period: + $ref: "./need_schemas.yml#/schemas/SalaryPeriod" + tax_basis: + $ref: "./need_schemas.yml#/schemas/SalaryTaxBasis" + ProfileSoftSkill: + type: string + minLength: 1 + maxLength: 50 + pattern: '^\S(?:.*\S)?$' + description: >- + Soft skill as the candidate wrote it, for example "Mentoring" or + "Negotiation". The platform has no soft skill taxonomy, so the text is + free; it never changes a category or a grade. It has no leading or + trailing whitespace and no line breaks. The server compares skills + without regard to letter case. Plain text; clients show it as text, + never as HTML. + ProfileEmployerName: + type: string + minLength: 1 + maxLength: 200 + pattern: '^\S(?:.*\S)?$' + description: >- + Name of the employer in one experience entry, as the candidate wrote + it. It is personal data of the candidate's career. It has no leading + or trailing whitespace and no line breaks. Plain text; clients show + it as text, never as HTML. + ProfileExperienceSummary: + type: string + minLength: 1 + maxLength: 1000 + description: >- + Tasks and results of the candidate in one experience entry. It + describes the work rather than a job title. It may contain line + breaks and personal data of the candidate; it must not contain + personal data of other people. Plain text; clients show it as text, + never as HTML. + ProfileYearMonth: + type: string + minLength: 7 + maxLength: 7 + pattern: "^[0-9]{4}-(0[1-9]|1[0-2])$" + description: >- + Calendar month in the `YYYY-MM` format, for example 2024-03. An + experience period has month precision only, so the contract holds no + exact date of employment. The server rejects a month that lies in the + future. + examples: + - "2024-03" + ProfileFullNameClaim: + type: object + description: >- + Full name of the candidate with its confirmation state and provenance. + The value is personal data. It is disclosed to one organization only + through the contact grant of the consent C4 and never appears in an + organization-visible schema. `value` and `source` are null exactly + when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactFullName" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfileEmailClaim: + type: object + description: >- + Contact email of the candidate with its confirmation state and + provenance. It is personal data. It is a contact channel that the + candidate gives, not the login of the account: the two may differ, the + server never sends mail to it and never verifies it. `value` and + `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + oneOf: + - $ref: "./identity_schemas.yml#/schemas/EmailAddress" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfilePhoneClaim: + type: object + description: >- + Contact phone number of the candidate with its confirmation state and + provenance. It is personal data, stored in the E.164 format of the + contact disclosure. `value` and `source` are null exactly when + `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactPhoneNumber" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfileTelegramClaim: + type: object + description: >- + Telegram username of the candidate with its confirmation state and + provenance. It is personal data, stored with the leading @ of the + contact disclosure. `value` and `source` are null exactly when + `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactTelegramUsername" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfileLocationClaim: + type: object + description: >- + Place of the candidate with its confirmation state and provenance. It + is personal data. `value` and `source` are null exactly when `status` + is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + oneOf: + - $ref: "#/schemas/ProfileLocationName" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfileRelocationClaim: + type: object + description: >- + Whether the candidate is ready to relocate, with its confirmation + state and provenance. `value` and `source` are null exactly when + `status` is `unknown`; the server never assumes an answer. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + type: + - boolean + - "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfileSalaryMinimumClaim: + type: object + description: >- + Lowest acceptable salary with its confirmation state and provenance. + It is personal data that no organization reads. `value` and `source` + are null exactly when `status` is `unknown`; the server never + substitutes zero or a market estimate. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/ProfileClaimStatus" + value: + oneOf: + - $ref: "#/schemas/ProfileSalaryMinimum" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/ProfileClaimSource" + - type: "null" + ProfileContacts: + type: object + description: >- + Contact channels of the candidate. Each channel is a claim of its own, + and the candidate fills in any subset. The kinds are the ones that + the contact disclosure (consent C4) can pass on, with the same value + formats, so a disclosure never has to convert or drop a stored value; + adding a kind, such as a link to a code repository, is a contract + change in both places. Contacts leave the profile only through a + contact grant, never in a card or a search result. All values are + personal data. + additionalProperties: false + required: + - email + - phone + - telegram + properties: + email: + $ref: "#/schemas/ProfileEmailClaim" + phone: + $ref: "#/schemas/ProfilePhoneClaim" + telegram: + $ref: "#/schemas/ProfileTelegramClaim" + ProfileTerms: + type: object + description: >- + Conditions that the candidate wants: the place, readiness to relocate, + and the lowest salary. Acceptable work formats are not repeated here; + they are the `work_formats` of the questionnaire `WorkContext`, the + only place that holds them. These are the candidate's wishes, never + the terms of an invitation, which an organization offers and which + the invitation contract describes. + additionalProperties: false + required: + - location + - relocation + - salary_minimum + properties: + location: + $ref: "#/schemas/ProfileLocationClaim" + relocation: + $ref: "#/schemas/ProfileRelocationClaim" + salary_minimum: + $ref: "#/schemas/ProfileSalaryMinimumClaim" + ProfileStackItem: + type: object + description: >- + One technology tag of the candidate's stack with its confirmation state + and provenance. The profile stack is one list for the whole profile; + the questionnaire holds the tags of each chosen specialization with the + same `StackTag` meaning, and the two lists are independent: the server + never copies one into the other. A tag is a descriptive attribute and + never forms a category. + additionalProperties: false + required: + - tag + - status + - source + properties: + tag: + $ref: "./questionnaire_schemas.yml#/schemas/StackTag" + status: + $ref: "#/schemas/ProfileItemStatus" + source: + $ref: "#/schemas/ProfileClaimSource" + ProfileSoftSkillItem: + type: object + description: >- + One soft skill of the candidate with its confirmation state and + provenance. It is a claim; no assessment checks it. + additionalProperties: false + required: + - skill + - status + - source + properties: + skill: + $ref: "#/schemas/ProfileSoftSkill" + status: + $ref: "#/schemas/ProfileItemStatus" + source: + $ref: "#/schemas/ProfileClaimSource" + ProfileRoleItem: + type: object + description: >- + One role of the candidate: a specialization of the catalog with the + grade that the candidate claims for it. `self_assessed_grade` is a + claim, the same one that the questionnaire calls `self_assessed_grade` + for its at most two chosen specializations: it influences nothing but + the display and never becomes a confirmed grade or a category. The + questionnaire value starts the assessment and the profile value is what + the profile shows; the two are saved separately and the server never + copies one into the other. A confirmed grade comes only from an + assessment result and appears in `confirmed_categories` of the profile, + never in a role; unknown fields such as `confirmed_grade` or `category` + are rejected. + additionalProperties: false + required: + - specialization + - self_assessed_grade + - status + - source + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + self_assessed_grade: + description: >- + Grade that the candidate claims in the specialization, or null when + the candidate names none. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + status: + $ref: "#/schemas/ProfileItemStatus" + source: + $ref: "#/schemas/ProfileClaimSource" + ProfileExperienceItem: + type: object + description: >- + One entry of the candidate's work history with its confirmation state + and provenance. An entry describes the work by its specialization and + tasks rather than by a job title, and it is a claim of trust level 0. + It is different from the `CandidateExperience` of the questionnaire, + which holds only the total months of commercial and academic + experience of a chosen specialization as a hint for the assessment: + the two are saved separately, and the server neither adds the entries + up for the questionnaire nor fills the entries from it. An entry is + personal data. + additionalProperties: false + required: + - employer_name + - specialization + - started_on + - ended_on + - summary + - status + - source + properties: + employer_name: + description: Employer of the entry, or null when the candidate gives none. + oneOf: + - $ref: "#/schemas/ProfileEmployerName" + - type: "null" + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + started_on: + $ref: "#/schemas/ProfileYearMonth" + ended_on: + description: >- + Last month of the work, or null when the candidate still works + there. It is not earlier than `started_on`. + oneOf: + - $ref: "#/schemas/ProfileYearMonth" + - type: "null" + summary: + description: Tasks and results of the entry, or null when the candidate gives none. + oneOf: + - $ref: "#/schemas/ProfileExperienceSummary" + - type: "null" + status: + $ref: "#/schemas/ProfileItemStatus" + source: + $ref: "#/schemas/ProfileClaimSource" + ProfileProjectTitle: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Name of a project as the candidate wants an organization to read it. It + has no leading or trailing whitespace and no line breaks. When the + candidate publishes the `projects` card field, the title reaches the + anonymous card and match explanations, so it must not contain a name, + a contact, or a repository address. Plain text; clients show it as + text, never as HTML. + ProfileProjectDescription: + type: string + minLength: 1 + maxLength: 500 + description: >- + What the project does and what the candidate did in it. It may contain + line breaks. When the `projects` card field is published it reaches the + anonymous card. Plain text; clients show it as text, never as HTML. + ProfileRepositoryUrl: + type: string + minLength: 22 + maxLength: 160 + pattern: '^https://github\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$' + description: >- + Address of a public GitHub repository of the project in the form + https://github.com//. The server accepts only this + host and form, removes a trailing slash and a `.git` suffix, and stores + the canonical address. Organizations never receive the address before + an accepted invitation, because the owner name can identify the + candidate. + examples: + - https://github.com/example-org/payments-ledger + ProfileRepositoryCheckState: + type: string + description: |- + Result of the latest server check of a project repository on the public GitHub API. The server only reads public metadata; a check never proves that the candidate wrote the code. + + - pending: the check is scheduled and has not finished yet. + - verified: the repository exists and is public. Match explanations may then say that the project is backed by a public repository. + - not_found: GitHub reports no such public repository; it may be private, renamed to another owner, or deleted. + - unavailable: GitHub could not be asked, for example because of its rate limit; the server retries later. + enum: + - pending + - verified + - not_found + - unavailable + ProfileRepositoryCheck: + type: object + description: >- + State of the server check of a project repository. Read-only; no + request writes it. The fetched metadata itself (description, topics, + languages, and a plain-text README excerpt) is used only for ranking + and is never returned or shown. + additionalProperties: false + required: + - state + - checked_at + properties: + state: + $ref: "#/schemas/ProfileRepositoryCheckState" + checked_at: + description: Time of the last finished check, or null before the first one. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + ProfileProjectStack: + type: array + maxItems: 10 + description: >- + Technology tags of the project, each tag at most once without regard to + letter case. + items: + $ref: "./questionnaire_schemas.yml#/schemas/StackTag" + ProfileRepositoryCheckRequest: + type: object + description: Result of a request to check the linked repositories again. + additionalProperties: false + required: + - scheduled + properties: + scheduled: + type: integer + format: int32 + minimum: 0 + maximum: 10 + description: Number of repository checks that the request scheduled. + ProfileProjectItem: + type: object + description: >- + One project of the candidate with its confirmation state and provenance. + A project is a claim of trust level 0 that the candidate types; a + linked repository adds a separate server check (`repository_check`), + never a higher trust level. The project reaches organizations only when + the candidate publishes the `projects` card field, and then without the + repository address. + additionalProperties: false + required: + - title + - description + - stack + - repository_url + - repository_check + - status + - source + properties: + title: + $ref: "#/schemas/ProfileProjectTitle" + description: + description: What the project is about, or null when the candidate gives nothing. + oneOf: + - $ref: "#/schemas/ProfileProjectDescription" + - type: "null" + stack: + $ref: "#/schemas/ProfileProjectStack" + repository_url: + description: Canonical repository address, or null when the project links none. + oneOf: + - $ref: "#/schemas/ProfileRepositoryUrl" + - type: "null" + repository_check: + description: >- + The server check of the linked repository, or null when the project + links none. + oneOf: + - $ref: "#/schemas/ProfileRepositoryCheck" + - type: "null" + status: + $ref: "#/schemas/ProfileItemStatus" + source: + $ref: "#/schemas/ProfileClaimSource" + ProfileExperienceOverlapStatus: + type: string + description: Whether the candidate confirmed that two overlapping periods are genuine parallel work. + enum: + - needs_confirmation + - confirmed + ProfileExperienceOverlap: + type: object + description: >- + One pair of work history entries whose inclusive month ranges overlap. + The indices refer to the experience array in this profile version. + `confirmed` records an explicit acknowledgement for this pair of dates; + otherwise the pair needs confirmation before a changed profile can be saved. + additionalProperties: false + required: + - first_index + - second_index + - status + properties: + first_index: + type: integer + minimum: 0 + maximum: 19 + second_index: + type: integer + minimum: 1 + maximum: 19 + status: + $ref: "#/schemas/ProfileExperienceOverlapStatus" + ProfileExperiencePeriod: + type: object + description: The exact month range of an experience entry, copied into a confirmation. + additionalProperties: false + required: + - started_on + - ended_on + properties: + started_on: + $ref: "#/schemas/ProfileYearMonth" + ended_on: + description: Last month of work, or null when the period is open-ended. + oneOf: + - $ref: "#/schemas/ProfileYearMonth" + - type: "null" + ProfileParallelPeriodConfirmation: + type: object + description: >- + Explicit acknowledgement that the two indexed experience periods are + genuine parallel work. The indices and exact ranges must match the + submitted experience array; expected_version binds the acknowledgement + to the profile version the candidate read. + additionalProperties: false + required: + - first_index + - second_index + - first_period + - second_period + properties: + first_index: + type: integer + minimum: 0 + maximum: 19 + second_index: + type: integer + minimum: 1 + maximum: 19 + first_period: + $ref: "#/schemas/ProfileExperiencePeriod" + second_period: + $ref: "#/schemas/ProfileExperiencePeriod" + ProfileConfirmedCategory: + type: object + description: >- + A category that an assessment result confirmed: the specialization + with the confirmed grade. It is read-only and derived by the server + from the assessment results of the candidate; no request carries it + and the profile storage holds no such column, so neither a form nor an + import can write a confirmed grade. It is separate from the claims of + the profile and from the self-assessed grades in `roles`. `basis` says + what the grade rests on; `synthetic_demo` marks a demonstration category + that is not a validated measurement. + additionalProperties: false + required: + - specialization + - grade + - basis + - confirmed_at + - attempt_id + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + basis: + $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" + confirmed_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + attempt_id: + type: string + format: uuid + description: >- + Assessment attempt whose result confirmed the grade. The attempt + belongs to the candidate. + CandidateProfile: + type: object + description: >- + The private profile of the current candidate: full name and contacts, + stack, roles, work experience, soft skills, projects, and desired + terms, each value with its confirmation state and provenance. It is personal data + that only the candidate reads. It is never an organization-visible + schema: an organization sees a candidate only through the anonymous + card and, after an accepted invitation, through the contact grant, and + no organization schema refers to this one. + + Every value is a claim of trust level 0. The `self_assessed_grade` of a + role is what the candidate says; the `confirmed_categories` list is + what assessment results established, and the two are never mixed. A + candidate who has not saved the profile gets version 0, every single + field `unknown`, empty lists, and null `updated_at`. + + The profile is manual by nature and complete without a file: no field + requires a resume, the ML service, or an FSP account, and a candidate + with none of them has the same fields. Work formats live in the + questionnaire; a candidate's assessment starts from the questionnaire, + not from this profile. + additionalProperties: false + required: + - version + - full_name + - contacts + - stack + - roles + - experience + - experience_overlaps + - soft_skills + - projects + - terms + - confirmed_categories + - updated_at + properties: + version: + $ref: "#/schemas/ProfileVersion" + full_name: + $ref: "#/schemas/ProfileFullNameClaim" + contacts: + $ref: "#/schemas/ProfileContacts" + stack: + type: array + maxItems: 30 + description: >- + Technology tags in the order the candidate gave them, each tag at + most once without regard to letter case. + items: + $ref: "#/schemas/ProfileStackItem" + roles: + type: array + maxItems: 9 + description: >- + Roles in the order the candidate gave them, each specialization at + most once. + items: + $ref: "#/schemas/ProfileRoleItem" + experience: + type: array + maxItems: 20 + description: Work history entries in the order the candidate gave them. + items: + $ref: "#/schemas/ProfileExperienceItem" + experience_overlaps: + type: array + maxItems: 190 + description: >- + Every pair of overlapping experience periods, with its confirmation + status. The indices refer to this version's experience array. + items: + $ref: "#/schemas/ProfileExperienceOverlap" + soft_skills: + type: array + maxItems: 10 + description: >- + Soft skills in the order the candidate gave them, each skill at + most once without regard to letter case. + items: + $ref: "#/schemas/ProfileSoftSkillItem" + projects: + type: array + maxItems: 10 + description: >- + Projects in the order the candidate gave them, each repository + address at most once. + items: + $ref: "#/schemas/ProfileProjectItem" + terms: + $ref: "#/schemas/ProfileTerms" + confirmed_categories: + type: array + maxItems: 9 + description: >- + Categories that assessment results confirmed, at most one per + specialization, in catalog order. Read-only and empty until an + assessment confirms a grade. + items: + $ref: "#/schemas/ProfileConfirmedCategory" + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + ProfileFullNameInput: + type: object + description: >- + Decision about the full name in a request; see CandidateProfileUpdate + for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "./contact_grant_schemas.yml#/schemas/ContactFullName" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileEmailInput: + type: object + description: >- + Decision about the contact email in a request; see + CandidateProfileUpdate for the rules of `status`. The value is + personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "./identity_schemas.yml#/schemas/EmailAddress" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfilePhoneInput: + type: object + description: >- + Decision about the contact phone number in a request; see + CandidateProfileUpdate for the rules of `status`. The value is + personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "./contact_grant_schemas.yml#/schemas/ContactPhoneNumber" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileTelegramInput: + type: object + description: >- + Decision about the Telegram username in a request; see + CandidateProfileUpdate for the rules of `status`. The value is + personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "./contact_grant_schemas.yml#/schemas/ContactTelegramUsername" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileLocationInput: + type: object + description: >- + Decision about the place in a request; see CandidateProfileUpdate for + the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "#/schemas/ProfileLocationName" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileRelocationInput: + type: object + description: >- + Decision about readiness to relocate in a request; see + CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + type: boolean + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileSalaryMinimumInput: + type: object + description: >- + Decision about the lowest salary in a request; see + CandidateProfileUpdate for the rules of `status`. The value is + personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "#/schemas/ProfileSalaryMinimum" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileContactsInput: + type: object + description: >- + Decisions about the contact channels in a request. A channel sent as + null is unknown: it is removed if it was set. + additionalProperties: false + required: + - email + - phone + - telegram + properties: + email: + oneOf: + - $ref: "#/schemas/ProfileEmailInput" + - type: "null" + phone: + oneOf: + - $ref: "#/schemas/ProfilePhoneInput" + - type: "null" + telegram: + oneOf: + - $ref: "#/schemas/ProfileTelegramInput" + - type: "null" + ProfileTermsInput: + type: object + description: >- + Decisions about the desired terms in a request. A field sent as null + is unknown: it is removed if it was set. + additionalProperties: false + required: + - location + - relocation + - salary_minimum + properties: + location: + oneOf: + - $ref: "#/schemas/ProfileLocationInput" + - type: "null" + relocation: + oneOf: + - $ref: "#/schemas/ProfileRelocationInput" + - type: "null" + salary_minimum: + oneOf: + - $ref: "#/schemas/ProfileSalaryMinimumInput" + - type: "null" + ProfileStackItemInput: + type: object + description: >- + Decision about one stack tag in a request; see CandidateProfileUpdate + for the rules of `status`. + additionalProperties: false + required: + - tag + - status + properties: + tag: + $ref: "./questionnaire_schemas.yml#/schemas/StackTag" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileSoftSkillItemInput: + type: object + description: >- + Decision about one soft skill in a request; see + CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - skill + - status + properties: + skill: + $ref: "#/schemas/ProfileSoftSkill" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileRoleItemInput: + type: object + description: >- + Decision about one role in a request; see CandidateProfileUpdate for + the rules of `status`. The object has no confirmed grade and no + category: unknown fields are rejected. + additionalProperties: false + required: + - specialization + - self_assessed_grade + - status + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + self_assessed_grade: + description: Grade that the candidate claims, or null when the candidate names none. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileExperienceItemInput: + type: object + description: >- + Decision about one work history entry in a request; see + CandidateProfileUpdate for the rules of `status`. The server also + requires `ended_on` not to precede `started_on` and no month to lie in + the future, and answers 400 with the pointer of the month. + additionalProperties: false + required: + - employer_name + - specialization + - started_on + - ended_on + - summary + - status + properties: + employer_name: + oneOf: + - $ref: "#/schemas/ProfileEmployerName" + - type: "null" + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + started_on: + $ref: "#/schemas/ProfileYearMonth" + ended_on: + oneOf: + - $ref: "#/schemas/ProfileYearMonth" + - type: "null" + summary: + oneOf: + - $ref: "#/schemas/ProfileExperienceSummary" + - type: "null" + status: + $ref: "#/schemas/ProfileItemStatus" + ProfileProjectItemInput: + type: object + description: >- + Decision about one project in a request; see CandidateProfileUpdate for + the rules of `status`. The server answers 400 with the pointer of the + field for a repository address that is not a GitHub repository address, + a repeated repository, or a repeated stack tag. + additionalProperties: false + required: + - title + - description + - stack + - repository_url + - status + properties: + title: + $ref: "#/schemas/ProfileProjectTitle" + description: + oneOf: + - $ref: "#/schemas/ProfileProjectDescription" + - type: "null" + stack: + $ref: "#/schemas/ProfileProjectStack" + repository_url: + oneOf: + - $ref: "#/schemas/ProfileRepositoryUrl" + - type: "null" + status: + $ref: "#/schemas/ProfileItemStatus" + CandidateProfileUpdate: + type: object + description: >- + Complete new state of the candidate profile. It replaces every stored + value as a whole: a single field sent as null is unknown and is removed, + and a list replaces the stored list; only `projects` may be omitted, + which keeps the stored projects. The body is personal data. + + Each value carries a decision `status`. `confirmed` sets a manual value + or confirms a stored suggestion; confirming a suggestion with exactly + its stored value keeps its origin and quote, and any other value makes + the claim manual. `extracted` keeps a stored suggestion unconfirmed and + is accepted only with exactly the stored value; any other use answers + 400 with the pointer of that status, for example `/stack/1/status`. The + provenance, the trust level, and the confirmed categories are not part + of the request, and unknown fields are rejected, so a request can + neither mark a claim as verified nor write a confirmed grade or a + category. + additionalProperties: false + required: + - expected_version + - full_name + - contacts + - stack + - roles + - experience + - soft_skills + - terms + properties: + expected_version: + $ref: "#/schemas/ProfileVersion" + full_name: + oneOf: + - $ref: "#/schemas/ProfileFullNameInput" + - type: "null" + contacts: + $ref: "#/schemas/ProfileContactsInput" + stack: + type: array + maxItems: 30 + description: >- + Technology tags. The schema limits the count; the server also + answers 400 with the pointer of a tag that repeats an earlier one + without regard to letter case, for example `/stack/2/tag`. + items: + $ref: "#/schemas/ProfileStackItemInput" + roles: + type: array + maxItems: 9 + description: >- + Roles. The server answers 400 with the pointer of a role whose + specialization repeats an earlier one, for example + `/roles/1/specialization`. + items: + $ref: "#/schemas/ProfileRoleItemInput" + experience: + type: array + maxItems: 20 + description: Work history entries. + items: + $ref: "#/schemas/ProfileExperienceItemInput" + confirmed_parallel_periods: + type: array + maxItems: 190 + description: >- + Explicit acknowledgements for overlapping periods. Each pair must + use distinct in-range indices and repeat the exact normalized + started_on and ended_on values of those entries in this body. A + changed or reordered period needs a new acknowledgement. The server + retains a previous acknowledgement only for the same indices and + dates. Duplicate pairs and pairs that do not overlap are rejected. + items: + $ref: "#/schemas/ProfileParallelPeriodConfirmation" + soft_skills: + type: array + maxItems: 10 + description: >- + Soft skills. The server answers 400 with the pointer of a skill + that repeats an earlier one without regard to letter case. + items: + $ref: "#/schemas/ProfileSoftSkillItemInput" + projects: + type: array + maxItems: 10 + description: >- + Projects. Unlike the other lists this one is optional: a body + without `projects` keeps the stored projects unchanged, so a client + that does not know the section never deletes it, and an array, + including an empty one, replaces the stored list. A new or changed + repository address schedules a server check on the public GitHub + API after the save commits; the save itself never waits for GitHub. + items: + $ref: "#/schemas/ProfileProjectItemInput" + terms: + $ref: "#/schemas/ProfileTermsInput" diff --git a/api/core/components/schemas/catalog_schemas.yml b/api/core/components/schemas/catalog_schemas.yml new file mode 100644 index 0000000..62a54b3 --- /dev/null +++ b/api/core/components/schemas/catalog_schemas.yml @@ -0,0 +1,212 @@ +schemas: + DirectionCode: + type: string + description: |- + Stable code of a professional direction, the group that a specialization belongs to. + + - development: Development. + - infrastructure: Infrastructure. + - data: Data. + - security: Security. + - quality: Quality. + + Adding a value is a contract change. + enum: + - development + - infrastructure + - data + - security + - quality + SpecializationCode: + type: string + description: |- + Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here. + + - backend: Backend (development). + - frontend: Frontend (development). + - mobile: Mobile (development). + - network_engineer: Network Engineer (infrastructure). + - devops_sre: DevOps/SRE (infrastructure). + - data_analyst: Data Analyst (data). + - ds_ml: DS/ML (data). + - information_security: Information security (security). + - qa: QA (quality). + + Adding a value is a contract change; renaming or removing one is a breaking change. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + GradeCode: + type: string + description: |- + Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change. + enum: + - intern + - junior + - middle + - senior + TaskLanguage: + type: string + description: >- + Programming language in which assessment tasks of a specialization are + offered and solved. It is the language of the task bank, not the + candidate's platform stack, and it never forms a separate category. + Only banks that offer a choice of language define task languages; the + first Backend bank offers Python and Go. Adding a value is a contract + change. + enum: + - python + - go + TestAvailabilityStatus: + type: string + description: >- + Whether an assessment can start for the specialization. `available` + means that a published task bank exists for at least one grade, listed + in `TestAvailability.grades`. `in_development` means that no grade of + the specialization has a published bank yet; the specialization can + still be chosen in the questionnaire, but no assessment starts and no + category can be confirmed for it. Presence in the catalog or in demo + data never means that a test is ready. + enum: + - available + - in_development + TestAvailability: + type: object + description: >- + Assessment availability of a specialization, derived by the server from + the published task banks at the time of the request. The MVP opens an + assessment only for a category, a specialization and a grade, that has + a published bank. `status` is `available` exactly when `grades` is not + empty; for `in_development` both `grades` and `task_languages` are + empty. + additionalProperties: false + required: + - status + - grades + - task_languages + - note + properties: + status: + $ref: "#/schemas/TestAvailabilityStatus" + grades: + type: array + maxItems: 10 + uniqueItems: true + description: >- + Grades of the specialization with a published task bank, in + ascending order. Only these categories can be assessed and + confirmed. + items: + $ref: "#/schemas/GradeCode" + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: >- + Task languages that the published bank offers for this + specialization. Empty when the bank does not offer a choice of + language, as for Network Engineer, or when no bank is published. + The questionnaire accepts only these languages for the + specialization. + items: + $ref: "#/schemas/TaskLanguage" + note: + type: + - string + - "null" + minLength: 1 + maxLength: 300 + description: >- + Short Russian note for the candidate, for example why the test is + not available yet, or null. Plain text; the client shows it as + text, never as HTML. + CatalogSpecialization: + type: object + description: Specialization in the catalog with its assessment availability. + additionalProperties: false + required: + - code + - title + - test_availability + properties: + code: + $ref: "#/schemas/SpecializationCode" + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + test_availability: + $ref: "#/schemas/TestAvailability" + CatalogDirection: + type: object + description: >- + Professional direction with its specializations. Each specialization + belongs to exactly one direction. + additionalProperties: false + required: + - code + - title + - specializations + properties: + code: + $ref: "#/schemas/DirectionCode" + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + specializations: + type: array + minItems: 1 + maxItems: 20 + description: Specializations of the direction in display order. + items: + $ref: "#/schemas/CatalogSpecialization" + CatalogGrade: + type: object + description: Grade of the scale with its display name. + additionalProperties: false + required: + - code + - title + properties: + code: + $ref: "#/schemas/GradeCode" + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + SpecializationCatalog: + type: object + description: >- + Catalog of directions, specializations, and the grade scale that the + questionnaire and the assessment use. The catalog is reference data and + identical for every caller; it contains no personal data. + additionalProperties: false + required: + - directions + - grades + properties: + directions: + type: array + minItems: 1 + maxItems: 20 + description: Directions in display order. + items: + $ref: "#/schemas/CatalogDirection" + grades: + type: array + minItems: 1 + maxItems: 10 + description: Grade scale in ascending order. + items: + $ref: "#/schemas/CatalogGrade" diff --git a/api/core/components/schemas/common_schemas.yml b/api/core/components/schemas/common_schemas.yml new file mode 100644 index 0000000..b7125da --- /dev/null +++ b/api/core/components/schemas/common_schemas.yml @@ -0,0 +1,49 @@ +schemas: + Timestamp: + type: string + format: date-time + description: >- + UTC instant in RFC 3339 format with the Z suffix, for example + 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in + this contract uses this schema. + examples: + - "2026-10-05T09:30:00Z" + PageInfo: + type: object + description: >- + Cursor pagination state of a list response. Lists are ordered by a + stable server-defined key. To read the next page, repeat the request + with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - "null" + minLength: 1 + maxLength: 512 + pattern: "^[A-Za-z0-9_-]+$" + description: >- + Opaque cursor of the next page, or null on the last page. Clients + must not parse, build, or store it beyond the current listing. + CandidateHandle: + type: string + minLength: 47 + maxLength: 47 + pattern: "^cv1_[A-Za-z0-9_-]{43}$" + description: >- + Opaque reference to a candidate as one organization sees it, taken + from the organization-scoped anonymous card. It is a versioned HMAC + alias, not a candidate account or profile identifier; it contains no + contact information and is meaningless to another organization. The + server resolves it only against the current visible cohort of the + organization in the path. Clients never parse or construct it. It is + shared by the candidate-card read and invitations. + examples: + - cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA diff --git a/api/core/components/schemas/consent_schemas.yml b/api/core/components/schemas/consent_schemas.yml new file mode 100644 index 0000000..f2d18fe --- /dev/null +++ b/api/core/components/schemas/consent_schemas.yml @@ -0,0 +1,244 @@ +schemas: + ConsentPurposeCode: + type: string + description: |- + One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. + + - c1: processing of personal data, given at registration. + - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change. + - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. + - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. + - c5: import of FSP results. + + ConsentPurpose lists the subset whose text the client may read before an account exists. + enum: + - c1 + - c2 + - c3 + - c4 + - c5 + ConsentSettingsPurpose: + type: string + description: >- + Consent text that an authenticated account can read and accept in + settings. C4 is scoped to an invitation and organization, so it is not + available through the general settings flow. + enum: + - c1 + - c2 + - c3 + - c5 + ConsentSettingsRevokePurpose: + type: string + description: >- + Consent that can be revoked through the general settings flow. C1 uses + the account deletion request, and C4 must be revoked for one + organization. + enum: + - c2 + - c3 + - c5 + ConsentState: + type: string + description: |- + State of a consent record, computed from the ledger. + + - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation. + - superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4. + - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it. + enum: + - active + - superseded + - revoked + ConsentSource: + type: string + description: |- + Where the subject gave the consent. + + - registration: the c1 acceptance of RegisterAccount. + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). + - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. + + A c4 given when sending an application (PRD Q9) is planned as an additional value. + enum: + - registration + - consent_settings + - invitation_acceptance + ConsentRevocationSource: + type: string + description: |- + Who recorded a revocation. + + - consent_settings: the subject revoked the consent in the product. + - support_request: an operator recorded a revocation that the subject requested through support. + enum: + - consent_settings + - support_request + ConsentOrganization: + type: object + description: >- + Organization of a c4 consent as the consent recorded it. `name` is a + snapshot of the name that the shown consent text carried at the time + of the consent, and the stored text hash proves that text with this + name; a later rename of the organization does not change it, so it + can differ from the current name. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: >- + Name of the organization in the consent text at the time of the + consent. Plain text; clients show it as text, never as HTML. + ConsentRecord: + type: object + description: >- + One record of the consent ledger as its subject reads it: the purpose, + the text version the subject accepted, where and when the consent was + given, its state, and the revocation. A c4 record also names the + organization, the contact fields, and the invitation with its terms + version; these fields are null for every other purpose. The server + also stores the SHA-256 hash of exactly the text the subject saw, + which a client never sends or receives. + additionalProperties: false + required: + - id + - purpose + - state + - text_version + - source + - granted_at + - revoked_at + - revocation_source + - organization + - fields + - invitation_id + - invitation_terms_version + properties: + id: + type: string + format: uuid + description: Identifier of the record. + purpose: + $ref: "#/schemas/ConsentPurposeCode" + state: + $ref: "#/schemas/ConsentState" + text_version: + description: Version of the consent text that the subject accepted. + allOf: + - $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + source: + $ref: "#/schemas/ConsentSource" + granted_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + revoked_at: + description: Moment of the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + revocation_source: + description: Who recorded the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: "#/schemas/ConsentRevocationSource" + - type: "null" + organization: + description: >- + Organization that a c4 consent allows to read the fields, with the + name the consent text showed, or null for every other purpose. + oneOf: + - $ref: "#/schemas/ConsentOrganization" + - type: "null" + fields: + type: + - array + - "null" + minItems: 1 + maxItems: 4 + uniqueItems: true + description: >- + Contact fields that a c4 consent covers, or null for every other + purpose. One kind never implies another. + items: + $ref: "./contact_grant_schemas.yml#/schemas/ContactFieldKind" + invitation_id: + type: + - string + - "null" + format: uuid + description: >- + Invitation whose acceptance gave a c4 consent, or null for every + other purpose. + invitation_terms_version: + description: >- + Terms version that the acceptance accepted, or null for every + other purpose. + oneOf: + - $ref: "./invitation_schemas.yml#/schemas/InvitationTermsVersion" + - type: "null" + ConsentRecordList: + type: object + description: >- + One page of the consent ledger of the current account, newest grant + first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Records of the page. + items: + $ref: "#/schemas/ConsentRecord" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + ConsentSettingsGrantRequest: + type: object + description: >- + Accept the current published text shown by GetMyConsentText. The server + checks its version again before recording the grant. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + accepted: + type: boolean + enum: + - true + description: Must be true to record an explicit acceptance. + ConsentDeletionRequest: + type: object + description: >- + Durable request to delete the account and its personal data. The request + is recorded before asynchronous processing starts; it does not mean + deletion has completed. + additionalProperties: false + required: + - id + - status + - requested_at + properties: + id: + type: string + format: uuid + description: Identifier of the durable deletion request. + status: + type: string + enum: + - requested + - processing + description: Current state of the deletion request. + requested_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" diff --git a/api/core/components/schemas/contact_grant_schemas.yml b/api/core/components/schemas/contact_grant_schemas.yml new file mode 100644 index 0000000..8646ae9 --- /dev/null +++ b/api/core/components/schemas/contact_grant_schemas.yml @@ -0,0 +1,279 @@ +schemas: + ContactFieldKind: + type: string + description: |- + Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another. + + - full_name: the full name from the profile. + - email: the contact email address from the profile. + - phone: the contact phone number from the profile. + - telegram: the Telegram username from the profile. + + The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change. + enum: + - full_name + - email + - phone + - telegram + ContactConsentText: + type: object + description: >- + Currently published text of the consent C4 for this invitation. The + server stores an acceptance with `text_version` and the hash of + exactly this text, together with the organization, the selected + fields, the invitation, and its terms version (the consent ledger). + additionalProperties: false + required: + - text_version + - text + properties: + text_version: + $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + text: + type: string + minLength: 1 + maxLength: 100000 + description: >- + Full consent text in plain UTF-8 with the name of the + organization; paragraphs are separated by an empty line. The + client shows it as text, never as HTML, next to the field choice. + ContactConsentOffer: + type: object + description: >- + What the candidate can consent to in an acceptance: the consent text + and the kinds of contact that the candidate's profile holds now. It + holds kinds only, never contact values, and nothing is preselected. + additionalProperties: false + required: + - text + - available_fields + properties: + text: + $ref: "#/schemas/ContactConsentText" + available_fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: >- + Kinds of contact that the profile holds and that an acceptance may + select. A kind outside this list answers 400 in an acceptance. + items: + $ref: "#/schemas/ContactFieldKind" + ContactConsentAcceptance: + type: object + description: >- + Consent C4 given in an acceptance: the text version the candidate saw, + an explicit `accepted`, and the contact fields the candidate selected. + At least one field is required, so a hidden default or an empty choice + never creates a grant. A text version that is not the currently + published one answers 400 validation_failed with the pointer + `/consent_c4/text_version`, and a field that the profile does not hold + answers 400 with the pointer of that item, such as + `/consent_c4/fields/1`. C4 is given only here, never at registration. + The permission to pass the selected data on to the organization's ATS + (PRD C4 and FR19) is planned as an additive optional flag that + defaults to no transfer. + additionalProperties: false + required: + - text_version + - accepted + - fields + properties: + text_version: + $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + accepted: + type: boolean + enum: + - true + description: Explicit consent. Only true is valid. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: >- + Contact fields the organization may read after the acceptance. + The grant covers exactly these fields and no other. + items: + $ref: "#/schemas/ContactFieldKind" + ContactGrantState: + type: string + description: |- + State of a contact grant. + + - active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile. + - revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant. + enum: + - active + - revoked + ContactRevocationReason: + type: string + description: |- + Why a contact grant was revoked, shown only to the candidate. + + - consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed. + - participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed. + - visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead. + + The withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant. + enum: + - consent_revoked + - participation_cancelled + - visibility_closed + ContactAccessBlock: + type: string + description: |- + Why an active grant does not allow a read now, shown only to the candidate. + + - visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization. + enum: + - visibility + ContactGrant: + type: object + description: >- + Contact grant as the candidate reads it: which fields one organization + may read, from which invitation and terms version, and whether it is + still active. It holds kinds only, never contact values. A grant is + stored apart from the invitation state, so a later change of the + state does not change it unless the state is a cancellation by the + candidate. + additionalProperties: false + required: + - id + - fields + - status + - readable + - blocked_by + - terms_version + - consent_text_version + - granted_at + - revoked_at + - revocation_reason + properties: + id: + type: string + format: uuid + description: Identifier of the grant. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that the grant covers. + items: + $ref: "#/schemas/ContactFieldKind" + status: + $ref: "#/schemas/ContactGrantState" + readable: + type: boolean + description: >- + Whether the organization can read the covered fields now: true + only for an active grant whose current consent and visibility + allow the read. The organization sees the same fact as + `contact_access.status` `available`, without the reason. + blocked_by: + description: >- + Why an active grant is not readable now, or null when it is + readable or revoked; a revoked grant has `revocation_reason` + instead. + oneOf: + - $ref: "#/schemas/ContactAccessBlock" + - type: "null" + terms_version: + description: Terms version of the invitation that the acceptance accepted. + allOf: + - $ref: "./invitation_schemas.yml#/schemas/InvitationTermsVersion" + consent_text_version: + description: Version of the consent C4 text that the candidate accepted. + allOf: + - $ref: "./identity_schemas.yml#/schemas/ConsentTextVersion" + granted_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + revoked_at: + description: Moment of the revocation, or null while the grant is active. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + revocation_reason: + description: Reason of the revocation, or null while the grant is active. + oneOf: + - $ref: "#/schemas/ContactRevocationReason" + - type: "null" + ContactPhoneNumber: + type: string + minLength: 8 + maxLength: 16 + pattern: '^\+[1-9][0-9]{6,14}$' + description: Phone number in the E.164 format, for example +70000000000. + ContactTelegramUsername: + type: string + minLength: 6 + maxLength: 33 + pattern: "^@[A-Za-z0-9_]{5,32}$" + description: Telegram username with the leading @. + ContactFullName: + type: string + minLength: 1 + maxLength: 200 + pattern: '^\S(?:.*\S)?$' + description: >- + Full name as the candidate wrote it in the profile. Plain text without + line breaks; clients show it as text, never as HTML. + ContactDisclosure: + type: object + description: >- + Contacts of the candidate that the organization may read through an + active grant of this invitation. This is the only response that + carries contact values, and it is separate from the terms and from + the invitation. Each field the grant does not cover is null, and so + is a covered field that the profile no longer holds. The response is + never cached or stored by the server for later reads, so a + revocation closes the next read at once. The value formats depend on + the profile contract (FR02), which must store the same + formats; see ContactFieldKind. + additionalProperties: false + required: + - invitation_id + - grant_id + - fields + - granted_at + - full_name + - email + - phone + - telegram + properties: + invitation_id: + type: string + format: uuid + description: Invitation whose acceptance created the grant. + grant_id: + type: string + format: uuid + description: Grant that allows the read. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that the grant covers. + items: + $ref: "#/schemas/ContactFieldKind" + granted_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + full_name: + oneOf: + - $ref: "#/schemas/ContactFullName" + - type: "null" + email: + oneOf: + - $ref: "./identity_schemas.yml#/schemas/EmailAddress" + - type: "null" + phone: + oneOf: + - $ref: "#/schemas/ContactPhoneNumber" + - type: "null" + telegram: + oneOf: + - $ref: "#/schemas/ContactTelegramUsername" + - type: "null" diff --git a/api/core/components/schemas/evidence_schemas.yml b/api/core/components/schemas/evidence_schemas.yml new file mode 100644 index 0000000..06e9bd9 --- /dev/null +++ b/api/core/components/schemas/evidence_schemas.yml @@ -0,0 +1,258 @@ +schemas: + EvidenceKind: + type: string + description: |- + Whether a fact is a statement or an observation. + + - claim: something the candidate stated that nothing confirmed separately. Its trust is 0. + - measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3. + + Assessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart. + enum: + - claim + - measurement + EvidenceSourceType: + type: string + description: |- + Where the fact comes from. + + - assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source. + + Adding a value is a contract change. + enum: + - assessment_result + EvidenceAttribution: + type: string + description: |- + Whose contribution the fact is. + + - personal: the candidate's own result. Every assessment fact is personal. + - team_role: a team result with a confirmed role of the candidate. + - team_unattributed: a team result without a confirmed role; it is not a personal skill. + + Only `personal` is produced today. + enum: + - personal + - team_role + - team_unattributed + EvidenceTrustLevel: + type: integer + format: int32 + minimum: 0 + maximum: 3 + description: |- + Strength of the confirmation. + + - 0: stated by the person, not confirmed separately. + - 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed. + - 2: a result tied to a confirmed identity or confirmed by an independent party. + - 3: an in-person check with a matching confirmation. + + A repeated statement, a sign-in, or a repeated tag of the same event never raises the level. + examples: + - 1 + EvidenceVisibility: + type: string + description: |- + Whether the fact may take part in what an organization reads. + + - visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2. + - hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result. + enum: + - visible + - hidden + EvidenceSkillCode: + type: string + description: A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + - go + - postgresql + - kafka + - docker + EvidenceBasis: + type: string + description: |- + What the measurement rests on. + + - synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement. + enum: + - synthetic_demo + EvidenceCalibrationStatus: + type: string + description: |- + Calibration of the method behind the result. + + - uncalibrated: the thresholds are initial values that no measurement has validated. + enum: + - uncalibrated + EvidenceResult: + type: object + description: >- + What the fact says: the grade that was passed and how reliable the method + is. It carries no score, answer, item, failure, or anti-cheat data. + additionalProperties: false + required: + - grade + - basis + - calibration_status + properties: + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + basis: + $ref: "#/schemas/EvidenceBasis" + calibration_status: + $ref: "#/schemas/EvidenceCalibrationStatus" + EvidenceSource: + type: object + description: >- + Where the fact comes from. For an assessment the event is the attempt + and the result is the immutable result of that attempt, which the + candidate reads at `GetMyAssessmentResult`; the two identifiers are + equal because a result is keyed by its attempt. + additionalProperties: false + required: + - type + - event_id + - result_id + properties: + type: + $ref: "#/schemas/EvidenceSourceType" + event_id: + type: string + format: uuid + description: Identifier of the source event. One event is one fact, however many skills it is tagged with. + result_id: + type: string + format: uuid + description: Identifier of the immutable result that produced the fact. + EvidenceFact: + type: object + description: >- + One independent fact of the current candidate. `occurred_at` is when + the source event ended; for an assessment it is the time of the + decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag + never makes a second fact. Hidden facts are listed here with their + visibility, because the candidate owns them. + additionalProperties: false + required: + - id + - kind + - source + - skills + - result + - attribution + - trust + - occurred_at + - visibility + properties: + id: + type: string + format: uuid + description: Identifier of the fact. + kind: + $ref: "#/schemas/EvidenceKind" + source: + $ref: "#/schemas/EvidenceSource" + skills: + type: array + minItems: 1 + maxItems: 13 + uniqueItems: true + description: Skill tags of the event in ascending order. + items: + $ref: "#/schemas/EvidenceSkillCode" + result: + $ref: "#/schemas/EvidenceResult" + attribution: + $ref: "#/schemas/EvidenceAttribution" + trust: + $ref: "#/schemas/EvidenceTrustLevel" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + visibility: + $ref: "#/schemas/EvidenceVisibility" + EvidenceFactList: + type: object + description: One page of the facts of the current candidate, newest event first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Facts of the page. + items: + $ref: "#/schemas/EvidenceFact" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + OrganizationEvidenceFact: + type: object + description: >- + The one assessment fact that supports a category of the card as an + organization reads it: the earliest visible measurement that passed + exactly the confirmed grade of that category. A lower grade, a retake, + the other tags of the event, the source, the basis, the exact time, and + every identifier stay with the candidate. The fact carries no + identifier of the fact, the event, the result, or the candidate, so it + cannot be joined to a person by a key. It is not unlinkable: the skill, + the grade, the trust level, and the year, together with the other + values of the card, can narrow a small pool of candidates, and the + minimum cohort of the card does not cover the year. `basis` and + `calibration_status` are the same for every candidate: they say that + the fact comes from a synthetic demonstration and is not calibrated, + so a demonstration is never read as a validated measurement. The fact + never carries an answer, score, item, failure, signal, or review band. + additionalProperties: false + required: + - skill + - grade + - trust + - basis + - calibration_status + - observed_year + properties: + skill: + $ref: "#/schemas/EvidenceSkillCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + trust: + $ref: "#/schemas/EvidenceTrustLevel" + basis: + $ref: "#/schemas/EvidenceBasis" + calibration_status: + $ref: "#/schemas/EvidenceCalibrationStatus" + observed_year: + type: integer + format: int32 + minimum: 2000 + maximum: 9999 + description: Year (UTC) when the assessment ended. The month, day, and time stay with the candidate. + examples: + - 2026 + OrganizationEvidence: + type: object + description: >- + The permitted evidence of one candidate card, ordered by skill: at most + one fact for each category of the card (at most nine). The list is empty + when no visible fact supports a category of the card. + additionalProperties: false + required: + - items + properties: + items: + type: array + maxItems: 9 + description: Permitted facts, one for each supported category. + items: + $ref: "#/schemas/OrganizationEvidenceFact" diff --git a/api/core/components/schemas/identity_schemas.yml b/api/core/components/schemas/identity_schemas.yml new file mode 100644 index 0000000..c8f3976 --- /dev/null +++ b/api/core/components/schemas/identity_schemas.yml @@ -0,0 +1,328 @@ +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: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. A successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step and leaves every other saved step unchanged. + - 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: "./consent_schemas.yml#/schemas/ConsentPurposeCode" + 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: >- + One-time token copied from the verification link and the password chosen + for the registration that issued it. The password is never included in + the link. + additionalProperties: false + required: + - token + - password + properties: + token: + $ref: "#/schemas/VerificationToken" + password: + type: string + minLength: 1 + maxLength: 128 + description: >- + Password chosen for the registration that issued this token. It is + sent in the request body and never appears in the verification link. + The server applies NFKC normalization and the login length bounds, + without reapplying the current new-registration blocklist. + VerificationCode: + type: string + minLength: 6 + maxLength: 6 + pattern: "^[0-9]{6}$" + description: >- + Six-digit code from the verification message, with leading zeros. It is + request input only; the server keeps a keyed digest of it, never the code. + EmailVerificationCodeRequest: + type: object + description: >- + Address, the six-digit code from its verification message, and the + password chosen for the registration that issued the code. The password + is checked the same way as in EmailVerificationRequest. + additionalProperties: false + required: + - email + - code + - password + properties: + email: + $ref: "#/schemas/EmailAddress" + code: + $ref: "#/schemas/VerificationCode" + password: + type: string + minLength: 1 + maxLength: 128 + description: >- + Password chosen for the registration that issued the code. The server + applies NFKC normalization and the login length bounds, without + reapplying the current new-registration blocklist. + 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/invitation_schemas.yml b/api/core/components/schemas/invitation_schemas.yml new file mode 100644 index 0000000..440932f --- /dev/null +++ b/api/core/components/schemas/invitation_schemas.yml @@ -0,0 +1,945 @@ +schemas: + InvitationVersion: + type: integer + format: int64 + minimum: 1 + description: >- + Version of an invitation. Creation makes version 1, and every committed + change advances it by exactly one: a change of the draft, a send, the + first view, an answer, a salary raise, a withdrawal, a cancellation, + and an expiry made by the server. Every command carries the version + the client read as `expected_version`; a stale value answers 412 + version_conflict and changes nothing. + examples: + - 3 + InvitationTermsVersion: + type: integer + format: int64 + minimum: 1 + description: >- + Version of the terms of an invitation. The terms of a version are an + immutable snapshot: every committed change of the terms, in the draft + or by the one raise of the upper salary bound after sending, creates + the next terms version, and a change of anything else keeps it. An + acceptance names the terms version it accepts, and the consent C4 and + the contact grant record it. + examples: + - 2 + InvitationState: + type: string + description: |- + State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`. + + - draft: the organization prepares the terms. The candidate does not see the invitation. + - delivered: the invitation is in the candidate's inbox and the response deadline runs. + - viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged. + - counter: planned; the candidate sent the one counter offer. No MVP operation produces it. + - accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists. + - interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them. + - declined: terminal; the candidate declined with a structured reason. No access arises. + - expired: terminal; a server deadline passed, see `expiry_reason`. No access arises. + - withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it. + - cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked. + + Planned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change. + enum: + - draft + - delivered + - viewed + - counter + - accepted + - interview_scheduled + - interviewed + - negotiation + - terms_agreed + - no_deal + - declined + - expired + - withdrawn + - cancelled_by_candidate + InvitationExpiryReason: + type: string + description: |- + Why an invitation expired. Set exactly when the state is `expired`, null otherwise. + + - invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created. + - negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it. + enum: + - invitation_timeout + - negotiation_timeout + InvitationResponsePeriod: + type: integer + format: int32 + enum: + - 3 + - 7 + - 14 + description: >- + Days the candidate has to answer, chosen by the organization in the + draft from the product policy: 3, 7, or 14. The deadline starts at the + first delivery and is never reset by an email, a view, or a counter + offer. + examples: + - 7 + InvitationRoleTitle: + type: string + minLength: 1 + maxLength: 200 + pattern: '^\S(?:.*\S)?$' + description: >- + Name of the offered role, for example "Middle Go developer in the + payments team". It has no leading or trailing whitespace and no line + breaks. Plain text; clients show it as text, never as HTML. + InvitationTeamDescription: + type: string + minLength: 1 + maxLength: 1000 + pattern: '\S' + description: >- + Description of the team the candidate would join, such as its size, + roles, and way of working. It may contain line breaks and has at least + one character that is not white space. Plain text; clients show it as + text, never as HTML. It describes the job and must not contain + personal data of employees or candidates. + InvitationOfferType: + type: string + description: |- + Type of the offer. + + - full_time: employment with a full working week. + - part_time: employment with a part-time working week. + - contract: a fixed-term or project contract outside employment. + - internship: an internship. + + Adding a value is a contract change. + enum: + - full_time + - part_time + - contract + - internship + InvitationCommunicationChannel: + type: string + description: |- + Channel through which the organization will contact the candidate after an acceptance. + + - email: a letter to the email address the candidate disclosed. + - phone: a call or a text to the phone number the candidate disclosed. + - telegram: a message to the Telegram username the candidate disclosed. + - video_call: an invitation to a video call, sent through one of the disclosed contacts. + + The channel describes the organization's plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel. + enum: + - email + - phone + - telegram + - video_call + InvitationCommunicationMethod: + type: object + description: >- + How the organization will contact the candidate after an acceptance. + It is part of the terms, so the candidate sees it before choosing + which contacts to disclose. An invitation without it cannot exist, + because the terms require it. + additionalProperties: false + required: + - channel + - details + properties: + channel: + $ref: "#/schemas/InvitationCommunicationChannel" + details: + description: >- + Optional short note, for example the first step or the expected + time of the first contact, or null. Plain text without line + breaks; it never contains a link or a contact of an employee. + oneOf: + - $ref: "#/schemas/InvitationCommunicationNote" + - type: "null" + InvitationCommunicationNote: + type: string + minLength: 1 + maxLength: 300 + pattern: '^\S(?:.*\S)?$' + description: >- + Short note on the communication method, for example "A 30-minute call + with the team lead within three working days". It has no leading or + trailing whitespace and no line breaks. Plain text; clients show it as + text, never as HTML. + InvitationPackageItemText: + type: string + minLength: 1 + maxLength: 300 + pattern: '^\S(?:.*\S)?$' + description: >- + Short description of a condition, for example "Quarterly bonus up to + 20% of the salary". It has no leading or trailing whitespace and no + line breaks. Plain text; clients show it as text, never as HTML. + InvitationPackageItemProvided: + type: object + description: The condition is part of the offer, with its description. + additionalProperties: false + required: + - status + - description + properties: + status: + type: string + enum: + - provided + description: + $ref: "#/schemas/InvitationPackageItemText" + InvitationPackageItemNotProvided: + type: object + description: >- + The organization states explicitly that the offer does not include the + condition ("Не предусмотрено" in the interface). It has no + description. + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - not_provided + InvitationPackageItem: + description: >- + One required condition of the package, selected by `status`: + `provided` with a description, or `not_provided` without one. Not + providing a condition is an explicit choice: the field is required in + the package, so an absent field fails validation instead of meaning + "not provided": it answers 400 `required` with its pointer, such as + `/terms/package/training`. A `provided` item without a description + answers `required` with the pointer of the description, and a + `not_provided` item with a description answers `invalid` with the + pointer of the item. ogen selects the variant by the value of + `status`. + oneOf: + - $ref: "#/schemas/InvitationPackageItemProvided" + - $ref: "#/schemas/InvitationPackageItemNotProvided" + InvitationPackage: + type: object + description: >- + Required section of the package (PRD FR12): the bonus, the equipment, + the training, and the voluntary health insurance (ДМС). Every field is + required and is either provided with a description or explicitly not + provided. The work format of the package is the required + `work_formats` term, which has no "not provided" variant. Adding a + required condition is a breaking change; an optional one is additive. + additionalProperties: false + required: + - bonus + - equipment + - training + - health_insurance + properties: + bonus: + $ref: "#/schemas/InvitationPackageItem" + equipment: + $ref: "#/schemas/InvitationPackageItem" + training: + $ref: "#/schemas/InvitationPackageItem" + health_insurance: + $ref: "#/schemas/InvitationPackageItem" + InvitationTerms: + type: object + description: >- + Terms of an invitation: everything the candidate sees before deciding + and before any contact is disclosed. The same schema is the request + field of a draft and the stored snapshot of a terms version, so a + response can be sent back unchanged. Every field is required; a field + that may have no value says so with an explicit variant (`location` + null for a remote role, a package item `not_provided`). The terms never + contain data of the candidate: no contact, no salary minimum, and no + indicator derived from it. The server checks the cross-field rules + after the schema and answers 400 validation_failed with the pointer of + the field: the salary rules of SalaryRange with `/terms/salary/salary_to`, + a missing place of work for the `office` or `hybrid` format with + `/terms/location`, and a repeated technology in `tech_stack` with the + pointer of the later item. + additionalProperties: false + required: + - role_title + - specialization + - grade + - offer_type + - tasks + - team + - tech_stack + - work_formats + - location + - communication_method + - salary + - package + properties: + role_title: + $ref: "#/schemas/InvitationRoleTitle" + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + offer_type: + $ref: "#/schemas/InvitationOfferType" + tasks: + type: array + minItems: 1 + maxItems: 20 + description: Work tasks of the role in the order given. + items: + $ref: "./need_schemas.yml#/schemas/NeedTaskText" + team: + $ref: "#/schemas/InvitationTeamDescription" + tech_stack: + type: array + minItems: 1 + maxItems: 30 + uniqueItems: true + description: >- + Technologies of the role. The server compares names without regard + to letter case. + items: + $ref: "./need_schemas.yml#/schemas/SkillName" + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: >- + Work formats the organization offers; the candidate may choose any + of them. + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + location: + description: >- + Place of work for the `office` or `hybrid` format, or null when + the only format is `remote`. It is required with either of those + formats. + oneOf: + - $ref: "./need_schemas.yml#/schemas/NeedLocationName" + - type: "null" + communication_method: + $ref: "#/schemas/InvitationCommunicationMethod" + salary: + $ref: "./need_schemas.yml#/schemas/SalaryRange" + package: + $ref: "#/schemas/InvitationPackage" + InvitationNeedReference: + type: object + description: >- + Need of the same organization that the invitation was built from, with + the requirements version used. A direct invitation has no need. The + link is informational: the invitation keeps its own terms, which may + differ from the need, and a later change of the need never changes + them. + additionalProperties: false + required: + - need_id + - requirements_version + properties: + need_id: + type: string + format: uuid + description: Identifier of a need of the organization in the path. + requirements_version: + description: >- + `requirements_version` of the need that the invitation refers to; + it must be a version that the need has had. + allOf: + - $ref: "./need_schemas.yml#/schemas/NeedVersion" + InvitationSalaryFit: + type: string + description: |- + Coarse indicator for the organization of how the salary range relates to the candidate's hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis. + + - within_range: the minimum is not above `B`. + - up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`. + - above: the minimum is more than 10% above `B`. + - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. + - not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis. + + Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting. + + The server never rejects or changes a range because of the minimum: a rejection would itself reveal it. + enum: + - within_range + - up_to_10_percent_above + - above + - withheld + - not_available + InvitationContactAccessState: + type: string + description: |- + Whether the organization may read the candidate's contacts through GetOrganizationInvitationContacts now. + + - not_granted: the candidate has not accepted this invitation, so no grant exists. + - available: a grant from this invitation is active and the current consent and visibility allow the read. + - closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate's visibility allows the read, which only follows the candidate's own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization. + enum: + - not_granted + - available + - closed + InvitationContactAccess: + type: object + description: >- + Contact access of the organization through this invitation, without + any contact value. The values come only from + GetOrganizationInvitationContacts. + additionalProperties: false + required: + - status + - fields + properties: + status: + $ref: "#/schemas/InvitationContactAccessState" + fields: + type: array + maxItems: 4 + uniqueItems: true + description: >- + Kinds of contact that the read returns while `status` is + `available`; empty otherwise. + items: + $ref: "./contact_grant_schemas.yml#/schemas/ContactFieldKind" + InvitationOrganization: + type: object + description: >- + Organization that sent the invitation, as the candidate sees it before + deciding. The card that a candidate sees is `CandidateOrganizationCard` of + the organization contract; returning it with the invitation is planned + as an additive field, and this object only names the organization. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: >- + Public name of the organization. Plain text; clients show it as + text, never as HTML. + InvitationDeclineReason: + type: string + description: |- + Structured reason of a decline. Every reason is neutral and none requires a comment. + + - salary: the salary range does not fit. + - tasks: the role or the tasks do not fit. + - stack: the technologies do not fit. + - work_format: the work format or the place of work does not fit. + - package: the package does not fit. + - company: the company or its domain does not fit. + - not_looking: the candidate is not looking for a job now. + - other_offer: the candidate accepted another offer. + - other: another reason ("Другое"); a comment stays optional. + + The organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change. + enum: + - salary + - tasks + - stack + - work_format + - package + - company + - not_looking + - other_offer + - other + InvitationDeclineComment: + type: string + minLength: 1 + maxLength: 500 + pattern: '\S' + description: >- + Optional comment of the candidate on the offer. It may contain line + breaks and has at least one character that is not white space. It is + never shown to the organization, never published, and never written to + logs or notifications; only the candidate reads it back. Plain text; + clients show it as text, never as HTML. + InvitationDeclineRecord: + type: object + description: The candidate's own decline, as the candidate reads it back. + additionalProperties: false + required: + - reason + - comment + - declined_at + properties: + reason: + $ref: "#/schemas/InvitationDeclineReason" + comment: + oneOf: + - $ref: "#/schemas/InvitationDeclineComment" + - type: "null" + declined_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + OrganizationInvitation: + type: object + description: >- + Invitation as the organization reads it: the candidate handle, the + current terms version, the state, the coarse salary indicator, and the + contact access without contact values. It never contains the + candidate's name, email address, phone number, or other contact, the + exact salary minimum, or the reason and comment of a decline. + additionalProperties: false + required: + - id + - organization_id + - candidate_handle + - need + - state + - expiry_reason + - version + - terms_version + - terms + - response_period_days + - response_deadline_at + - salary_raise_used + - salary_fit + - contact_access + - created_at + - updated_at + - delivered_at + - viewed_at + - responded_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization_id: + type: string + format: uuid + description: >- + Organization that owns the invitation, equal to `org_id` of the + path. It never changes. + candidate_handle: + $ref: "./common_schemas.yml#/schemas/CandidateHandle" + need: + description: Need the invitation was built from, or null for a direct invitation. + oneOf: + - $ref: "#/schemas/InvitationNeedReference" + - type: "null" + state: + $ref: "#/schemas/InvitationState" + expiry_reason: + description: Reason of an expiry, or null unless `state` is `expired`. + oneOf: + - $ref: "#/schemas/InvitationExpiryReason" + - type: "null" + version: + $ref: "#/schemas/InvitationVersion" + terms_version: + $ref: "#/schemas/InvitationTermsVersion" + terms: + $ref: "#/schemas/InvitationTerms" + response_period_days: + $ref: "#/schemas/InvitationResponsePeriod" + response_deadline_at: + description: >- + Moment when the candidate's time to answer ends, set at the first + delivery to `delivered_at` plus `response_period_days`, or null for + a draft. A command received at this moment or later is late. After + an acceptance the deadline no longer applies. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + salary_raise_used: + type: boolean + description: >- + Whether the one raise of the upper salary bound after sending + (PRD FR13) has been used. It counts the whole history of the + invitation. + salary_fit: + $ref: "#/schemas/InvitationSalaryFit" + contact_access: + $ref: "#/schemas/InvitationContactAccess" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + delivered_at: + description: Moment of delivery to the candidate's inbox, or null for a draft. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + viewed_at: + description: Moment when the candidate first opened the terms, or null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + responded_at: + description: Moment of the candidate's acceptance or decline, or null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + OrganizationInvitationSummary: + type: object + description: >- + Invitation in the organization's list: its identity, state, versions, + role, salary range, deadline, and contact access. Read the invitation + for the full terms and the salary indicator. + additionalProperties: false + required: + - id + - candidate_handle + - need + - state + - expiry_reason + - version + - terms_version + - role_title + - salary + - response_deadline_at + - contact_access + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + candidate_handle: + $ref: "./common_schemas.yml#/schemas/CandidateHandle" + need: + oneOf: + - $ref: "#/schemas/InvitationNeedReference" + - type: "null" + state: + $ref: "#/schemas/InvitationState" + expiry_reason: + oneOf: + - $ref: "#/schemas/InvitationExpiryReason" + - type: "null" + version: + $ref: "#/schemas/InvitationVersion" + terms_version: + $ref: "#/schemas/InvitationTermsVersion" + role_title: + $ref: "#/schemas/InvitationRoleTitle" + salary: + $ref: "./need_schemas.yml#/schemas/SalaryRange" + response_deadline_at: + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + contact_access: + $ref: "#/schemas/InvitationContactAccess" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + OrganizationInvitationList: + type: object + description: >- + One page of the invitations of an organization, newest first by + creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Invitations of the page. + items: + $ref: "#/schemas/OrganizationInvitationSummary" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + OrganizationInvitationCreate: + type: object + description: >- + New draft for one candidate. The candidate is named only by the + handle from a search result of this organization, never by an email + address, a phone number, or an account identifier. The terms are + complete from the start, so a draft without the tax basis or the + communication method cannot exist. Unknown fields are rejected, so a + request cannot set the state, a version, a deadline, the salary + indicator, contact access, or a candidate's minimum or contact. + additionalProperties: false + required: + - candidate_handle + - terms + properties: + candidate_handle: + $ref: "./common_schemas.yml#/schemas/CandidateHandle" + need: + description: >- + Need of the organization the invitation is built from, or null or + absent for a direct invitation. + oneOf: + - $ref: "#/schemas/InvitationNeedReference" + - type: "null" + response_period_days: + description: Days to answer; absent means 7, the default of the product policy. + allOf: + - $ref: "#/schemas/InvitationResponsePeriod" + terms: + $ref: "#/schemas/InvitationTerms" + OrganizationInvitationUpdate: + type: object + description: >- + Change of a draft over the version the client read. Each field present + replaces that field as a whole and an absent field stays unchanged; + `terms` is always replaced completely, never merged, and a change of + the terms creates the next terms version. `need` sent as null unlinks + the need. The candidate cannot change: a draft for another candidate + is a new draft. Unknown fields are rejected. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/InvitationVersion" + need: + oneOf: + - $ref: "#/schemas/InvitationNeedReference" + - type: "null" + response_period_days: + $ref: "#/schemas/InvitationResponsePeriod" + terms: + $ref: "#/schemas/InvitationTerms" + InvitationCommand: + type: object + description: >- + Command without parameters over the invitation version the client + read: send, withdraw, or cancel. Unknown fields are rejected. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/InvitationVersion" + InvitationSalaryRaise: + type: object + description: >- + The one raise of the upper salary bound of a sent invitation (PRD + FR13). Only `salary_to` changes; the lower bound, the currency, the + period, and the tax basis stay fixed. Unknown fields are rejected, so + the request cannot lower the lower bound or change the basis. + additionalProperties: false + required: + - expected_version + - salary_to + properties: + expected_version: + $ref: "#/schemas/InvitationVersion" + salary_to: + description: >- + New upper bound, above the current one, with a width of the range + from 10% to 40% of its midpoint. + allOf: + - $ref: "./need_schemas.yml#/schemas/RubAmount" + CandidateInvitation: + type: object + description: >- + Invitation as the addressed candidate reads it: the organization, the + current terms with their version, the state and the deadline, the + text and the choice of the consent C4 while an acceptance is + possible, the candidate's own decline, and the contact grant that the + acceptance created. It has no candidate handle, no need, no salary + indicator, and no contact value: the candidate's own contacts and + salary minimum stay in the profile. + additionalProperties: false + required: + - id + - organization + - state + - expiry_reason + - version + - terms_version + - terms + - response_deadline_at + - delivered_at + - viewed_at + - responded_at + - updated_at + - contact_consent + - decline + - contact_grant + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization: + $ref: "#/schemas/InvitationOrganization" + state: + $ref: "#/schemas/InvitationState" + expiry_reason: + oneOf: + - $ref: "#/schemas/InvitationExpiryReason" + - type: "null" + version: + $ref: "#/schemas/InvitationVersion" + terms_version: + $ref: "#/schemas/InvitationTermsVersion" + terms: + $ref: "#/schemas/InvitationTerms" + response_deadline_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + delivered_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + viewed_at: + description: >- + Moment of the first view recorded by ViewMyInvitation, or null + when the candidate has not opened the terms. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + responded_at: + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + contact_consent: + description: >- + Text and choice of the consent C4 for an acceptance, or null when + an acceptance is impossible now: the state does not allow it, the + deadline has passed, or the profile holds no contact to disclose. + In the last case the client tells the candidate to add a contact + to the profile first, because a grant must cover at least one + field. + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactConsentOffer" + - type: "null" + decline: + description: The candidate's decline, or null unless `state` is `declined`. + oneOf: + - $ref: "#/schemas/InvitationDeclineRecord" + - type: "null" + contact_grant: + description: >- + Contact grant that the acceptance of this invitation created, or + null when the invitation was never accepted. It stays after a + revocation, with its status and reason. + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactGrant" + - type: "null" + CandidateInvitationSummary: + type: object + description: >- + Invitation in the candidate's inbox: the organization, the state, the + versions, the role, the salary range, and the deadline. Listing never + records a view; GetMyInvitation returns the full terms, and + ViewMyInvitation records the view. + additionalProperties: false + required: + - id + - organization + - state + - expiry_reason + - version + - terms_version + - role_title + - salary + - work_formats + - response_deadline_at + - delivered_at + - viewed_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization: + $ref: "#/schemas/InvitationOrganization" + state: + $ref: "#/schemas/InvitationState" + expiry_reason: + oneOf: + - $ref: "#/schemas/InvitationExpiryReason" + - type: "null" + version: + $ref: "#/schemas/InvitationVersion" + terms_version: + $ref: "#/schemas/InvitationTermsVersion" + role_title: + $ref: "#/schemas/InvitationRoleTitle" + salary: + $ref: "./need_schemas.yml#/schemas/SalaryRange" + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + response_deadline_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + delivered_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + viewed_at: + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + CandidateInvitationList: + type: object + description: >- + One page of the candidate's invitations, newest first by delivery + time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Invitations of the page. + items: + $ref: "#/schemas/CandidateInvitationSummary" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + InvitationAcceptance: + type: object + description: >- + Acceptance of the current terms with the consent C4. The client sends + the `version` and the `terms_version` it read and the contact fields + the candidate selected; nothing is preselected or defaulted. Unknown + fields are rejected, so a request cannot carry contact values, a + grant, or another consent. + additionalProperties: false + required: + - expected_version + - terms_version + - consent_c4 + properties: + expected_version: + $ref: "#/schemas/InvitationVersion" + terms_version: + description: >- + Terms version that the candidate read and accepts. A version that + is not the current one answers 412 version_conflict. + allOf: + - $ref: "#/schemas/InvitationTermsVersion" + consent_c4: + $ref: "./contact_grant_schemas.yml#/schemas/ContactConsentAcceptance" + InvitationDeclineRequest: + type: object + description: >- + Structured decline: a reason and an optional comment. Unknown fields + are rejected. + additionalProperties: false + required: + - expected_version + - reason + properties: + expected_version: + $ref: "#/schemas/InvitationVersion" + reason: + $ref: "#/schemas/InvitationDeclineReason" + comment: + description: Optional comment for any reason, including `other`; absent or null means none. + oneOf: + - $ref: "#/schemas/InvitationDeclineComment" + - type: "null" diff --git a/api/core/components/schemas/lab_schemas.yml b/api/core/components/schemas/lab_schemas.yml new file mode 100644 index 0000000..28ca48d --- /dev/null +++ b/api/core/components/schemas/lab_schemas.yml @@ -0,0 +1,236 @@ +schemas: + AssessmentLabNodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: "^[a-z][a-z0-9-]{0,14}$" + description: >- + Name of a lab node as the task statement uses it, such as `r1` or + `srv`. It is a label of the task, not a host name or an address. + AssessmentLabNodeKind: + type: string + description: |- + What the console of a node shows. + + - mikrotik: a MikroTik router with the RouterOS console. + - ubuntu: a small Ubuntu server with a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + AssessmentLabNode: + type: object + description: >- + A node of a lab by its task name and kind. It never carries an address, + a MAC address, a port, a password, a key, or an infrastructure name. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: "#/schemas/AssessmentLabNodeName" + kind: + $ref: "#/schemas/AssessmentLabNodeKind" + LabItemContent: + type: object + description: >- + Practical lab: configure or repair a small network of virtual nodes + through their consoles. The candidate starts the lab of the item with + CreateMyAssessmentLab, works in the node consoles, and submits with + SubmitMyAssessmentLab; the server then checks the state of the nodes. + The content lists only the nodes the statement names and the lifetime + of the lab, never the checker, its criteria, the seed, or an address. + SubmitMyAssessmentAnswer takes no answer to a lab item; its result is + submitted only with SubmitMyAssessmentLab. + additionalProperties: false + required: + - format + - nodes + - time_limit_seconds + properties: + format: + type: string + enum: + - lab + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the lab in the order of the statement. + items: + $ref: "#/schemas/AssessmentLabNode" + time_limit_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: >- + Lifetime of a lab of this item from its creation. The lab also ends + no later than the attempt deadline. + LabAnswer: + type: object + description: >- + Answer of a lab item: the state of the nodes of the named lab at the + moment of submission. The server reads that state with the checker of + the task; the body carries no configuration text, score, or + correctness flag. Two answers are equal when they name the same lab. + It is the answer of SubmitMyAssessmentLab only and is not a member of + AssessmentAnswer. + additionalProperties: false + required: + - format + - lab_id + properties: + format: + type: string + enum: + - lab + lab_id: + type: string + format: uuid + description: The lab of this item that the candidate worked in. + AssessmentLabState: + type: string + description: |- + State of a lab of an attempt item. + + - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. + - ready: the consoles can be opened until `expires_at`. + - checking: the answer was accepted; the consoles are closed and the server checks the nodes. + - submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct. + - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab. + - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - checking + - submitted + - expired + - failed + AssessmentLabFailureReason: + type: string + description: >- + Why a lab failed: `lab_error` for an infrastructure failure, such as a + node that did not boot or a check that could not reach a node. It never + depends on the candidate and is never a failed check. + enum: + - lab_error + AssessmentLab: + type: object + description: >- + Candidate view of the lab of one attempt item. It contains no node + address, MAC address, port, password, key, token, seed, checker state, + criteria, score, or infrastructure name. + additionalProperties: false + required: + - id + - item_id + - state + - nodes + - created_at + - ready_at + - expires_at + - finished_at + - failure_reason + properties: + id: + type: string + format: uuid + description: Identifier of the lab. + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + state: + $ref: "#/schemas/AssessmentLabState" + nodes: + type: array + minItems: 1 + maxItems: 8 + items: + $ref: "#/schemas/AssessmentLabNode" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + ready_at: + description: Time the lab became `ready`, or null before. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + expires_at: + description: >- + Time the lab ends unless it was submitted before: the earlier of the + lifetime of the item and the attempt deadline. It never moves. + $ref: "./common_schemas.yml#/schemas/Timestamp" + finished_at: + description: Time the lab reached `submitted`, `expired`, or `failed`, or null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + failure_reason: + description: "`lab_error` when `state` is `failed`, otherwise null." + oneOf: + - $ref: "#/schemas/AssessmentLabFailureReason" + - type: "null" + AssessmentLabCreate: + type: object + description: Start the lab of the current lab item. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + properties: + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + AssessmentLabConsoleSessionCreate: + type: object + description: Open a console of one node of a ready lab. Unknown fields are rejected. + additionalProperties: false + required: + - node + properties: + node: + $ref: "#/schemas/AssessmentLabNodeName" + AssessmentLabConsoleSession: + type: object + description: >- + A console session of one node. The client opens a WebSocket to + `websocket_path` on the same origin before `expires_at`; the session + cookie and the Origin check authorize the upgrade, so no secret travels + in the path, the body, or a query string. A session can be attached + once and ends with the lab. + additionalProperties: false + required: + - id + - node + - websocket_path + - expires_at + properties: + id: + type: string + format: uuid + description: Identifier of the console session; it is not a secret. + node: + $ref: "#/schemas/AssessmentLabNodeName" + websocket_path: + type: string + maxLength: 128 + pattern: "^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$" + description: Same-origin path of the console WebSocket. + expires_at: + description: Time by which the WebSocket must be opened. + $ref: "./common_schemas.yml#/schemas/Timestamp" + AssessmentLabSubmission: + type: object + description: >- + Submit the lab of the current lab item as its answer. Unknown fields + are rejected, so a request cannot send a score or a correctness flag. + additionalProperties: false + required: + - expected_version + - answer + properties: + expected_version: + $ref: "./assessment_schemas.yml#/schemas/AssessmentAttemptVersion" + answer: + $ref: "#/schemas/LabAnswer" diff --git a/api/core/components/schemas/match_schemas.yml b/api/core/components/schemas/match_schemas.yml new file mode 100644 index 0000000..df4610e --- /dev/null +++ b/api/core/components/schemas/match_schemas.yml @@ -0,0 +1,685 @@ +schemas: + MatchConfirmationStatus: + type: string + description: >- + Confirmation state for this specialization only. A result for one + specialization never changes the state of another specialization. + enum: + - confirmed + - unconfirmed + MatchGradeFilter: + type: object + description: A confirmed category filter, never a candidate declaration. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + MatchSearchStackTag: + type: string + description: >- + A stack code that the anonymous card may expose. Search filters do not + accept arbitrary profile text or candidate-provided evidence. + enum: + - go + - postgresql + - kafka + - docker + MatchSearchConditions: + type: object + description: >- + Filters against safe, coarse card conditions. No candidate location, + salary amount, salary minimum, or salary range is accepted. + additionalProperties: false + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + salary_compatibility: + $ref: "./privacy_schemas.yml#/schemas/CandidateSalaryCompatibility" + MatchSearchFilters: + type: object + description: >- + Optional filters over the current organization-visible bank. An empty + object means no additional filter. Confirmed and declared grades are + separate fields; a declaration never satisfies a confirmed-grade or + category filter. Conditions use only the safe, coarse card fields. + additionalProperties: false + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmed_grade: + description: >- + Match only candidates with this currently confirmed grade in the + selected specialization. It never matches a declared grade. + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + confirmed_category: + $ref: "#/schemas/MatchGradeFilter" + confirmation_status: + $ref: "#/schemas/MatchConfirmationStatus" + declared_grade: + description: >- + Candidate-declared grade filter. This is a separate claim and + cannot satisfy `confirmed_grade` or `confirmed_category`. + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + stack: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + items: + $ref: "#/schemas/MatchSearchStackTag" + conditions: + $ref: "#/schemas/MatchSearchConditions" + MatchSearchByNeed: + type: object + description: >- + Search one immutable set of confirmed requirements. `requirements_version` + is the Need.requirements_version, not the general Need.version; text-only + or suggestion-only edits do not change this search basis. + additionalProperties: false + required: + - need_id + - requirements_version + properties: + need_id: + type: string + format: uuid + description: Need owned by the organization in the path. + requirements_version: + $ref: "./need_schemas.yml#/schemas/NeedVersion" + filters: + $ref: "#/schemas/MatchSearchFilters" + MatchSearchByBank: + type: object + description: >- + Search the current organization-visible bank. An empty `filters` object + includes all otherwise eligible specializations as separate entries. + additionalProperties: false + required: + - filters + properties: + filters: + $ref: "#/schemas/MatchSearchFilters" + MatchSearchRequest: + oneOf: + - $ref: "#/schemas/MatchSearchByNeed" + - $ref: "#/schemas/MatchSearchByBank" + description: >- + Search either a Need.requirements_version snapshot or the whole + organization-visible bank with explicit filters. Unknown fields are + rejected by both closed request variants. + MatchSearchNeedSource: + type: object + description: The immutable need requirements snapshot used by this result. + additionalProperties: false + required: + - kind + - need_id + - requirements_version + properties: + kind: + type: string + enum: + - need + need_id: + type: string + format: uuid + requirements_version: + $ref: "./need_schemas.yml#/schemas/NeedVersion" + MatchAppliedConditions: + type: object + description: Conditions echoed as a complete snapshot; null means no filter. + additionalProperties: false + required: + - work_formats + - salary_compatibility + properties: + work_formats: + oneOf: + - type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + - type: "null" + salary_compatibility: + oneOf: + - $ref: "./privacy_schemas.yml#/schemas/CandidateSalaryCompatibility" + - type: "null" + MatchAppliedFilters: + type: object + description: >- + A normalized response snapshot of the bank filters. Each key is present; + null means the corresponding request filter was omitted. This keeps a + search result tied to its exact filter basis. + additionalProperties: false + required: + - specialization + - confirmed_grade + - confirmed_category + - confirmation_status + - declared_grade + - stack + - conditions + properties: + specialization: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + - type: "null" + confirmed_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + confirmed_category: + oneOf: + - $ref: "#/schemas/MatchGradeFilter" + - type: "null" + confirmation_status: + oneOf: + - $ref: "#/schemas/MatchConfirmationStatus" + - type: "null" + declared_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + stack: + oneOf: + - type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + items: + $ref: "#/schemas/MatchSearchStackTag" + - type: "null" + conditions: + oneOf: + - $ref: "#/schemas/MatchAppliedConditions" + - type: "null" + MatchSearchBankSource: + type: object + description: The normalized filters used for a bank search. + additionalProperties: false + required: + - kind + - filters + properties: + kind: + type: string + enum: + - bank + filters: + $ref: "#/schemas/MatchAppliedFilters" + MatchSearchSource: + oneOf: + - $ref: "#/schemas/MatchSearchNeedSource" + - $ref: "#/schemas/MatchSearchBankSource" + description: >- + Search basis echoed with the response so the displayed result remains + tied to its need requirements version or bank filters. + MatchStrength: + type: string + description: Coarse strength of a confirmed assessment for this specialization. + enum: + - standard + - strong + MatchCategory: + type: object + description: >- + A confirmed category. Its specialization must equal the enclosing + match entry's specialization. `basis` says what the grade rests on; + `synthetic_demo` marks a demonstration category, which an organization + must read as one and never as a standard confirmation. + additionalProperties: false + required: + - specialization + - grade + - basis + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + basis: + $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" + MatchScore: + type: number + format: double + minimum: 0 + maximum: 1 + description: A normalized FR09 ranking component from 0 to 1. + MatchNullableScore: + description: >- + A score from a versioned ranking component, or null when it is not + available. Any null component has a matching bounded entry in + `unknown_flags`. + oneOf: + - type: number + format: double + minimum: 0 + maximum: 1 + - type: "null" + MatchUnknownComponent: + type: string + description: Ranking or public-card component whose value is unknown. + enum: + - semantics + - percentile + - assessment + - freshness + - responsiveness + - experience_band + - work_formats + - salary_compatibility + - domain + MatchUnknownReason: + type: string + description: >- + Bounded explanation for an unknown component, not a hiding reason. + `cohort_below_30` is reported only while the comparable real cohort of + the category is smaller than the versioned minimum; once the cohort + reaches the minimum but the percentile is still not computed, the reason + is `percentile_not_computed`. In both cases T is the neutral 0.5. + enum: + - ml_unavailable + - cohort_below_30 + - no_confirmation_for_specialization + - not_in_public_card + - need_field_unconfirmed + - no_freshness_history + - no_response_history + - percentile_not_computed + MatchUnknownFlag: + type: object + description: A safe, bounded explanation for one unavailable component. + additionalProperties: false + required: + - component + - reason + properties: + component: + $ref: "#/schemas/MatchUnknownComponent" + reason: + $ref: "#/schemas/MatchUnknownReason" + MatchUnknownFlags: + type: array + maxItems: 9 + items: + $ref: "#/schemas/MatchUnknownFlag" + MatchEvidenceCode: + type: string + description: >- + Template code for an explanation derived from allowed evidence. It + carries no free text, raw answer, or reason for withheld FSP data. + enum: + - confirmed_category + - required_skill_evidence + - desired_skill_evidence + - domain_alignment + - task_alignment + - work_conditions_match + - salary_compatibility + - declared_grade + MatchEvidenceState: + type: string + enum: + - supports + - partial + - gap + - declared_only + MatchEvidenceSummaryItem: + type: object + description: A templated, non-text evidence explanation. + additionalProperties: false + required: + - code + - state + properties: + code: + $ref: "#/schemas/MatchEvidenceCode" + state: + $ref: "#/schemas/MatchEvidenceState" + MatchEvidenceSummary: + type: array + maxItems: 12 + items: + $ref: "#/schemas/MatchEvidenceSummaryItem" + MatchRequirementKind: + type: string + description: Kind of the need requirement that an explanation item answers. + enum: + - required_skill + - desired_skill + - task + MatchSemanticItemKind: + type: string + description: |- + Kind of the published card item that matched a requirement. + + - project: one published project; `project_title` names it. + - stack: the recognized technology codes of the card. + - roles: the specializations and grades that the card shows. + enum: + - project + - stack + - roles + MatchSimilarityBand: + type: string + description: >- + Coarse band of the cosine similarity between the requirement and the + matched item under the versioned policy thresholds. `high` and `medium` + are the only values; a weaker similarity produces no item. The band is + a computed similarity of two texts, not a judgement of the candidate. + enum: + - high + - medium + MatchSemanticEvidence: + type: object + description: >- + Why the entry is in the result: one confirmed requirement of the need + and the published card item with the highest semantic similarity to it. + The server computes it from stored vectors and the versioned + thresholds; no model writes text into it. `requirement_text` is the + confirmed text of the organization's own need. `project_title` is the + title the candidate published with the `projects` card field and is + null for other kinds. No repository address, owner, or fetched + repository text is ever part of it. + additionalProperties: false + required: + - requirement_kind + - requirement_text + - item_kind + - project_title + - repository_verified + - similarity + properties: + requirement_kind: + $ref: "#/schemas/MatchRequirementKind" + requirement_text: + type: string + minLength: 1 + maxLength: 300 + description: Confirmed skill name or task text of the need. Plain text; show it as text, never as HTML. + item_kind: + $ref: "#/schemas/MatchSemanticItemKind" + project_title: + description: Published project title for `project`, otherwise null. Plain text; show it as text, never as HTML. + oneOf: + - type: string + minLength: 1 + maxLength: 100 + - type: "null" + repository_verified: + type: boolean + description: >- + True only for a project whose linked repository the latest server + check found public on GitHub ("backed by a public repository"). It + does not prove authorship. + similarity: + $ref: "#/schemas/MatchSimilarityBand" + MatchSemanticEvidenceList: + type: array + description: >- + Semantic explanation items in a stable order: `high` before `medium`, + then by similarity, then by the order of the requirements in the need. + At most the versioned per-entry limit is returned. It is empty for a + bank search, while vectors are not ready, when ML is unavailable, and + when no requirement reaches a band; `unknown_flags` names + `ml_unavailable` when the semantic component itself is unknown. + maxItems: 12 + items: + $ref: "#/schemas/MatchSemanticEvidence" + MatchPublicStack: + type: array + maxItems: 4 + uniqueItems: true + items: + $ref: "#/schemas/MatchSearchStackTag" + MatchPublicContext: + type: object + description: >- + Safe anonymous-card context only. A null value means that the value is + not in the public card or is not present; the response does not reveal + which. It contains no contact, candidate location, or salary amount. + additionalProperties: false + required: + - stack + - experience_band + - work_formats + - salary_compatibility + properties: + stack: + oneOf: + - $ref: "#/schemas/MatchPublicStack" + - type: "null" + experience_band: + oneOf: + - $ref: "./privacy_schemas.yml#/schemas/CandidateExperienceBand" + - type: "null" + work_formats: + oneOf: + - type: array + maxItems: 3 + uniqueItems: true + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + - type: "null" + salary_compatibility: + oneOf: + - $ref: "./privacy_schemas.yml#/schemas/CandidateSalaryCompatibility" + - type: "null" + MatchConfirmedComponents: + type: object + description: >- + Components from the FR09 ranking model for a confirmed category. + `percentile` is null when fewer than 30 comparable real candidates are + available; the ranking uses neutral T = 0.5 and does not publish a + percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the + reason appears in `unknown_flags`. + additionalProperties: false + required: + - fit + - coverage + - domain + - semantics + - percentile + - competition + - freshness + - responsiveness + - rank_score + properties: + fit: + $ref: "#/schemas/MatchScore" + coverage: + $ref: "#/schemas/MatchScore" + domain: + $ref: "#/schemas/MatchScore" + semantics: + $ref: "#/schemas/MatchScore" + percentile: + $ref: "#/schemas/MatchNullableScore" + competition: + $ref: "#/schemas/MatchScore" + freshness: + $ref: "#/schemas/MatchScore" + responsiveness: + $ref: "#/schemas/MatchScore" + rank_score: + $ref: "#/schemas/MatchScore" + MatchUnconfirmedComponents: + type: object + description: >- + Unconfirmed entries are ordered only by Fit and coverage. This strict + component object has no theta, T, P, test percentile, or confirmed + assessment score. + additionalProperties: false + required: + - fit + - coverage + properties: + fit: + type: number + format: double + minimum: 0 + maximum: 1 + description: Job fit for this specialization, never an assessment score. + coverage: + type: number + format: double + minimum: 0 + maximum: 1 + description: Coverage of confirmed need skills by allowed public evidence. + MatchConfirmedCandidate: + type: object + description: >- + One confirmed specialization entry in the `main` or `near` group. The + group containing it supplies the group label. A candidate may have a + separate entry for another specialization. + additionalProperties: false + required: + - candidate_handle + - specialization + - confirmation_status + - declared_grade + - category + - strength + - public_context + - evidence_summary + - semantic_evidence + - components + - unknown_flags + properties: + candidate_handle: + $ref: "./common_schemas.yml#/schemas/CandidateHandle" + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmation_status: + type: string + enum: + - confirmed + declared_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + description: Candidate-declared grade for this specialization, never a confirmation. + category: + $ref: "#/schemas/MatchCategory" + strength: + $ref: "#/schemas/MatchStrength" + public_context: + $ref: "#/schemas/MatchPublicContext" + evidence_summary: + $ref: "#/schemas/MatchEvidenceSummary" + semantic_evidence: + $ref: "#/schemas/MatchSemanticEvidenceList" + components: + $ref: "#/schemas/MatchConfirmedComponents" + unknown_flags: + $ref: "#/schemas/MatchUnknownFlags" + MatchUnconfirmedCandidate: + type: object + description: >- + One specialization with no confirmed category. `category` and + `strength` remain present and null. A confirmation in another + specialization never changes this entry. The schema intentionally has + no assessment measurement fields. + additionalProperties: false + required: + - candidate_handle + - specialization + - confirmation_status + - declared_grade + - category + - strength + - public_context + - evidence_summary + - semantic_evidence + - components + - unknown_flags + properties: + candidate_handle: + $ref: "./common_schemas.yml#/schemas/CandidateHandle" + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmation_status: + type: string + enum: + - unconfirmed + declared_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + description: Candidate-declared grade, separate from assessment confirmation. + category: + type: "null" + description: There is no confirmed category for this specialization. + strength: + type: "null" + description: Assessment strength is not measured for this specialization. + public_context: + $ref: "#/schemas/MatchPublicContext" + evidence_summary: + $ref: "#/schemas/MatchEvidenceSummary" + semantic_evidence: + $ref: "#/schemas/MatchSemanticEvidenceList" + components: + $ref: "#/schemas/MatchUnconfirmedComponents" + unknown_flags: + $ref: "#/schemas/MatchUnknownFlags" + MatchSearchGroups: + type: object + description: >- + Separate ranking groups. Confirmed categories appear in main and near; + unconfirmed specializations appear only in the lower unconfirmed group. + additionalProperties: false + required: + - main + - near + - unconfirmed + properties: + main: + type: array + items: + $ref: "#/schemas/MatchConfirmedCandidate" + near: + type: array + items: + $ref: "#/schemas/MatchConfirmedCandidate" + unconfirmed: + type: array + items: + $ref: "#/schemas/MatchUnconfirmedCandidate" + MatchSearchResponse: + type: object + description: >- + Anonymous search result grouped by specialization state. Repeated + organization-scoped handles are allowed when the same candidate has + different specialization entries; entries never transfer confirmation + between specializations. + additionalProperties: false + required: + - source + - groups + - truncated + properties: + source: + $ref: "#/schemas/MatchSearchSource" + groups: + $ref: "#/schemas/MatchSearchGroups" + truncated: + type: boolean + description: >- + True when the groups are not the whole ranked result: a group exceeded + the versioned per-group limit, or the organization's card-view + allowance ended while the entries were being revealed. The entries + returned are in rank order and already counted as card views. It + carries no total, so it does not reveal how many candidates match. diff --git a/api/core/components/schemas/need_schemas.yml b/api/core/components/schemas/need_schemas.yml new file mode 100644 index 0000000..8236f02 --- /dev/null +++ b/api/core/components/schemas/need_schemas.yml @@ -0,0 +1,1175 @@ +schemas: + NeedVersion: + type: integer + format: int64 + minimum: 1 + description: >- + Version of an employer need. Creation makes version 1, and every + committed change of the need advances it by exactly one, including a + change made by the server, such as a planned asynchronous ML + suggestion. Each version is an immutable snapshot of the need. + `requirements_version` names the version whose confirmed requirements + are current, so a change that leaves them unchanged creates a need + version without a new requirements version. + examples: + - 2 + NeedTitle: + type: string + minLength: 1 + maxLength: 200 + pattern: '^\S(?:.*\S)?$' + description: >- + Short name of the need inside the organization, for example "Backend + for the payments team". It has no leading or trailing whitespace and no + line breaks. Plain text; clients show it as text, never as HTML. + NeedSourceText: + type: string + minLength: 1 + maxLength: 10000 + description: >- + Free description of the team's tasks as the employer wrote or pasted + it. The server extracts proposed requirements from it; the text itself + is never a requirement. It may contain line breaks. Plain text; clients + show it as text, never as HTML. It describes the job and must not + contain personal data of candidates. The server stores it as written: + it may contain requirements that discriminate by a protected + characteristic, and the extractor never turns such a requirement into + a need field. Exclusions, the requirements that a candidate must not + meet, are planned as a separate additive field with the Labor Code + article 64 check. + NeedValueStatus: + type: string + description: |- + Confirmation state of one need field. + + - confirmed: a member of the organization entered the value or confirmed it. Only confirmed values feed readiness, category recommendations, search, and invitations. + - extracted: the server proposed the value from the need text or an import, and nobody has confirmed it yet. It is a suggestion: it never feeds search or recommendations and never counts as an answer in readiness. + - unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a Senior grade, the remote format, or a zero salary. + enum: + - confirmed + - extracted + - unknown + NeedItemStatus: + type: string + description: >- + Confirmation state of a list item, and the decision that a request + sends for a field or an item: `confirmed` or `extracted`, with the + meaning of NeedValueStatus. A request sends `confirmed` to confirm a + suggestion or to set a manual value, and `extracted` only to keep a + stored suggestion unconfirmed with exactly its stored value. An item is + never `unknown`; a list with no confirmed item is what readiness + reports as missing. + enum: + - confirmed + - extracted + NeedValueOrigin: + type: string + description: |- + Where the value of a field or item came from. The server sets it; a request never sends it. + + - manual: a member of the organization typed the value in the form. `quote`, `extraction_version`, and `extracted_in_version` are null. + - extracted_from_text: the server extracted the value from `source_text`, with the deterministic rules and dictionary or, planned, with the ML service. `extraction_version` names the extractor version. + - imported: planned; the value was copied from a linked vacancy or an import. No MVP operation produces it. + + Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change. + enum: + - manual + - extracted_from_text + - imported + NeedSourceQuote: + type: string + minLength: 1 + maxLength: 300 + description: >- + Exact excerpt of the `source_text` that the value was extracted from, + so a reviewer can check it. It may contain line breaks. Plain text; + clients show it as text, never as HTML. + NeedVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Opaque identifier of a published extractor or algorithm version, for + example `need-rules.2026-10.1`. Clients show it as text and never + parse it. + NeedValueSource: + type: object + description: >- + Provenance of a value: its origin, the quote it was extracted from, the + need version whose text the quote belongs to, and the extractor + version. Read-only; the server derives it and a request cannot set it. + additionalProperties: false + required: + - origin + - quote + - extracted_in_version + - extraction_version + properties: + origin: + $ref: "#/schemas/NeedValueOrigin" + quote: + description: >- + Excerpt of the need text that supports the value, or null for a + manual value and for an extracted value that the extractor did not + tie to one excerpt. + oneOf: + - $ref: "#/schemas/NeedSourceQuote" + - type: "null" + extracted_in_version: + description: >- + Need version whose `source_text` the value was extracted from and + the quote is an excerpt of, or null for a manual value. A confirmed + value keeps it after the text changes, so its quote may be absent + from the current `source_text`. + oneOf: + - $ref: "#/schemas/NeedVersion" + - type: "null" + extraction_version: + description: >- + Extractor version for an extracted or imported value, or null for + a manual value. + oneOf: + - $ref: "#/schemas/NeedVersionLabel" + - type: "null" + SkillName: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Name of a skill or technology as the employer gave it, for example Go, + PostgreSQL, or Temporal. It has no leading or trailing whitespace and + no line breaks. The server compares names without regard to letter + case. Plain text; clients show it as text, never as HTML. + SkillTaxonomyCode: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z0-9][a-z0-9_.+#-]*$" + description: >- + Code of a skill in the platform skill taxonomy, for example + `postgresql`. The server assigns it from the taxonomy; clients never + send it and never derive it from the name. + NeedTaskText: + type: string + minLength: 1 + maxLength: 300 + pattern: '^\S(?:.*\S)?$' + description: >- + One work task of the team, for example "Move the payout service to an + event model". It has no leading or trailing whitespace and no line + breaks. Plain text; clients show it as text, never as HTML. + NeedDomainName: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Business domain of the work, for example payments or logistics, as + free text. Plain text without line breaks; clients show it as text, + never as HTML. + NeedLocationName: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Place of work for the office or hybrid format, for example a city, + as free text. It describes the employer's office, never a candidate's + address. Plain text without line breaks; clients show it as text, + never as HTML. + RubAmount: + type: integer + format: int64 + minimum: 1000 + maximum: 100000000 + multipleOf: 1000 + description: >- + Amount of money in whole rubles. A salary bound is positive and a + multiple of 1000, the step that PRD FR13 sets for the bounds of a + salary range and for the bids of the sealed final. + examples: + - 120000 + CurrencyCode: + type: string + description: >- + ISO 4217 currency code. The MVP accepts only RUB; adding a value is a + contract change. + enum: + - RUB + SalaryPeriod: + type: string + description: >- + Pay period of a salary amount. The MVP uses only `month`; adding a + value is a contract change. + enum: + - month + SalaryTaxBasis: + type: string + description: >- + Tax basis of a salary amount: `net`, the amount paid out after personal + income tax, or `gross`, the amount before it. The basis is always + explicit; amounts in different bases are never compared directly. + enum: + - net + - gross + SalaryRange: + type: object + description: >- + Salary range `[A; B]` in whole rubles with its base: the currency, the + pay period, and the tax basis (PRD FR13). The schema requires every + field, bounds that are positive multiples of 1000, and the known + currency, period, and basis. The server checks the cross-field rules + in integer arithmetic: `salary_from < salary_to`, and a width `(B - A) + / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + + B` and `5 * (B - A) <= A + B`. A violation answers 400 + validation_failed with the pointer of `salary_to` in the request, for + example `/salary/value/salary_to`. For example, `[95000; 105000]` has + a width of exactly 10% and `[80000; 120000]` exactly 40%; both are + accepted. The rules are the same for a need and an invitation. + additionalProperties: false + required: + - salary_from + - salary_to + - currency + - period + - tax_basis + properties: + salary_from: + $ref: "#/schemas/RubAmount" + salary_to: + $ref: "#/schemas/RubAmount" + currency: + $ref: "#/schemas/CurrencyCode" + period: + $ref: "#/schemas/SalaryPeriod" + tax_basis: + $ref: "#/schemas/SalaryTaxBasis" + NeedSpecialization: + type: object + description: >- + Target specialization of the need with its confirmation state and + provenance. `value` and `source` are null exactly when `status` is + `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/NeedValueStatus" + value: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/NeedValueSource" + - type: "null" + NeedGrade: + type: object + description: >- + Target grade of the need with its confirmation state and provenance. + `value` and `source` are null exactly when `status` is `unknown`; a + text that names no grade leaves the grade unknown instead of assuming + one. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/NeedValueStatus" + value: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/NeedValueSource" + - type: "null" + NeedDomain: + type: object + description: >- + Business domain of the need with its confirmation state and + provenance. `value` and `source` are null exactly when `status` is + `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/NeedValueStatus" + value: + oneOf: + - $ref: "#/schemas/NeedDomainName" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/NeedValueSource" + - type: "null" + NeedWorkFormats: + type: object + description: >- + Work formats that the employer offers, with their confirmation state + and provenance. `value` and `source` are null exactly when `status` is + `unknown`; a known value lists one to three formats. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/NeedValueStatus" + value: + type: + - array + - "null" + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + source: + oneOf: + - $ref: "#/schemas/NeedValueSource" + - type: "null" + NeedLocation: + type: object + description: >- + Place of work with its confirmation state and provenance. `value` and + `source` are null exactly when `status` is `unknown`. Readiness + requires a confirmed place only when the confirmed work formats + include `office` or `hybrid`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/NeedValueStatus" + value: + oneOf: + - $ref: "#/schemas/NeedLocationName" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/NeedValueSource" + - type: "null" + NeedSalary: + type: object + description: >- + Salary range that the employer offers, with its confirmation state and + provenance. `value` and `source` are null exactly when `status` is + `unknown`. A text without a salary leaves it unknown; the server never + substitutes zero, a market estimate, or a range from another need. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: "#/schemas/NeedValueStatus" + value: + oneOf: + - $ref: "#/schemas/SalaryRange" + - type: "null" + source: + oneOf: + - $ref: "#/schemas/NeedValueSource" + - type: "null" + NeedSkill: + type: object + description: >- + One required or desired skill of the need. `taxonomy_code` is null for + a skill that the platform taxonomy does not know: the server keeps the + name as given, never maps it to a guessed code, and counts it as not + covered in category recommendations. + additionalProperties: false + required: + - name + - taxonomy_code + - status + - source + properties: + name: + $ref: "#/schemas/SkillName" + taxonomy_code: + oneOf: + - $ref: "#/schemas/SkillTaxonomyCode" + - type: "null" + status: + $ref: "#/schemas/NeedItemStatus" + source: + $ref: "#/schemas/NeedValueSource" + NeedTask: + type: object + description: One work task of the team with its confirmation state and provenance. + additionalProperties: false + required: + - text + - status + - source + properties: + text: + $ref: "#/schemas/NeedTaskText" + status: + $ref: "#/schemas/NeedItemStatus" + source: + $ref: "#/schemas/NeedValueSource" + NeedSpecializationInput: + type: object + description: >- + Decision about the specialization in a request; see NeedUpdate for the + rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + status: + $ref: "#/schemas/NeedItemStatus" + NeedGradeInput: + type: object + description: >- + Decision about the grade in a request; see NeedUpdate for the rules of + `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + status: + $ref: "#/schemas/NeedItemStatus" + NeedDomainInput: + type: object + description: >- + Decision about the domain in a request; see NeedUpdate for the rules of + `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "#/schemas/NeedDomainName" + status: + $ref: "#/schemas/NeedItemStatus" + NeedWorkFormatsInput: + type: object + description: >- + Decision about the work formats in a request; see NeedUpdate for the + rules of `status`. Formats are compared as a set. + additionalProperties: false + required: + - value + - status + properties: + value: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: "./questionnaire_schemas.yml#/schemas/WorkFormat" + status: + $ref: "#/schemas/NeedItemStatus" + NeedLocationInput: + type: object + description: >- + Decision about the place of work in a request; see NeedUpdate for the + rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "#/schemas/NeedLocationName" + status: + $ref: "#/schemas/NeedItemStatus" + NeedSalaryInput: + type: object + description: >- + Decision about the salary range in a request; see NeedUpdate for the + rules of `status` and SalaryRange for the rules of the range, whose + pointers are under `/salary/value`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: "#/schemas/SalaryRange" + status: + $ref: "#/schemas/NeedItemStatus" + NeedSkillInput: + type: object + description: >- + One skill of a list in a request. A name that equals, without regard to + letter case, a skill of the current version in either skill list + refers to that skill and keeps its origin, quote, and taxonomy code; + this is how an extracted skill is confirmed or moved between the + required and desired lists. Any other name is a new manual skill. + `status` follows the rules of NeedUpdate: `extracted` for a name that + is not a stored suggestion answers 400 validation_failed with the + pointer of that `status`, for example `/required_skills/2/status`. A + name repeated within or across the two skill lists answers 400 with + the pointer of the later `name`. + additionalProperties: false + required: + - name + - status + properties: + name: + $ref: "#/schemas/SkillName" + status: + $ref: "#/schemas/NeedItemStatus" + NeedTaskInput: + type: object + description: >- + One task of the list in a request. A text equal to a task of the + current version refers to that task and keeps its origin and quote; + any other text is a new manual task. `status` and repeated texts follow + the rules of NeedSkillInput. + additionalProperties: false + required: + - text + - status + properties: + text: + $ref: "#/schemas/NeedTaskText" + status: + $ref: "#/schemas/NeedItemStatus" + NeedRequirementSet: + type: object + description: >- + Requirements of one need version, each with its confirmation state and + provenance. Read-only; requests change them through the fields of + NeedCreate and NeedUpdate. + additionalProperties: false + required: + - specialization + - grade + - required_skills + - desired_skills + - tasks + - domain + - work_formats + - location + - salary + properties: + specialization: + $ref: "#/schemas/NeedSpecialization" + grade: + $ref: "#/schemas/NeedGrade" + required_skills: + type: array + maxItems: 30 + description: >- + Required skills; each has weight 2 in skill coverage. Only + confirmed skills count. + items: + $ref: "#/schemas/NeedSkill" + desired_skills: + type: array + maxItems: 30 + description: >- + Desired skills; each has weight 1 in skill coverage. Only confirmed + skills count. + items: + $ref: "#/schemas/NeedSkill" + tasks: + type: array + maxItems: 20 + description: Work tasks of the team in the order given. + items: + $ref: "#/schemas/NeedTask" + domain: + $ref: "#/schemas/NeedDomain" + work_formats: + $ref: "#/schemas/NeedWorkFormats" + location: + $ref: "#/schemas/NeedLocation" + salary: + $ref: "#/schemas/NeedSalary" + NeedFieldName: + type: string + description: >- + Name of a need field, equal to its property name in NeedRequirementSet + and in the request bodies. Adding a value is a contract change. + enum: + - specialization + - grade + - required_skills + - desired_skills + - tasks + - domain + - work_formats + - location + - salary + NeedMissingReason: + type: string + description: >- + Why a critical field is missing: `unknown`, the field has no value, or + `unconfirmed`, it has only an extracted value or, for required + skills, only extracted items that wait for confirmation. + enum: + - unknown + - unconfirmed + NeedMissingField: + type: object + description: >- + One critical field that has no confirmed value, with a specific + question that the client shows next to the field. + additionalProperties: false + required: + - field + - reason + - question + properties: + field: + $ref: "#/schemas/NeedFieldName" + reason: + $ref: "#/schemas/NeedMissingReason" + question: + type: string + minLength: 1 + maxLength: 300 + description: >- + Specific Russian question about the missing value, for example + which grade is needed. Plain text; the client shows it as text, + never as HTML. + NeedReadinessStatus: + type: string + description: >- + `complete` when every critical field has a confirmed value, otherwise + `incomplete`. + enum: + - complete + - incomplete + NeedReadinessReport: + type: object + description: >- + Completeness of the critical fields, computed by the server for the + current version. The critical fields are `specialization`, `grade`, + `required_skills` (at least one confirmed skill), `work_formats`, + `salary`, and `location` when the confirmed work formats include + `office` or `hybrid`. An incomplete need is still a valid saved need; + each later operation, such as search or an invitation, states which + readiness it requires. + additionalProperties: false + required: + - status + - missing_fields + properties: + status: + $ref: "#/schemas/NeedReadinessStatus" + missing_fields: + type: array + maxItems: 9 + description: >- + Critical fields without a confirmed value, each at most once, in + the order of NeedFieldName. Empty exactly when `status` is + `complete`. + items: + $ref: "#/schemas/NeedMissingField" + NeedRecommendationStatus: + type: string + description: |- + State of the category recommendations of the current requirements version. + + - computed: `categories` holds the recommendations computed from the confirmed requirements of `requirements_version`. + - pending: the computation for the current requirements version has not finished yet; `categories` is empty. Read the need again later. + - not_available: the current requirements have no confirmed required or desired skill to compute from; `categories` is empty. + enum: + - computed + - pending + - not_available + NeedSkillOverlap: + type: object + description: >- + Skill coverage of a category: the weighted share of the confirmed + skills of the need that the category taxonomy covers, with weight 2 + for a required and 1 for a desired skill. + additionalProperties: false + required: + - share + - covered_skills + - uncovered_skills + properties: + share: + type: number + format: double + minimum: 0 + maximum: 1 + description: Weighted share from 0 to 1, rounded to two decimals. + covered_skills: + type: array + maxItems: 60 + description: Confirmed skills of the need that the category covers. + items: + $ref: "#/schemas/SkillName" + uncovered_skills: + type: array + maxItems: 60 + description: >- + Confirmed skills of the need that the category does not cover, + including skills without a taxonomy code. + items: + $ref: "#/schemas/SkillName" + NeedMoneyStatus: + type: string + description: |- + How the salary component of a recommendation was obtained. + + - computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given. + - insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null. + - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null. + - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null. + + An unknown candidate minimum never counts as zero. + enum: + - computed + - insufficient_data + - no_salary + - withheld + NeedMoneyFit: + type: object + description: >- + Salary component of a recommendation. It is an aggregate over at least + five candidates and never reveals a minimum of any candidate. + additionalProperties: false + required: + - status + - share + properties: + status: + $ref: "#/schemas/NeedMoneyStatus" + share: + type: + - number + - "null" + format: double + minimum: 0 + maximum: 1 + description: >- + Share of those candidates whose minimum is not above the upper + bound of the range, rounded down to a multiple of 0.25 (one of 0, + 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The + score and the ranking use this rounded value, never the exact + share. A quarter step gives five levels: each probe of a new upper + bound tells at most which quarter of the group accepts it, and in + the smallest allowed group of five candidates a single minimum + often does not move the value, while the share still separates a + range that most candidates accept from one that few accept. + NeedSupplyBand: + type: string + description: >- + Number of available candidates of the category in the allowed + detail: `fewer_than_5`, `from_5_to_29`, or `30_or_more`. Smaller + groups are never counted exactly. + enum: + - fewer_than_5 + - from_5_to_29 + - 30_or_more + NeedCategoryRecommendation: + type: object + description: >- + One recommended category, a specialization with a grade, with its + score and the reasons for it. The score is `0.5 * Overlap + 0.3 * + Money + 0.2 * Supply` (PRD FR08) computed from the published + components: the exact skill overlap, the money share rounded down to a + quarter or the neutral 0.5, and `Supply = min(1, active / 30)` when at + least five candidates are available. For a group of fewer than five, + Supply enters the ranking as 0, the same for every such group, so + neither the score nor the order reveals the exact size of a group + below five. + additionalProperties: false + required: + - specialization + - grade + - score + - skill_overlap + - money + - supply + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + score: + type: + - number + - "null" + format: double + minimum: 0 + maximum: 1 + description: >- + Recommendation score from 0 to 1, rounded half up to two decimals, + or null when `supply` is `fewer_than_5`. Read-only; no request can + set it. + skill_overlap: + $ref: "#/schemas/NeedSkillOverlap" + money: + $ref: "#/schemas/NeedMoneyFit" + supply: + $ref: "#/schemas/NeedSupplyBand" + NeedCategoryRecommendations: + type: object + description: >- + Category recommendations computed by the server from the confirmed + requirements of `requirements_version` with a versioned policy (PRD + FR08). Read-only: no request can set a recommendation, a score, or one + of its components. The server may recompute them for the same + requirements version, for example for a new policy or a changed pool + of available candidates, without a new need version; `computed_at` + and `policy_version` then change. The policy version and the candidate + group used are stored with each computation, so a later policy never + rewrites it. + additionalProperties: false + required: + - status + - requirements_version + - policy_version + - algorithm_version + - computed_at + - categories + properties: + status: + $ref: "#/schemas/NeedRecommendationStatus" + requirements_version: + $ref: "#/schemas/NeedVersion" + policy_version: + type: + - integer + - "null" + format: int32 + minimum: 1 + description: >- + Number of the policy version whose weights were applied, or null + unless `status` is `computed`. + algorithm_version: + description: >- + Version of the recommendation algorithm, or null unless `status` + is `computed`. + oneOf: + - $ref: "#/schemas/NeedVersionLabel" + - type: "null" + computed_at: + description: >- + Time of the computation, or null unless `status` is `computed`. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + categories: + type: array + maxItems: 10 + description: >- + Recommended categories, best first by the score described in + NeedCategoryRecommendation. Empty unless `status` is `computed`. + items: + $ref: "#/schemas/NeedCategoryRecommendation" + Need: + type: object + description: >- + Hiring need of an organization: what the team needs, independent of + any published vacancy. It holds the current version of the + requirements with their provenance, the readiness of the critical + fields, and the category recommendations. It never contains + membership data, a candidate's personal data, or a candidate's salary + minimum. + additionalProperties: false + required: + - id + - organization_id + - vacancy_id + - title + - source_text + - version + - requirements_version + - requirements + - readiness + - recommendations + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the need. + organization_id: + type: string + format: uuid + description: >- + Organization that owns the need, equal to `org_id` of the path. It + never changes. + vacancy_id: + type: + - string + - "null" + format: uuid + description: >- + Linked vacancy of the same organization, or null. A need never + requires a vacancy. + title: + $ref: "#/schemas/NeedTitle" + source_text: + description: Text the requirements were extracted from, or null. + oneOf: + - $ref: "#/schemas/NeedSourceText" + - type: "null" + version: + $ref: "#/schemas/NeedVersion" + requirements_version: + description: >- + Need version in which the current confirmed requirements were last + changed, at most `version`. A change that confirms, changes, or + removes a requirement makes it equal to the new `version`. A change + of the title, the vacancy link, or the text, or of suggestions + only, creates a new `version` but keeps `requirements_version`, so + it invalidates neither the recommendations nor search results and + selection snapshots. Search runs and selection snapshots (PRD FR10) + refer to `(need id, requirements_version)`, and a new selection + snapshot is due only when it changes. + allOf: + - $ref: "#/schemas/NeedVersion" + requirements: + $ref: "#/schemas/NeedRequirementSet" + readiness: + $ref: "#/schemas/NeedReadinessReport" + recommendations: + $ref: "#/schemas/NeedCategoryRecommendations" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + NeedSummary: + type: object + description: >- + Need in a list: its identity, current version, target category + fields, and readiness. Read the need for the requirements and the + recommendations. + additionalProperties: false + required: + - id + - vacancy_id + - title + - version + - specialization + - grade + - readiness + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the need. + vacancy_id: + type: + - string + - "null" + format: uuid + description: Linked vacancy, or null. + title: + $ref: "#/schemas/NeedTitle" + version: + $ref: "#/schemas/NeedVersion" + specialization: + $ref: "#/schemas/NeedSpecialization" + grade: + $ref: "#/schemas/NeedGrade" + readiness: + $ref: "#/schemas/NeedReadinessReport" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + NeedList: + type: object + description: >- + One page of the needs of an organization, newest first by creation + time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Needs of the page. + items: + $ref: "#/schemas/NeedSummary" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + NeedCreate: + type: object + description: >- + New need. Only `title` is required, so a need can start from a title, + from a text, or from form fields, and with or without a vacancy. A + field or list item given here must have `status` `confirmed` and + becomes a confirmed manual value; `extracted` answers 400 with the + pointer of that `status`, such as `/grade/status`, because a new need + has no stored suggestion. A field that is absent is extracted from + `source_text` when the text is given and is left unknown or empty + otherwise. A nullable field sent as null, and a skill or task list sent + as an empty list, stays unknown or empty and is not extracted; an + empty `work_formats` value fails `minItems`. Unknown fields are + rejected, so a request cannot set membership, a role, a status of the + need, a provenance, readiness, a recommendation or its score, or a + candidate's salary minimum. + additionalProperties: false + required: + - title + properties: + title: + $ref: "#/schemas/NeedTitle" + vacancy_id: + type: + - string + - "null" + format: uuid + description: >- + Vacancy of the same organization to link, or null or absent for a + need without a vacancy. + source_text: + oneOf: + - $ref: "#/schemas/NeedSourceText" + - type: "null" + specialization: + oneOf: + - $ref: "#/schemas/NeedSpecializationInput" + - type: "null" + grade: + oneOf: + - $ref: "#/schemas/NeedGradeInput" + - type: "null" + required_skills: + type: array + maxItems: 30 + items: + $ref: "#/schemas/NeedSkillInput" + desired_skills: + type: array + maxItems: 30 + items: + $ref: "#/schemas/NeedSkillInput" + tasks: + type: array + maxItems: 20 + items: + $ref: "#/schemas/NeedTaskInput" + domain: + oneOf: + - $ref: "#/schemas/NeedDomainInput" + - type: "null" + work_formats: + oneOf: + - $ref: "#/schemas/NeedWorkFormatsInput" + - type: "null" + location: + oneOf: + - $ref: "#/schemas/NeedLocationInput" + - type: "null" + salary: + oneOf: + - $ref: "#/schemas/NeedSalaryInput" + - type: "null" + NeedUpdate: + type: object + description: >- + Change of a need over the version the client read. Each field present + in the body replaces that field as a whole; an absent field stays + unchanged. Nested objects and lists are not merged: a field decision + and each list are replaced entirely, and a stored item missing from a + sent list is deleted. A nullable field sent as null becomes unknown, or + unlinked for `vacancy_id`; a skill or task list sent empty deletes + every item; a list sent as null fails validation. A field decision + `{value, status}` and a list item follow the same rules: `confirmed` + with the stored value confirms it and keeps its origin and quote, and + `confirmed` with another value sets a confirmed manual value; + `extracted` keeps a stored suggestion unconfirmed and is allowed only + with exactly the stored suggested value, otherwise it answers 400 with + the pointer of that `status`, such as `/grade/status` or + `/required_skills/0/status`. A client that sends back an unchanged + form therefore confirms nothing by accident: it sends each suggestion + with `extracted`, or leaves the field out. Sending a different + `source_text` extracts again: new suggestions replace only the + `extracted` values and items of fields not named in this body; + confirmed values are never overwritten, a suggested skill whose name is + already in either skill list is skipped, and a suggestion that a + member deleted is not proposed again for this need. Unknown fields are + rejected, so a request cannot set membership, a role, a provenance, + readiness, a recommendation or its score, or a candidate's salary + minimum. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/NeedVersion" + title: + $ref: "#/schemas/NeedTitle" + vacancy_id: + type: + - string + - "null" + format: uuid + description: Vacancy of the same organization to link, or null to unlink. + source_text: + oneOf: + - $ref: "#/schemas/NeedSourceText" + - type: "null" + specialization: + oneOf: + - $ref: "#/schemas/NeedSpecializationInput" + - type: "null" + grade: + oneOf: + - $ref: "#/schemas/NeedGradeInput" + - type: "null" + required_skills: + type: array + maxItems: 30 + items: + $ref: "#/schemas/NeedSkillInput" + desired_skills: + type: array + maxItems: 30 + items: + $ref: "#/schemas/NeedSkillInput" + tasks: + type: array + maxItems: 20 + items: + $ref: "#/schemas/NeedTaskInput" + domain: + oneOf: + - $ref: "#/schemas/NeedDomainInput" + - type: "null" + work_formats: + oneOf: + - $ref: "#/schemas/NeedWorkFormatsInput" + - type: "null" + location: + oneOf: + - $ref: "#/schemas/NeedLocationInput" + - type: "null" + salary: + oneOf: + - $ref: "#/schemas/NeedSalaryInput" + - type: "null" diff --git a/api/core/components/schemas/notification_schemas.yml b/api/core/components/schemas/notification_schemas.yml new file mode 100644 index 0000000..48fa86e --- /dev/null +++ b/api/core/components/schemas/notification_schemas.yml @@ -0,0 +1,131 @@ +schemas: + NotificationKind: + type: string + description: |- + Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. + + - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit. + - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. + + Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content. + enum: + - invitation_delivered + - synthetic + NotificationContent: + type: object + description: >- + The text of a notification as the current source shows it to the + recipient now. It is computed on every read and never stored, so a + hiding, a revoked membership, or a withdrawn source removes it from the + next read. It holds no contact, no score, and no result of an + assessment. + additionalProperties: false + required: + - title + - summary + - link_path + properties: + title: + type: string + minLength: 1 + maxLength: 120 + description: Short heading in Russian. + summary: + type: string + minLength: 1 + maxLength: 500 + description: One or two sentences in Russian. Plain text, never markup. + link_path: + type: + - string + - "null" + maxLength: 256 + pattern: "^/[A-Za-z0-9/_-]{0,255}$" + description: >- + Same-origin absolute path of the screen that the notification + opens, or null when there is none. It has no origin, query, + fragment, or escape; a client opens it only as a path of its own + router. + examples: + - /candidate/invitations + Notification: + type: object + description: >- + One item of the inbox of the current account. Its identity, kind, + organization, delivery time, and read state are stored; its content is + resolved from the current source on every read. + additionalProperties: false + required: + - id + - kind + - organization_id + - delivered_at + - read_at + - content + properties: + id: + type: string + format: uuid + description: >- + Identifier of the item. It equals the identifier of the event that + produced it, so a repeated delivery of the same event is the same + item. + kind: + $ref: "#/schemas/NotificationKind" + organization_id: + type: string + format: uuid + description: >- + The organization context of the item: the organization that sent it + to a candidate, or the organization whose cabinet holds it for an + employer. The identifier is not a right to read the organization. + delivered_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + read_at: + description: >- + When the recipient first marked the item read, or null while it is + unread. A repeated mark keeps the first time. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + content: + description: >- + The current content, or null when the source is gone or the + recipient may not see it now. A client then shows a generic line + such as "The content is no longer available" and never an old + copy. The item stays in the list and can be marked read. + oneOf: + - $ref: "#/schemas/NotificationContent" + - type: "null" + NotificationList: + type: object + description: One page of the inbox, newest delivery first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Items of the page. + items: + $ref: "#/schemas/Notification" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + NotificationReadReceipt: + type: object + description: >- + The read state of one item after a mark. It carries no content, so + marking never reads the source. + additionalProperties: false + required: + - id + - read_at + properties: + id: + type: string + format: uuid + description: Identifier of the marked item. + read_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" diff --git a/api/core/components/schemas/organization_schemas.yml b/api/core/components/schemas/organization_schemas.yml new file mode 100644 index 0000000..7aff4c2 --- /dev/null +++ b/api/core/components/schemas/organization_schemas.yml @@ -0,0 +1,503 @@ +schemas: + OrganizationVersion: + type: integer + format: int64 + minimum: 1 + description: >- + Version of the profile of an organization. Creation makes version 1, + and every committed change of the profile advances it by exactly one. + A change carries the version the client read as `expected_version`. + Only the profile has a version: the memberships and the verification + level of the organization do not advance it. + examples: + - 2 + OrganizationName: + type: string + minLength: 1 + maxLength: 200 + pattern: '^\S(?:[^\n\r]*\S)?$' + description: >- + Public name of the organization, for example the legal name that a + candidate knows. It has no leading or trailing whitespace and no line + breaks, and it is at most 200 characters because consent records keep + a copy of it. Plain text; clients show it as text, never as HTML. A + later rename never changes the copy that a consent record holds. + examples: + - ООО Пример Платежи + OrganizationDescription: + type: string + minLength: 1 + maxLength: 2000 + description: >- + What the organization does, written for candidates. It may contain + line breaks; the server stores CRLF as LF, and it refuses leading and + trailing whitespace and any other control character. Plain text; + clients show it as text, never as HTML. + examples: + - Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + OrganizationSphere: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Field of business of the organization as free text, for example + "Платежи и финансовые сервисы". It has no leading or trailing + whitespace and no line breaks. The product has no sphere taxonomy + yet; a taxonomy code would be an additive field. Plain text; clients + show it as text, never as HTML. + examples: + - Платежи и финансовые сервисы + OrganizationWebsite: + type: string + minLength: 9 + maxLength: 300 + pattern: '^https://[^\s/?#@]+(?:[/?#][^\s]*)?$' + description: >- + Public website of the organization: an https URL with a host name, + without credentials. The server also refuses a port, an IP address, a + host name without a dot, and `localhost`. It never fetches the + address. + examples: + - https://payments.example.com + OrganizationContactChannels: + type: object + description: >- + Public contacts of the organization, the ones a candidate sees on its + card. They are company channels, such as a careers mailbox, the + website, a company phone, or a company Telegram account, and never the + personal email address, phone, or messenger of an employee; personal + contacts of the people of the organization stay out of this object. + The server cannot tell a company address from a personal one, so the + owner answers for the content, and a candidate can complain about an + organization through a support case. The object is the request field + and the stored value alike, so a response can be sent back unchanged; + every field is required and null means not set. A change replaces the + whole object, never a single field of it. + additionalProperties: false + required: + - website + - email + - phone + - telegram + properties: + website: + oneOf: + - $ref: "#/schemas/OrganizationWebsite" + - type: "null" + email: + description: >- + Public mailbox of the organization, such as a careers address, or + null. It is stored in the form it was given. + oneOf: + - $ref: "./identity_schemas.yml#/schemas/EmailAddress" + - type: "null" + phone: + description: Public phone number of the organization, or null. + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactPhoneNumber" + - type: "null" + telegram: + description: Public Telegram account of the organization, or null. + oneOf: + - $ref: "./contact_grant_schemas.yml#/schemas/ContactTelegramUsername" + - type: "null" + OrganizationRepresentative: + type: object + description: >- + A person that speaks for the organization to candidates, as the + owner presents them on the card. It is presentation only: a + representative is not a member of the organization, has no account + link, and gains no right from being listed, and a member does not + become a representative by joining. It holds no contact of the + person; reaching the organization goes through its public contacts. + The name is personal data of an employee that the owner publishes, so + the owner must have the right to do it; see the open questions in the + organization section of the API guide. + additionalProperties: false + required: + - name + - job_title + properties: + name: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Name of the person as the card shows it. It has no leading or + trailing whitespace and no line breaks. Plain text; clients show + it as text, never as HTML. + job_title: + type: string + minLength: 1 + maxLength: 100 + pattern: '^\S(?:.*\S)?$' + description: >- + Position of the person in the organization, for example "Руководитель + по подбору". It has no leading or trailing whitespace and no line + breaks. Plain text; clients show it as text, never as HTML. + OrganizationVerificationLevel: + type: string + description: |- + Trust level of an organization (PRD FR07). It limits the quotas of the organization and, in a planned mode, the access of candidates under 18; it never replaces the consent of a candidate. + + - e0: the confirmed email of the account that created the organization. Every new organization starts here. + - e1: a corporate email, a verified domain, and a link with the organization. + - e2: a check of the requisites and of the authority of the person. + - e3: a manual check or a partner status. + + The server reports e1, e2, or e3 only after a verification process has recorded it for the organization. No request of this contract sets or raises a level, and neither does an edit of the profile, the size of the profile, the number of members, or the domain of an email address. The first slice of the product uses e0 and e1; the processes for e1, e2, and e3 do not exist yet, so a client treats every level other than e0 as unavailable until they do. Adding a level is a contract change. + enum: + - e0 + - e1 + - e2 + - e3 + OrganizationVerificationBasis: + type: string + description: |- + Ground of the current verification level, the reason a cabinet can show next to it. + + - confirmed_email: the confirmed email of the creating account (e0). + - corporate_domain: a corporate email and a verified domain (e1). + - requisites_and_authority: a check of the requisites and of the authority (e2). + - manual_review: a manual check by the platform (e3). + - partner_status: a partner status (e3). + + Each level has its own bases, so a level and a basis that do not belong together never occur. Adding a value is a contract change. + enum: + - confirmed_email + - corporate_domain + - requisites_and_authority + - manual_review + - partner_status + OrganizationVerification: + type: object + description: >- + Verification level of an organization with its ground and the time it + was set. It is read-only everywhere in this contract: the server sets + it, and no request carries it. The scope of the check and the history + of changes (PRD FR07) are planned as additive fields and a separate + history with the first verification process. + additionalProperties: false + required: + - level + - basis + - changed_at + properties: + level: + $ref: "#/schemas/OrganizationVerificationLevel" + basis: + $ref: "#/schemas/OrganizationVerificationBasis" + changed_at: + description: >- + Moment the level was set to its current value; for a new + organization, the creation time. + allOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + CandidateOrganizationCard: + type: object + description: >- + The card of an organization as a candidate sees it: what an invitation + shows before the candidate decides. The server builds it from the + profile and the verification level and returns it to the owner as the + preview of PRD FR07 ("through the eyes of the candidate"); a client + never sends it. It holds no membership, no role, no account, no + version, and no ground of the verification: a member's email address, + the number of members, and the history of the organization stay out of + it. The card is the same object that the candidate side will return + (planned in the invitation contract). Only a candidate who received an + invitation from the organization sees it; it is not a public page, and + no operation shows it to anyone else until the open question about + publishing the names of representatives is decided (152-FZ). The + server may leave `representatives` out, and a card without them means + that the representatives are not published, not that the organization + has none. + additionalProperties: false + required: + - id + - name + - description + - sphere + - contacts + - verification_level + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + $ref: "#/schemas/OrganizationName" + description: + description: Description of the organization, or null. + oneOf: + - $ref: "#/schemas/OrganizationDescription" + - type: "null" + sphere: + description: Field of business of the organization, or null. + oneOf: + - $ref: "#/schemas/OrganizationSphere" + - type: "null" + contacts: + $ref: "#/schemas/OrganizationContactChannels" + representatives: + type: + - array + - "null" + maxItems: 10 + description: >- + Representatives in the order the owner gave them. Absent or null + means that they are not published on this card, which says nothing + about whether the organization has any. + items: + $ref: "#/schemas/OrganizationRepresentative" + verification_level: + $ref: "#/schemas/OrganizationVerificationLevel" + Organization: + type: object + description: >- + Organization as its members read it: the profile that the owner edits, + the verification level that only the server sets, and the card that a + candidate sees. It never contains a role, a membership, the members + of the organization, or an account identifier, so no field of it can + raise a right: the role of the caller is in `OrganizationMembership` + and comes only from the membership held by the server. The profile + fields repeat in `candidate_card`, which is the candidate's view of + them; the client reads the profile fields for the form and + `candidate_card` for the preview. + additionalProperties: false + required: + - id + - version + - name + - description + - sphere + - contacts + - representatives + - verification + - candidate_card + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: >- + Identifier of the organization, the `org_id` of every + organization-scoped path. It never changes. + version: + $ref: "#/schemas/OrganizationVersion" + name: + $ref: "#/schemas/OrganizationName" + description: + description: Description of the organization, or null. + oneOf: + - $ref: "#/schemas/OrganizationDescription" + - type: "null" + sphere: + description: Field of business of the organization, or null. + oneOf: + - $ref: "#/schemas/OrganizationSphere" + - type: "null" + contacts: + $ref: "#/schemas/OrganizationContactChannels" + representatives: + type: array + maxItems: 10 + description: Representatives in the order the owner gave them. + items: + $ref: "#/schemas/OrganizationRepresentative" + verification: + $ref: "#/schemas/OrganizationVerification" + candidate_card: + $ref: "#/schemas/CandidateOrganizationCard" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + OrganizationCreate: + type: object + description: >- + New organization. Only `name` is required, so a company can start with + its name and complete the card later. The creating account becomes the + owner of the organization; the body has no field for a role, a + membership, an owner, a verification level, or a version, and unknown + fields are rejected, so a request cannot set any of them. An absent + `description` or `sphere`, and one sent as null, stay unset; an absent + `contacts` has every contact unset; an absent `representatives` is an + empty list. + additionalProperties: false + required: + - name + properties: + name: + $ref: "#/schemas/OrganizationName" + description: + oneOf: + - $ref: "#/schemas/OrganizationDescription" + - type: "null" + sphere: + oneOf: + - $ref: "#/schemas/OrganizationSphere" + - type: "null" + contacts: + $ref: "#/schemas/OrganizationContactChannels" + representatives: + type: array + maxItems: 10 + items: + $ref: "#/schemas/OrganizationRepresentative" + OrganizationUpdate: + type: object + description: >- + Change of the profile of an organization over the version the client + read. Each field present replaces that field as a whole and an absent + field stays unchanged; `contacts` and `representatives` are replaced + entirely and never merged, and a representative left out of a sent + list is removed. `description` and `sphere` sent as null become unset; + `name`, `contacts`, and `representatives` cannot be null. The body can + change the profile only. It has no field for a role, a membership, an + owner, a verification level, a basis, or a card, and unknown fields + are rejected, so editing the profile can neither raise a right nor + raise the trust level of the organization; both change only through + processes of the server. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: "#/schemas/OrganizationVersion" + name: + $ref: "#/schemas/OrganizationName" + description: + oneOf: + - $ref: "#/schemas/OrganizationDescription" + - type: "null" + sphere: + oneOf: + - $ref: "#/schemas/OrganizationSphere" + - type: "null" + contacts: + $ref: "#/schemas/OrganizationContactChannels" + representatives: + type: array + maxItems: 10 + items: + $ref: "#/schemas/OrganizationRepresentative" + OrganizationRole: + type: string + description: |- + Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile. + + - owner: manages the organization and its members, and acts on behalf of the company. + - recruiter: leads the selection of candidates for all needs. + - hiring_manager: acts on the needs assigned to the member. + - technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations. + + In the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change. + enum: + - owner + - recruiter + - hiring_manager + - technical_expert + MembershipState: + type: string + description: |- + State of a membership. Only `active` gives access: every other state answers as if the account were no member. + + - active: the member works in the organization with the role. + - suspended: access is stopped, and the owner or the platform may restore it. + - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management. + - left: the member ended the membership. + + One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change. + enum: + - active + - suspended + - removed + - left + OrganizationMembership: + type: object + description: >- + The membership of the caller in one organization. The caller is the + account of the session, so the object holds no account identifier. + Only the server sets the role and the state, through the operations + that manage members, which are planned; no operation of this contract + changes them. + additionalProperties: false + required: + - organization_id + - role + - state + - joined_at + properties: + organization_id: + type: string + format: uuid + description: Identifier of the organization. + role: + $ref: "#/schemas/OrganizationRole" + state: + $ref: "#/schemas/MembershipState" + joined_at: + description: >- + Moment the membership was first created. A member who left and + returns keeps the same value, because the pair has one membership; + the moment of the latest activation is a planned additive field + (`activated_at`). + allOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + OrganizationSummary: + type: object + description: >- + An organization in the list of the caller's organizations: what a + switcher needs to name it. The profile, the contacts, and the + representatives are in `Organization`. + additionalProperties: false + required: + - id + - name + - verification_level + properties: + id: + type: string + format: uuid + description: Identifier of the organization, the `org_id` of its paths. + name: + $ref: "#/schemas/OrganizationName" + verification_level: + $ref: "#/schemas/OrganizationVerificationLevel" + MyOrganization: + type: object + description: >- + An organization available to the caller together with the caller's + membership in it. + additionalProperties: false + required: + - organization + - membership + properties: + organization: + $ref: "#/schemas/OrganizationSummary" + membership: + $ref: "#/schemas/OrganizationMembership" + MyOrganizationList: + type: object + description: >- + One page of the organizations available to the caller, newest + membership first. It holds only organizations where the caller has an + `active` membership, so it is also the list of contexts the caller can + work in; it never names an organization the caller cannot enter. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Organizations of the page. + items: + $ref: "#/schemas/MyOrganization" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" diff --git a/api/core/components/schemas/practice_schemas.yml b/api/core/components/schemas/practice_schemas.yml new file mode 100644 index 0000000..10fb7bf --- /dev/null +++ b/api/core/components/schemas/practice_schemas.yml @@ -0,0 +1,189 @@ +schemas: + PracticeRunTest: + type: object + description: >- + One test of the candidate for a debug run: an input and the output the + candidate expects. It is compared with the checker of the task. + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeRunCreate: + type: object + description: >- + Debug run of a practice solution against the public examples of the task + and up to ten tests of the candidate. It never runs a hidden check and + never changes the practice state, the verdict, or the attempt version. + Unknown fields are rejected. + additionalProperties: false + required: + - item_id + - language + - source_code + properties: + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + - type: "null" + source_code: + type: string + minLength: 1 + maxLength: 65536 + tests: + type: array + maxItems: 10 + description: Tests of the candidate, run after the public examples. + items: + $ref: "#/schemas/PracticeRunTest" + PracticeRunState: + type: string + description: |- + State of a debug run. + + - queued: the run waits in the sandbox queue. + - running: the sandbox runs it. + - finished: `result` holds the outcome of the public examples and the tests of the candidate. + - failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run. + + Adding a value is a contract change. + enum: + - queued + - running + - finished + - failed + PracticeRunOutcome: + type: string + description: >- + Outcome of a run or one of its tests. Every outcome caused by the + solution, such as a compilation error, a crash, or a limit, is a + finished run with this outcome; an infrastructure failure is a failed + run instead. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + PracticeRunTestSource: + type: string + description: >- + Where a test of a debug run comes from: a public example of the task or + a test of the candidate. + enum: + - example + - candidate + PracticeRunTestResult: + type: object + description: >- + Outcome of one evaluated test. The tests of a source stop at the first + failed one, so later tests of that source are not listed. + additionalProperties: false + required: + - source + - index + - outcome + - time_ms + - memory_kb + - diagnostic + properties: + source: + $ref: "#/schemas/PracticeRunTestSource" + index: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Position of the test in its source, from 1. + outcome: + $ref: "#/schemas/PracticeRunOutcome" + time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + diagnostic: + description: Truncated error output of a failed test, or null. + oneOf: + - type: string + maxLength: 2048 + - type: "null" + PracticeRunResult: + type: object + description: >- + Result of a debug run on the public examples and the tests of the + candidate. It never contains a hidden check, its outcome, or the score. + additionalProperties: false + required: + - outcome + - compile_diagnostic + - tests + properties: + outcome: + $ref: "#/schemas/PracticeRunOutcome" + compile_diagnostic: + description: The compiler message when `outcome` is `compile_error`, otherwise null. + oneOf: + - type: string + maxLength: 4096 + - type: "null" + tests: + type: array + maxItems: 20 + items: + $ref: "#/schemas/PracticeRunTestResult" + PracticeRun: + type: object + description: >- + Debug run of a practice solution. It shows only the public examples and + the tests of the candidate; hidden checks are never run, listed, or + scored by a debug run. + additionalProperties: false + required: + - id + - item_id + - state + - created_at + - finished_at + - failure_reason + - result + properties: + id: + type: string + format: uuid + description: Identifier of the run. + item_id: + $ref: "./assessment_schemas.yml#/schemas/AssessmentItemId" + state: + $ref: "#/schemas/PracticeRunState" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + finished_at: + description: Time the run reached `finished` or `failed`, or null. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + failure_reason: + description: "`sandbox_error` when `state` is `failed`, otherwise null." + oneOf: + - $ref: "./assessment_schemas.yml#/schemas/PracticeFailureReason" + - type: "null" + result: + description: The result when `state` is `finished`, otherwise null. + oneOf: + - $ref: "#/schemas/PracticeRunResult" + - type: "null" diff --git a/api/core/components/schemas/privacy_schemas.yml b/api/core/components/schemas/privacy_schemas.yml new file mode 100644 index 0000000..ea6555f --- /dev/null +++ b/api/core/components/schemas/privacy_schemas.yml @@ -0,0 +1,705 @@ +schemas: + PublicationVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the publication setting of the candidate. A candidate who + has never published has version 0 and the profile is closed; every + change that alters the setting advances it by one. The client sends + the version it read as `expected_version`. It is independent of the + versions of the profile and of the search status, so a change of one + never makes another stale. + examples: + - 2 + SearchStatusVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the search status of the candidate. A candidate who never + set the status has version 0 and the status `not_looking`; every + confirmation or change advances it by one. The client sends the + version it read as `expected_version`. + examples: + - 3 + CardField: + type: string + description: |- + A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. + + - categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`. + - self_assessment: the candidate's declared specialization and grade, separate from confirmed categories. + - stack: only recognized technology codes from the server's closed taxonomy. + - experience: a coarse total-experience band, without employers, periods, or descriptions. + - work_formats: explicitly selected work formats from the private questionnaire. + - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. + - projects: the projects of the profile with their title, description, stack tags, and whether a linked repository is a public GitHub repository. The titles and descriptions are text that the candidate writes and may identify them; the repository address and its owner never reach an organization through the card. Published projects are also the text that semantic ranking reads and that match explanations name. + - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card. + + Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. + + Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own. + enum: + - categories + - salary_compatibility + - self_assessment + - stack + - experience + - soft_skills + - location + - relocation + - work_formats + - projects + CardFieldSet: + type: array + minItems: 0 + maxItems: 10 + uniqueItems: true + description: >- + Distinct card fields. The server stores them in ascending order of + the codes and answers them in that order, whatever order the client + sent, so equal sets are equal arrays. + items: + $ref: "#/schemas/CardField" + PublicationState: + type: string + description: |- + Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked. + + - closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked. + - published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid. + enum: + - closed + - published + PublicationClosedReason: + type: string + description: |- + Why a closed profile is closed, shown only to the candidate. + + - never_published: the candidate has never published the profile. + - closed_by_candidate: the candidate closed the publication. + - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record. + enum: + - never_published + - closed_by_candidate + - consent_revoked + Publication: + type: object + description: >- + Publication setting of the candidate card. It is separate from the + consent: the C2 consent in the ledger proves that the candidate + accepted the publication text, and this setting records whether and + which fields are published. `state` is `published` only while the + referenced C2 record is unrevoked, whatever the stored setting says, + so a revocation closes the card at once. The state, the fields, and + the times belong to the history that the C2 consent record does not + carry. + additionalProperties: false + required: + - state + - closed_reason + - fields + - consent_id + - published_at + - version + properties: + state: + $ref: "#/schemas/PublicationState" + closed_reason: + description: Why the profile is closed, or null while it is published. + oneOf: + - $ref: "#/schemas/PublicationClosedReason" + - type: "null" + fields: + description: >- + Card fields that organizations may read. Empty exactly when `state` + is `closed`. + allOf: + - $ref: "#/schemas/CardFieldSet" + consent_id: + description: >- + Identifier of the C2 record of the consent ledger that backs the + current or the last publication, the `id` of a `ConsentRecord` of + this account, or null when the profile was never published. + oneOf: + - type: string + format: uuid + - type: "null" + published_at: + description: >- + Moment of the latest change that published or republished the + card, or null while the profile was never published. It stays + after a closing, as the time of the last publication. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + version: + $ref: "#/schemas/PublicationVersion" + PublicationUpdate: + type: object + description: >- + The complete new publication setting. `published` needs a non-empty + set of fields and an active C2 consent of the account; `closed` needs + an empty set and never fails for a missing consent. The body names no + consent: the server binds the publication to the account's current + unrevoked C2 record, and a client can neither supply nor forge one. + additionalProperties: false + required: + - expected_version + - state + - fields + properties: + expected_version: + $ref: "#/schemas/PublicationVersion" + state: + $ref: "#/schemas/PublicationState" + fields: + $ref: "#/schemas/CardFieldSet" + SearchStatusValue: + type: string + description: |- + Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations. + + - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`. + - not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls. + enum: + - looking + - not_looking + SearchStatus: + type: object + description: >- + Search status of the candidate as it holds now. The status `looking` + stores the moment of its confirmation and lapses when the + confirmation interval of the product policy passes without a new + confirmation. A lapse only ever narrows: the status falls to + `not_looking`, which is the non-public state, and a lapse never + changes the publication or the hidden organizations. It needs no + stored change, so no process can make a candidate more visible by + expiry, and a lapsed candidate confirms again explicitly. + additionalProperties: false + required: + - value + - lapsed + - confirmed_at + - lapses_at + - version + properties: + value: + description: >- + The status that holds now: `looking` only while the confirmation + has not lapsed. + allOf: + - $ref: "#/schemas/SearchStatusValue" + lapsed: + type: boolean + description: >- + True when the candidate set `looking`, did not confirm it again, + and the interval ended, so `value` is `not_looking`. False + otherwise, including a status the candidate cleared. + confirmed_at: + description: >- + Moment of the latest confirmation of `looking`, or null when the + candidate never set it or cleared it. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + lapses_at: + description: >- + Moment at which the confirmed status lapses, fixed when it was + confirmed from the `search_status` section of the product policy + version in force then, or null when `confirmed_at` is null. A + later policy change does not move it; it stays in the past for a + lapsed status. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + version: + $ref: "#/schemas/SearchStatusVersion" + SearchStatusUpdate: + type: object + description: >- + The complete new search status. `looking` is also the confirmation of + a status that still holds or has lapsed: it sets the confirmation time + to now. The body carries no time, interval, or policy version; the + server takes them from the effective product policy. + additionalProperties: false + required: + - expected_version + - value + properties: + expected_version: + $ref: "#/schemas/SearchStatusVersion" + value: + $ref: "#/schemas/SearchStatusValue" + PrivacyOrganization: + type: object + description: >- + Organization as the candidate who hid it reads it. The name is the + current name of the organization. The candidate must already have been + able to see the organization to hide it, so the reference tells them + nothing that they could not read before. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: >- + Current name of the organization. Plain text; clients show it as + text, never as HTML. + HiddenOrganization: + type: object + description: >- + One organization that the candidate hides the profile from. The record + belongs to the candidate: no organization reads it, learns that it was + hidden, or can tell a hidden candidate from one who is not published. + additionalProperties: false + required: + - organization + - hidden_at + properties: + organization: + $ref: "#/schemas/PrivacyOrganization" + hidden_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + HiddenOrganizationList: + type: object + description: >- + One page of the organizations that the candidate hides the profile + from, newest first with the organization identifier as the + tie-breaker. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Hidden organizations of the page. + items: + $ref: "#/schemas/HiddenOrganization" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + PrivacySettings: + type: object + description: >- + The visibility settings of the current candidate in one read: the + publication, the search status, and the number of hidden + organizations. The three are independent: each has its own version and + its own operation, and a change of one leaves the others as they were. + A new account reads a closed profile, `not_looking`, and no hidden + organization. + additionalProperties: false + required: + - publication + - search_status + - hidden_organizations_total + properties: + publication: + $ref: "#/schemas/Publication" + search_status: + $ref: "#/schemas/SearchStatus" + hidden_organizations_total: + type: integer + minimum: 0 + maximum: 1000 + description: >- + Number of organizations that the candidate hides the profile from. + The list is read with `ListMyHiddenOrganizations`. + CardCategory: + type: object + description: >- + A category confirmed by assessment results, as the card shows it. + `basis` says what the grade rests on; `synthetic_demo` marks a + demonstration category, which is never a standard confirmation. + additionalProperties: false + required: + - specialization + - grade + - strength + - basis + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + strength: + type: string + enum: + - standard + - strong + description: Coarse strength of the authoritative confirmation. + basis: + $ref: "./evidence_schemas.yml#/schemas/EvidenceBasis" + CardSelfAssessment: + type: object + description: Candidate-declared specialization and optional grade. This is never an assessment result. + additionalProperties: false + required: + - specialization + - confirmation_status + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + confirmation_status: + type: string + enum: + - confirmed + - unconfirmed + declared_grade: + oneOf: + - $ref: "./catalog_schemas.yml#/schemas/GradeCode" + - type: "null" + CandidateExperienceBand: + type: string + description: >- + Coarse total experience bucket. Rare combinations may be generalized to + 0_3 or 3_plus before they are returned. + enum: + - "0_1" + - "1_3" + - "3_6" + - "6_plus" + - "0_3" + - "3_plus" + CandidateWorkFormat: + type: string + enum: + - remote + - office + - hybrid + CandidateSalaryCompatibility: + type: string + description: >- + A coarse compatibility result only. No salary amount, minimum, range, + or threshold is part of the anonymous card. + enum: + - compatible + - not_compatible + CardProject: + type: object + description: >- + One published project as the card shows it. It never carries the + repository address, the repository owner, or any text fetched from the + repository. + additionalProperties: false + required: + - title + - description + - stack + - repository_verified + properties: + title: + type: string + minLength: 1 + maxLength: 100 + description: >- + Project title as the candidate published it. Plain text; show it as + text, never as HTML. + description: + description: >- + Published project description, or null. Plain text; show it as text, + never as HTML. + oneOf: + - type: string + minLength: 1 + maxLength: 500 + - type: "null" + stack: + type: array + maxItems: 10 + description: Published technology tags of the project. + items: + $ref: "./questionnaire_schemas.yml#/schemas/StackTag" + repository_verified: + type: boolean + description: >- + True when the latest server check found the linked repository on + GitHub and it is public. It does not prove that the candidate wrote + the code. + AnonymousCardContent: + type: object + description: >- + The anonymous candidate card as an organization reads it. Only explicitly + published values reach it; unconfirmed stack suggestions and unknown + values never do. Stack output uses a closed taxonomy. It carries no name, + contact, resume text, employer, salary figure, account or + profile identifier, and no schema of the private profile or of a + contact disclosure is reachable from it; a contact reaches an + organization only through the contact grant of an accepted + invitation. Each property is null when its field is not published or + the candidate has no value for it, so the card does not tell the two + apart. The set of properties is closed, and an organization-visible + card must never gain a property that identifies the candidate. The one + free-text exception is `projects`: the candidate writes it and + publishes it by a separate explicit choice, the card never adds the + repository address or owner to it, and the client warns that a project + title can identify its author. The search ranking and the full card of an organization's search result + are defined by the search contract, which reuses this + content. + additionalProperties: false + required: + - pseudonym + - categories + - stack + - self_assessment + - experience_band + - work_formats + - salary_compatibility + - projects + properties: + pseudonym: + type: string + minLength: 47 + maxLength: 47 + pattern: "^cv1_[A-Za-z0-9_-]{43}$" + description: >- + Stable opaque alias scoped to the reading organization. It is not an + account or profile identifier and changes across organizations. + categories: + type: + - array + - "null" + maxItems: 9 + description: Categories confirmed by assessment results, or null. + items: + $ref: "#/schemas/CardCategory" + stack: + type: + - array + - "null" + maxItems: 4 + description: Recognized confirmed technology codes only, or null. + items: + type: string + enum: + - go + - postgresql + - kafka + - docker + self_assessment: + type: + - array + - "null" + maxItems: 9 + description: Candidate-declared specialization and grade, separate from categories. + items: + $ref: "#/schemas/CardSelfAssessment" + experience_band: + oneOf: + - $ref: "#/schemas/CandidateExperienceBand" + - type: "null" + description: Coarse total work-experience bucket, or null. + work_formats: + type: + - array + - "null" + maxItems: 3 + description: Explicitly opted-in work formats, or null. + items: + $ref: "#/schemas/CandidateWorkFormat" + salary_compatibility: + oneOf: + - $ref: "#/schemas/CandidateSalaryCompatibility" + - type: "null" + description: Nullable compatibility result with no salary values. + projects: + type: + - array + - "null" + maxItems: 10 + description: >- + Published projects in the candidate's order, or null. Cohort + generalization never changes them: they are text the candidate + chose to publish, so publishing them can make the card unique. + items: + $ref: "#/schemas/CardProject" + CardPreview: + type: object + description: >- + A private candidate preview computed from the current profile, + publication, and consent ledger. Its pseudonym uses a separate preview + context and is not an organization's alias. Organization-specific + visibility filters and cohort checks can further generalize or suppress + the organization-facing card. This read creates no view or history + record and never reaches an organization. `card` is null while the + profile is closed. `evidence` is what an organization would read in the + evidence section of the card, one supporting assessment fact for each + category of the card, and is null exactly when `card` is null; the + organization-facing section can still be generalized or suppressed. + additionalProperties: false + required: + - state + - fields + - card + - evidence + - generated_at + properties: + state: + $ref: "#/schemas/PublicationState" + fields: + $ref: "#/schemas/CardFieldSet" + card: + oneOf: + - $ref: "#/schemas/AnonymousCardContent" + - type: "null" + evidence: + oneOf: + - $ref: "./evidence_schemas.yml#/schemas/OrganizationEvidence" + - type: "null" + generated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + PrivacyEventKind: + type: string + description: |- + Kind of a change of the visibility settings that the history records. + + - publication_opened: the candidate published a closed profile. + - publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record. + - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here. + - search_status_confirmed: the candidate set or confirmed `looking`. + - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. + - organization_hidden: the candidate hid the profile from an organization. + - organization_unhidden: the candidate lifted the hiding for an organization. + enum: + - publication_opened + - publication_changed + - publication_closed + - search_status_confirmed + - search_status_cleared + - organization_hidden + - organization_unhidden + PrivacyEvent: + type: object + description: >- + One recorded change of the visibility settings of the current + candidate, as evidence of what was published, hidden, or announced and + when. The history is append-only and returns only the caller's own + records. A publication event carries the published fields and the C2 + record behind them; an organization event names the organization; the + other properties are null. + additionalProperties: false + required: + - id + - kind + - occurred_at + - fields + - consent_id + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the event. + kind: + $ref: "#/schemas/PrivacyEventKind" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + fields: + description: >- + Published fields after the change for `publication_opened` and + `publication_changed`, an empty set for `publication_closed`, and + null for every other kind. + oneOf: + - $ref: "#/schemas/CardFieldSet" + - type: "null" + consent_id: + description: >- + C2 record that backs the publication, for `publication_opened` and + `publication_changed`, or null. + oneOf: + - type: string + format: uuid + - type: "null" + organization: + description: >- + Organization of `organization_hidden` and `organization_unhidden` + with its current name, resolved when the history is read (the event + stores only the identifier), or null. + oneOf: + - $ref: "#/schemas/PrivacyOrganization" + - type: "null" + PrivacyEventList: + type: object + description: >- + One page of the settings history of the current candidate, newest + first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Events of the page. + items: + $ref: "#/schemas/PrivacyEvent" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" + CardAccessKind: + type: string + description: |- + How an organization reached the candidate. + + - card_viewed: an organization read the permitted anonymous card. + - contact_read: an organization read the contacts through the contact grant of an accepted invitation. + enum: + - card_viewed + - contact_read + CardAccess: + type: object + description: >- + One access of an organization to the card or the contacts of the + current candidate. A retained access permits the candidate to see the + organization's identifier and current name and to hide their profile + from it. `organization` is null when the organization cannot be + presented. Earlier permitted accesses remain after hiding. The record + carries no employee identity, query, ranking, or search filter of the + organization. + additionalProperties: false + required: + - id + - kind + - occurred_at + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the access record. + kind: + $ref: "#/schemas/CardAccessKind" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + organization: + oneOf: + - $ref: "#/schemas/PrivacyOrganization" + - type: "null" + CardAccessList: + type: object + description: >- + One page of the accesses to the card of the current candidate, newest + first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Accesses of the page. + items: + $ref: "#/schemas/CardAccess" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" diff --git a/api/core/components/schemas/problem_schemas.yml b/api/core/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..bd29634 --- /dev/null +++ b/api/core/components/schemas/problem_schemas.yml @@ -0,0 +1,160 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier, equal to the X-Request-ID response header. Quote + it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - 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, or an `expected_version` field in the request body, does not match the current version; nothing was changed. + - 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. + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later. + 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 + - service_unavailable + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/salary_from`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema), and, + on a state_conflict, `consent_required` (the operation needs a + consent that is not active) and `limit_reached` (a per-account + bound is reached). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/core/components/schemas/questionnaire_schemas.yml b/api/core/components/schemas/questionnaire_schemas.yml new file mode 100644 index 0000000..bb640d4 --- /dev/null +++ b/api/core/components/schemas/questionnaire_schemas.yml @@ -0,0 +1,197 @@ +schemas: + QuestionnaireVersion: + type: integer + format: int64 + minimum: 0 + description: >- + Version of the candidate questionnaire. A candidate without a saved + questionnaire has version 0; every save that changes the questionnaire + advances it by one. + examples: + - 3 + StackTag: + type: string + minLength: 1 + maxLength: 50 + pattern: '^\S(?:.*\S)?$' + description: >- + Free technology tag of the candidate's stack, for example PostgreSQL, + Kubernetes, or Django. A tag is a descriptive attribute: it never + forms a category, never selects the task language, and never changes + a grade, so a tag such as "Senior" has no effect on any category. It + has no leading or trailing whitespace and no line breaks. The server + compares tags without regard to letter case. Clients show tags as + text, never as HTML. + WorkFormat: + type: string + description: "Acceptable work format: `remote`, `office`, or `hybrid`." + enum: + - remote + - office + - hybrid + WorkContext: + type: object + description: >- + Working context of the candidate's search. It holds no personal data + such as an address or a city; location, relocation, and salary + expectations belong to the candidate profile (`ProfileTerms`). The + acceptable work formats live only here: the profile does not repeat + them. + additionalProperties: false + required: + - work_formats + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Acceptable work formats. + items: + $ref: "#/schemas/WorkFormat" + CandidateExperience: + type: object + description: >- + Experience that the candidate states for one specialization, in whole + months. It is self-reported context: it never adds assessment points + and never confirms a grade. The work history entries of the candidate + profile (`ProfileExperienceItem`) are a different, detailed claim: the + two are saved separately and the server neither adds the entries up + nor fills them from these totals. + additionalProperties: false + required: + - commercial_months + - academic_months + properties: + commercial_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of commercial work in the specialization. + academic_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: >- + Months of study, internships, or academic projects in the + specialization. + QuestionnaireSpecialization: + type: object + description: >- + One specialization chosen by the candidate with the candidate's + self-assessment. `self_assessed_grade` is a claim: it influences where + the assessment starts and which grade the assessment step offers + first, but it adds no points and never becomes a confirmed grade. A + confirmed grade, and with it a category, comes only from an assessment + result and is never part of the questionnaire; unknown fields such as + `confirmed_grade` or `category` are rejected. Task languages and the + stack are attributes of the chosen specialization, not categories. The + candidate profile states the same kind of claim in the `roles` of + `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the + questionnaire value starts the assessment and the profile value is what + the profile shows, the two are saved separately, and neither is ever a + confirmed grade. + additionalProperties: false + required: + - specialization + - self_assessed_grade + - task_languages + - stack + - experience + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + self_assessed_grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: >- + Task languages in which the candidate wants to solve assessment + tasks of this specialization. Each value must be one of + `test_availability.task_languages` of the specialization in the + current catalog; any other value answers 400 validation_failed + with a pointer to it. Empty when the bank offers no choice of + language. + items: + $ref: "./catalog_schemas.yml#/schemas/TaskLanguage" + stack: + type: array + maxItems: 20 + uniqueItems: true + description: Technology tags of the candidate in this specialization. + items: + $ref: "#/schemas/StackTag" + experience: + description: >- + Stated experience, or null when the candidate did not state it. + oneOf: + - $ref: "#/schemas/CandidateExperience" + - type: "null" + CandidateQuestionnaire: + type: object + description: >- + Questionnaire of the current candidate: the chosen specializations with + self-assessed grades and the working context. It never contains a + confirmed grade or a category; those come only from assessment + results. A candidate who has not saved the questionnaire yet gets + version 0, no specializations, and null `work_context` and + `updated_at`. + additionalProperties: false + required: + - version + - specializations + - work_context + - updated_at + properties: + version: + $ref: "#/schemas/QuestionnaireVersion" + specializations: + type: array + maxItems: 2 + description: >- + Chosen specializations in the order the candidate gave them, each + specialization at most once. Each one is assessed independently. + items: + $ref: "#/schemas/QuestionnaireSpecialization" + work_context: + description: Working context, or null before the first save. + oneOf: + - $ref: "#/schemas/WorkContext" + - type: "null" + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + CandidateQuestionnaireUpdate: + type: object + description: >- + Complete new state of the questionnaire. It replaces the stored + specializations and working context as a whole. Unknown fields are + rejected, so a request cannot set a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - specializations + - work_context + properties: + expected_version: + $ref: "#/schemas/QuestionnaireVersion" + specializations: + type: array + minItems: 1 + maxItems: 2 + description: >- + One or two chosen specializations. The schema limits the count; the + server also requires each specialization to appear at most once and + answers a repeated one with 400 validation_failed and the pointer + of the repeated item's `specialization`, for example + `/specializations/1/specialization`. + items: + $ref: "#/schemas/QuestionnaireSpecialization" + work_context: + $ref: "#/schemas/WorkContext" diff --git a/api/core/components/schemas/support_schemas.yml b/api/core/components/schemas/support_schemas.yml new file mode 100644 index 0000000..c4c1e8d --- /dev/null +++ b/api/core/components/schemas/support_schemas.yml @@ -0,0 +1,630 @@ +schemas: + SupportCaseNumber: + type: string + minLength: 14 + maxLength: 18 + pattern: "^SC-[0-9]{4}-[0-9]{6,10}$" + description: >- + Human-readable case number that the server assigns on creation, for + example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, + and a sequence number of at least six digits with leading zeros. The + sequence is global and never reused, so the number is unique across + every case and year and never changes. The user quotes it in letters + and calls; the API addresses a case only by its `id`. Clients show the + number as text and never parse it. + examples: + - SC-2026-000123 + SupportCaseType: + type: string + description: |- + Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case. + + - support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts. + - complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts. + - grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts. + - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts. + - manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts. + enum: + - support + - complaint + - grade_appeal + - anticheat_appeal + - manual_assessment + SupportCaseStatus: + type: string + description: |- + Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value. + + - submitted: the case was accepted and waits in its queue. + - in_review: support or a moderator works on it. + - waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status. + - waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time. + - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. + - closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why. + enum: + - submitted + - in_review + - waiting_for_user + - waiting_expert + - resolved + - closed + SupportCaseObjectType: + type: string + description: |- + Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis. + + - assessment_attempt: an assessment attempt of the caller. + - organization: an organization that the caller can see. + - invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found. + - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes. + enum: + - assessment_attempt + - organization + - invitation + - support_case + SupportCaseObjectReference: + type: object + description: >- + Typed reference to an object that the case is about. The server checks + on creation that the caller may see the object; an unknown object and + an object of someone else both answer 404 not_found, so a reference + never reveals whether another person's object exists. The case keeps + only the type and the identifier, never a copy of the object. + additionalProperties: false + required: + - type + - id + properties: + type: + $ref: "#/schemas/SupportCaseObjectType" + id: + type: string + format: uuid + description: Identifier of the object. + SupportCaseAttemptReference: + type: object + description: >- + Reference to an assessment attempt of the caller. Any other object + type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + id: + type: string + format: uuid + description: Identifier of an assessment attempt of the caller. + SupportCaseGradeAppealReference: + type: object + description: >- + Reference to the category that a grade appeal disputes: an assessment + attempt of the caller in a terminal state, or a `manual_assessment` + case of the caller that is `resolved` with the outcome `assessed`, for + a category that an expert assigned without an attempt. Any other object + type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + - support_case + id: + type: string + format: uuid + description: Identifier of the attempt or the case. + SupportCaseComplaintReference: + type: object + description: >- + Reference to the object of a complaint: an organization that the caller + can see or an invitation addressed to the caller. Any other object type + fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - organization + - invitation + id: + type: string + format: uuid + description: Identifier of the organization or the invitation. + SupportCaseAssessmentTarget: + type: object + description: >- + Category that the case is about: a specialization and a grade of the + MVP scale. For a manual assessment it is the category to assess; for a + support case it is optional context, for example the category whose + test is not available. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: "./catalog_schemas.yml#/schemas/SpecializationCode" + grade: + $ref: "./catalog_schemas.yml#/schemas/GradeCode" + SupportCaseComplaintReason: + type: string + description: |- + Ground of a complaint (PRD FR18). + + - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. + - offer_content: misleading or discriminatory content of an offer. Requires an invitation reference. + - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference. + - data_disclosure: a disclosure of the caller's personal data beyond what the caller granted. + - other: another ground, explained in the description. + enum: + - organization_conduct + - offer_content + - salary_terms_violation + - data_disclosure + - other + SupportCaseDescription: + type: string + minLength: 1 + maxLength: 4000 + pattern: \S + description: >- + What the user asks or reports, as the user wrote it. It must contain at + least one character that is not whitespace, so an empty or blank text + fails validation with the pointer `/description`; it may contain line + breaks. The pattern `\S` uses the ECMAScript white space set in both + generated validators: ogen converts it to that set for Go, so a text + made only of spaces such as U+00A0, U+2003, or U+3000 fails in the + server schema and in Zod alike. ECMAScript white space omits U+0085 + (NEL), which Go `unicode.IsSpace` includes; the server therefore also + rejects a text whose every character is `unicode.IsSpace` or U+FEFF, + with the same 400 and the pointer `/description`, while generated Zod + accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server + stores it as written, shows it only to the author and to the staff of + the queue, and never writes it to logs or notifications. Users should + not put passwords or other people's contact data into it. Generated + Zod validators count UTF-16 code units, so the server stays + authoritative for the length. + examples: + - Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + SupportCasePublicText: + type: string + minLength: 1 + maxLength: 4000 + description: >- + Text that support or a moderator wrote for the user: a public reply or + the public reason of a decision. Plain text; clients show it as text, + never as HTML. Internal notes of the staff are never public texts. + SupportCaseCreateSupport: + type: object + description: >- + New support case. Both the object reference and the assessment target + are optional context; omit what does not apply. + additionalProperties: false + required: + - type + - description + properties: + type: + type: string + enum: + - support + description: + $ref: "#/schemas/SupportCaseDescription" + object: + $ref: "#/schemas/SupportCaseObjectReference" + assessment_target: + $ref: "#/schemas/SupportCaseAssessmentTarget" + SupportCaseCreateComplaint: + type: object + description: New complaint about an organization or an offer. + additionalProperties: false + required: + - type + - description + - complaint_reason + - object + properties: + type: + type: string + enum: + - complaint + description: + $ref: "#/schemas/SupportCaseDescription" + complaint_reason: + $ref: "#/schemas/SupportCaseComplaintReason" + object: + $ref: "#/schemas/SupportCaseComplaintReference" + SupportCaseCreateGradeAppeal: + type: object + description: >- + New appeal of a category the caller received: the result of an own + assessment attempt, or the outcome of an own resolved manual + assessment. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - grade_appeal + description: + $ref: "#/schemas/SupportCaseDescription" + object: + $ref: "#/schemas/SupportCaseGradeAppealReference" + SupportCaseCreateAnticheatAppeal: + type: object + description: New appeal of an anti-cheat review decision on an own assessment attempt. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - anticheat_appeal + description: + $ref: "#/schemas/SupportCaseDescription" + object: + $ref: "#/schemas/SupportCaseAttemptReference" + SupportCaseCreateManualAssessment: + type: object + description: >- + New request for a manual assessment of a category by a subject expert. + A prior attempt of the same category is optional context: a failed + first test or no attempt at all never blocks the request. + additionalProperties: false + required: + - type + - description + - assessment_target + properties: + type: + type: string + enum: + - manual_assessment + description: + $ref: "#/schemas/SupportCaseDescription" + assessment_target: + $ref: "#/schemas/SupportCaseAssessmentTarget" + object: + $ref: "#/schemas/SupportCaseAttemptReference" + SupportCaseCreate: + description: >- + New case, selected by `type`. Each type fixes its required fields and + the object types it accepts. The body carries only what the user + states: the request has no status, decision, outcome, priority, + response target, assignee, moderator, rubric, or contact field, and + every variant rejects unknown fields, so a client cannot set any of + them. The user and the account come only from the session. + oneOf: + - $ref: "#/schemas/SupportCaseCreateSupport" + - $ref: "#/schemas/SupportCaseCreateComplaint" + - $ref: "#/schemas/SupportCaseCreateGradeAppeal" + - $ref: "#/schemas/SupportCaseCreateAnticheatAppeal" + - $ref: "#/schemas/SupportCaseCreateManualAssessment" + SupportResponseTarget: + type: object + description: >- + Operational target for the answer to the case (PRD FR18: a case gets a + number, a status, and a response deadline). The server fixes it on + creation from the product policy version and the configured business + calendar; it is a goal of the team, not a deadline set by law. The + target is met by the first public reply, a decision, or a closure for + `support` and `complaint`, and only by a decision or a closure for the + appeals and `manual_assessment`. Missing the target never closes the + case, never decides it, and never changes a grade. + additionalProperties: false + required: + - kind + - business_days + - due_at + - answered_at + - late + - policy_version + properties: + kind: + type: string + enum: + - operational_goal + description: >- + Nature of the target. `operational_goal` is a goal of the team + that clients label as such, never as a legal deadline. + business_days: + type: integer + format: int32 + minimum: 1 + maximum: 60 + description: >- + Length of the target in business days of the policy version, for + example 5 for a manual assessment and 10 for an appeal. + due_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + answered_at: + description: Time the target was met, or null while it is not. + oneOf: + - $ref: "./common_schemas.yml#/schemas/Timestamp" + - type: "null" + late: + type: boolean + description: >- + Whether the target was missed: it was met after `due_at`, or it is + not met and `due_at` has passed at the time of the response. + policy_version: + type: integer + format: int32 + minimum: 1 + description: Number of the `product` policy version that fixed the target. + SupportCaseDecisionOutcome: + type: string + description: |- + Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. + + - upheld: the appeal or the complaint is upheld in full. + - partially_upheld: the appeal or the complaint is upheld in part. + - not_upheld: the appeal or the complaint is not upheld. + - answered: a support case was answered. + - assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case. + enum: + - upheld + - partially_upheld + - not_upheld + - answered + - assessed + SupportCaseDecision: + type: object + description: >- + Decision visible to the user. It exists only once the case is + `resolved`. It holds the outcome and the public reason; it never names + the moderator or the expert and never contains internal notes, + evidence, sanctions against another party, or risk signals. An upheld + grade appeal never rewrites the original result: the corrected result + is a separate decision of the assessment, and both stay in the history + of that attempt. + additionalProperties: false + required: + - outcome + - reason + - decided_at + properties: + outcome: + $ref: "#/schemas/SupportCaseDecisionOutcome" + reason: + $ref: "#/schemas/SupportCasePublicText" + decided_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + SupportCaseActorKind: + type: string + description: |- + Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change. + + - user: the author of the case. + - support: a person of the support, moderation, or expert staff. + - system: the server, for example on creation or when it routes the case. + enum: + - user + - support + - system + SupportCaseEventKind: + type: string + description: |- + Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value. + + - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. + - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. + - reply: support replied; `message` holds the reply and `status` is null. + - decision: a decision was made; `status` is `resolved` and `message` holds the public reason. + enum: + - created + - status_changed + - reply + - decision + SupportCaseEvent: + type: object + description: >- + One public event of the case history. Internal notes, assignments, + evidence requests, and risk signals are never history events. + additionalProperties: false + required: + - sequence + - kind + - actor + - occurred_at + - status + - message + properties: + sequence: + type: integer + format: int32 + minimum: 1 + description: Position of the event in the history, starting at 1 and increasing by one. + kind: + $ref: "#/schemas/SupportCaseEventKind" + actor: + $ref: "#/schemas/SupportCaseActorKind" + occurred_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + status: + description: Status of the case after the event, or null for a reply. + oneOf: + - $ref: "#/schemas/SupportCaseStatus" + - type: "null" + message: + description: Public text of the event, or null. + oneOf: + - $ref: "#/schemas/SupportCasePublicText" + - type: "null" + SupportCase: + type: object + description: >- + Case of the current account. It contains what the author sent, the + public processing state, and the public history. It never contains + the identity of a moderator, an expert, or a support agent, internal + notes, evidence, assessment answers or anti-cheat signals, risk + signals, or contact data of another person. Fields that do not apply + to the type are null. + additionalProperties: false + required: + - id + - number + - type + - status + - description + - object + - assessment_target + - complaint_reason + - rubric_version + - response_target + - decision + - history + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: "#/schemas/SupportCaseNumber" + type: + $ref: "#/schemas/SupportCaseType" + status: + $ref: "#/schemas/SupportCaseStatus" + description: + $ref: "#/schemas/SupportCaseDescription" + object: + description: >- + Object that the case is about, as sent on creation, or null when + the case has none. + oneOf: + - $ref: "#/schemas/SupportCaseObjectReference" + - type: "null" + assessment_target: + description: >- + Category of a manual assessment, the optional category of a + support case, or null. + oneOf: + - $ref: "#/schemas/SupportCaseAssessmentTarget" + - type: "null" + complaint_reason: + description: Ground of a complaint, or null for other types. + oneOf: + - $ref: "#/schemas/SupportCaseComplaintReason" + - type: "null" + rubric_version: + type: + - integer + - "null" + format: int32 + minimum: 1 + description: >- + For a manual assessment, the version of the grading policy pinned + by the server at creation. The exact reviewed category opening and + rubric manifest are retained privately so the expert can use the + same rubric as automated assessment. Null for other types and for a + manual assessment without one unique current reviewed category; the + case still waits in `waiting_expert`. + response_target: + $ref: "#/schemas/SupportResponseTarget" + decision: + description: Decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: "#/schemas/SupportCaseDecision" + - type: "null" + history: + type: array + minItems: 1 + maxItems: 200 + description: >- + Every public event in the order it happened, starting with + `created`; the list is never truncated. The server keeps a case + within 200 events: it rejects a staff reply or status change that + would leave no room for the terminal event, so a case always fits + and can always be resolved or closed. Further correspondence goes + into a new case that references this one as `support_case`. + items: + $ref: "#/schemas/SupportCaseEvent" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + SupportCaseSummary: + type: object + description: >- + Case in a list: the fields that a list of cases shows, without the + description and the history. GetMySupportCase returns the full case. + additionalProperties: false + required: + - id + - number + - type + - status + - object + - assessment_target + - response_target + - decision_outcome + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: "#/schemas/SupportCaseNumber" + type: + $ref: "#/schemas/SupportCaseType" + status: + $ref: "#/schemas/SupportCaseStatus" + object: + description: Object that the case is about, or null. + oneOf: + - $ref: "#/schemas/SupportCaseObjectReference" + - type: "null" + assessment_target: + description: Category of the case, or null. + oneOf: + - $ref: "#/schemas/SupportCaseAssessmentTarget" + - type: "null" + response_target: + $ref: "#/schemas/SupportResponseTarget" + decision_outcome: + description: Outcome of the decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: "#/schemas/SupportCaseDecisionOutcome" + - type: "null" + created_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + updated_at: + $ref: "./common_schemas.yml#/schemas/Timestamp" + SupportCaseList: + type: object + description: One page of the cases of the current account, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Case summaries of the page. + items: + $ref: "#/schemas/SupportCaseSummary" + page: + $ref: "./common_schemas.yml#/schemas/PageInfo" diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index cbc3fde..51f3fd6 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -4,6 +4,35 @@ 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. + - name: catalog + description: 'Public reference data: directions, specializations with their assessment availability, and the grade scale.' + - name: candidate + description: 'Data of the current candidate: the questionnaire with the chosen specializations and self-assessed grades, and the private profile with full name, contacts, stack, roles, experience, soft skills, and desired terms. Confirmed grades and categories come only from assessment results.' + - name: assessment + description: 'Assessment attempts of the current candidate: availability, start and resume, answers and the code practice, finalization, and the result. Answers, keys, and attempt history are visible only to the candidate.' + - name: organization + description: 'Organizations of employer accounts: the profile with its contacts and representatives, the verification level that only the server sets, and the memberships that give an account its role in an organization. The organization in the path is authoritative and is checked against an active membership on every request; no body carries a role, a membership, or a verification level.' + - name: need + description: 'Hiring needs of an organization: requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. Access comes only from an active membership in the organization; a need never requires a vacancy.' + - name: invitation + description: 'Invitations from an organization to one candidate: drafts with complete terms, immutable terms versions, sending, the candidate''s inbox, acceptance with the consent C4, structured declines, withdrawal and cancellation, and the contact grant. Contacts are readable only through an active grant, in a response separate from the terms.' + - name: privacy + description: 'Visibility of the current candidate: the publication of the anonymous card (a setting that refers to the C2 consent of the ledger and never replaces it), the search status that is not a consent, the organizations that the candidate hides the profile from, the preview of the card, and the history of the settings and of the accesses. Everything is closed by default, and no change makes a candidate more visible than they chose. No schema here reaches a contact, a name, or the lowest salary.' + - name: evidence + description: 'Skill evidence derived from confirmed assessment results: one fact per source event with its skills, trust level, attribution, date, and visibility. The candidate reads their own facts; an organization reads only the permitted projection of a currently visible card. Raw answers, failures, and anti-cheat data are never part of it.' + - name: notification + description: 'The in-platform inbox of the current account: references to delivered events with a read state, in the candidate cabinet and in the cabinet of one organization. The inbox is the source of the delivery state inside the platform and never depends on email. It stores no text: the content of every item is resolved from the current source for the recipient on each read, and an item whose source is gone or no longer visible stays in the list without content.' + - name: consent + description: 'The consent ledger of the current account: the independent consents C1-C5 with their text versions, sources, states, and revocations. The ledger is append-only and returns only the caller''s own records.' + - name: support + description: 'Support cases of the current account: questions, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The author sees the number, the status, the response target, the decision, and the public history; moderators and internal notes stay hidden.' paths: /api/v1/healthz: get: @@ -19,8 +48,10996 @@ paths: application/json: schema: $ref: '#/components/schemas/HealthResponse' + examples: + ok: + summary: The process is responding + value: + 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/me/consent-texts/{purpose}: + get: + operationId: GetMyConsentText + summary: Read a current consent text for account settings. + description: 'Requires a verified session. Returns the current published text and version of c1, c2, c3, or c5 so the user can read the exact text before an explicit settings grant. C4 is excluded: its text includes an organization snapshot and it is granted only during invitation acceptance. The response is private and is not cached.' + security: + - sessionCookie: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent whose current text is requested. + schema: + $ref: '#/components/schemas/ConsentSettingsPurpose' + responses: + '200': + description: The current published consent text. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentText' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + 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 plus the pending registration credentials, 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 advances the registration version, replaces the C1 record, invalidates every earlier verification token, and queues a message with a new token carrying the pending password hash, scenario, and onboarding step. The account's saved credentials and scenario change only when the address owner confirms that token with its registration password, so a pre-registration with someone else's password cannot take over the account. + - 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 of the current registration answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid, even when that token is also expired. Neither refusal changes anything. For both, the client offers a new link and sign-in, because the address may already be verified. + + Confirmation also requires the password chosen for the registration that issued this token. A token from a replaced registration cannot apply another registration's password or scenario. The server checks the password against the token's pending password hash before consuming the token, then applies that token's password, scenario, and onboarding step only if the current registration's C1 consent matches its registration version. A wrong password or token without pending registration data answers verification_token_invalid and leaves the account and token unchanged. + + 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. Missing Origin, the special value `null`, or an Origin other than the configured public application origin answers csrf_check_failed. + security: [] + tags: + - identity + parameters: + - name: Origin + in: header + required: false + description: The exact configured public application origin. This optional parameter is read by the server as empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin as an allowed request. + schema: + type: string + minLength: 1 + maxLength: 2048 + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationRequest' + examples: + token: + summary: Token from the link and password chosen during registration + value: + token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE + password: correct horse battery staple + 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/email-verifications/code: + post: + operationId: ConfirmEmailByCode + summary: Verify an email with the six-digit code from the verification message. + description: |- + Public operation without a session. The verification message carries a six-digit code next to the link. The client sends the address, the code, and the password chosen for the registration that issued the code, so the user types only the code after registration. A reloaded page has no password in memory, so it asks for the address, the password, and the code together. + + The server finds the newest open verification token of the unverified account with this normalized address, whose registration is current and which carries a code. It compares the keyed digest of the code with the stored digest, checks the password against the token's pending password hash, and checks that the code has not expired. The code lives 30 minutes, or until the token ends if the token ends sooner. When all three checks pass, the server consumes the token, verifies the email, and applies the pending credentials in one transaction, exactly as the link confirmation does, and answers 200 with the same body. Success does not start a session. + + Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, or a code that was burned. This keeps the answer from showing which addresses have a pending registration. Every failed attempt of an open code counts against that token. The fifth failed attempt burns the token: the code and the link stop working, and the user must request a new message. A refused attempt changes nothing else. + + The same refusal is returned after the rate limits are checked. The operation is limited per client address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with Retry-After. A body that does not match the contract, such as a code that is not six digits, answers 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` otherwise. + security: [] + tags: + - identity + parameters: + - name: Origin + in: header + required: false + description: The exact configured public application origin. This optional parameter is read by the server as empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin as an allowed request. + schema: + type: string + minLength: 1 + maxLength: 2048 + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationCodeRequest' + examples: + code: + summary: Address, code from the message, and the registration password + value: + email: candidate@example.com + code: '482915' + password: correct horse battery staple + 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/EmailVerificationCodeFailed' + '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' + /api/v1/specializations: + get: + operationId: GetSpecializationCatalog + summary: Read the catalog of directions, specializations, and grades. + description: |- + Public operation without a session. Returns the directions with their specializations, the assessment availability of each specialization, and the grade scale. The candidate picks specializations and self-assessed grades from this catalog for the questionnaire, and the client joins the codes stored in the questionnaire with the titles here. + + The catalog is public because it is the same for every caller and contains no personal data: the product shows it before registration, and a public read lets intermediaries and the browser cache it. It reveals nothing beyond what the landing pages already show. + + A category is a specialization together with a confirmed grade. Task languages and the stack are attributes of a chosen specialization and never appear as categories. `test_availability` is derived from the published task banks at the time of the request, so it changes when a bank is published, without a contract change: the MVP opens an assessment only for a category with a published bank, and every other specialization is marked `in_development`. Presence in the catalog never means that its test is ready. + security: [] + tags: + - catalog + responses: + '200': + description: The catalog. + content: + application/json: + schema: + $ref: '#/components/schemas/SpecializationCatalog' + examples: + mvp: + $ref: '#/components/examples/SpecializationCatalog' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/questionnaire: + get: + operationId: GetMyQuestionnaire + summary: Read the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and no specializations rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing questionnaire is not an error state. + + The response never contains a confirmed grade or a category; those come only from assessment results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - candidate + responses: + '200': + description: The questionnaire of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateQuestionnaire' + examples: + new_candidate: + $ref: '#/components/examples/NewCandidateQuestionnaire' + backend_go_and_network_engineer: + $ref: '#/components/examples/BackendGoAndNetworkEngineerQuestionnaire' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + put: + operationId: SaveMyQuestionnaire + summary: Replace the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state: one or two specializations, each with a self-assessed grade, task languages, stack tags, and stated experience or null, and the working context. It replaces the stored questionnaire as a whole. + + Self-assessment is a claim. It influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never writes a confirmed grade or a category: a self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A real profile stays invisible to employers until an assessment confirms a category. Choosing a specialization whose test is `in_development` is allowed; no assessment starts for it until its bank is published. Removing a specialization from the questionnaire does not change assessment results. + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing; the client reads the questionnaire again. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet. The status and code are the same as for a failed If-Match, since the client action is the same. + + The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose specializations and working context equal the stored ones changes nothing, keeps the version, and answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The schema rejects more than two specializations, an unknown grade, specialization, or task language, and unknown fields. The server also rejects a repeated specialization and a task language that the specialization's published bank does not offer, with 400 validation_failed and pointers to the items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. + + A successful save on the onboarding step candidate_questionnaire advances the account to candidate_assessment (planned). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateQuestionnaireUpdate' + examples: + backend_go_and_network_engineer: + $ref: '#/components/examples/BackendGoAndNetworkEngineerQuestionnaireUpdate' + responses: + '200': + description: The saved questionnaire with its new version. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateQuestionnaire' + examples: + backend_go_and_network_engineer: + $ref: '#/components/examples/BackendGoAndNetworkEngineerQuestionnaire' + '400': + $ref: '#/components/responses/QuestionnaireValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '412': + $ref: '#/components/responses/QuestionnaireVersionConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/profile: + get: + operationId: GetMyProfile + summary: Read the private profile of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the profile yet gets 200 with version 0, every single field `unknown`, and empty lists rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing profile is not an error state. + + The profile is personal data that only its owner reads: full name, contacts, work history, and the lowest salary. It is a private resource and never an organization-visible one; organizations see a candidate through the anonymous card and, after an accepted invitation, through the contact grant, and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and the server never writes its values to logs, metrics, URLs, or events. + + Every value carries its confirmation state and provenance, and every claim has trust level 0. The self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results establish and which no request writes. The profile needs no file, no ML extraction, and no FSP account. + + `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices refer to this response's `experience` array and are scoped to the same `version`; each pair is either `needs_confirmation` or `confirmed`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - candidate + responses: + '200': + description: The private profile of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateProfile' + examples: + new_candidate: + $ref: '#/components/examples/NewCandidateProfile' + backend_manual_with_suggestion: + $ref: '#/components/examples/BackendCandidateProfile' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + put: + operationId: SaveMyProfile + summary: Replace the private profile of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state of every field and list; see CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole. + + Every field is optional in substance: a profile can be saved with any subset filled and the rest null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or link. A successful save advances an account whose current onboarding step is candidate_profile to candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update is atomic with the profile and its history. + + Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level, confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed grade never becomes a confirmed grade or a category. + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing, and the client reads the profile again and reapplies its edits, so a concurrent edit from another tab or device is never lost silently. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for the questionnaire; the status and code are the same as for a failed If-Match. + + The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose values equal the stored ones, with the same decisions, changes nothing, keeps the version, and answers 200 with the current profile even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. A version above the current one never existed and always answers 412 version_conflict, even for an unchanged body. + + The save replaces the stored claims as a whole. A suggestion that an import stored and that the client did not render and send back with the decision `extracted` is dropped by the save; a client therefore sends every suggestion that it received, and a client that read an older version gets 412 instead of silently dropping a suggestion it never saw. + + Experience periods use inclusive calendar months. An overlap is allowed only when `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel work. Each acknowledgement names two distinct experience indices and repeats their exact normalized `started_on` and `ended_on` values; both indices and periods must match the submitted array and `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries an earlier acknowledgement only when the same two indices still contain the same dates; reordering or changing either date requires a new acknowledgement. Editing other experience fields does not invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping acknowledgements are invalid. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims against the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when `expected_version` is stale, because another save may have confirmed that value, and 400 when it is current; an unchanged body (200); any other change over a stale version (412). The schema rejects an unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is not a positive multiple of 1000, and more items than a list allows. The server also rejects a repeated tag, skill, or role specialization, a period that ends before it starts or lies in the future, a changed overlap without explicit confirmation, and a decision `extracted` for a value that is not a stored suggestion, with 400 validation_failed and pointers to the items, for example `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateProfileUpdate' + examples: + backend_manual: + $ref: '#/components/examples/BackendCandidateProfileUpdate' + responses: + '200': + description: The saved profile with its new version, or the current profile when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateProfile' + examples: + backend_manual_with_suggestion: + $ref: '#/components/examples/BackendCandidateProfile' + '400': + $ref: '#/components/responses/ProfileValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '412': + $ref: '#/components/responses/ProfileVersionConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/profile/repository-checks: + post: + operationId: RequestMyRepositoryChecks + summary: Ask the server to check the linked project repositories again. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body. It schedules a new check of every repository that the current profile links, for example after the candidate made a repository public, and answers 202 with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0. + + A check reads only public metadata from the public GitHub API (`api.github.com`): whether the repository exists and is public, its description, topics, languages, and the beginning of its README as plain text. The server never fetches any other host, never follows a redirect to another host, and never shows the fetched text; it uses it only for semantic ranking. A verified repository does not prove that the candidate wrote the code. + + The operation is limited per candidate: a second request inside the versioned window answers 429 rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + responses: + '202': + description: The checks are scheduled. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ProfileRepositoryCheckRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-availability: + get: + operationId: GetMyAssessmentAvailability + summary: Read which assessment attempts the current candidate can start. + description: |- + Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. + + `insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - assessment + responses: + '200': + description: Assessment availability of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAvailability' + examples: + backend_and_network_engineer: + $ref: '#/components/examples/AssessmentAvailability' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-results: + get: + operationId: ListMyAssessmentResults + summary: List immutable real assessment results of the current candidate. + description: |- + Requires a candidate session. Returns only completed root and corrective results owned by this candidate, newest first by decided_at and attempt_id. demo_express training results never appear. The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns 400 validation_failed. + + A v2 result includes the category decision captured when that attempt ended, including the confirmed grade then in force. Legacy v1 results omit category_decision because a later category must not be projected backward. Later policy, bank, review, or category changes do not alter either result. Employers cannot read this history; their separate projection contains only the current permitted category and no answers. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - name: limit + in: query + required: false + description: Maximum number of results per page. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 50 + default: 20 + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: One owner-scoped page of immutable results. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentResultHistoryPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-signal-notice: + get: + operationId: GetMyAssessmentSignalNotice + summary: Read whether the current candidate acknowledged the signal notice. + description: |- + Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The notice also lists the measures that the page applies during a real attempt: fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste into answer fields (paste into the practice code editor is allowed and recorded as a signal with a size only). A watermark on the task page is announced as planned. These measures are applied by the client and never change a score, a category, or a quota. The client shows the notice before a real attempt starts and does not start the attempt until the notice is acknowledged. + + The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. An acknowledgement of an earlier version never counts for the current one: when the text gains a version, every candidate acknowledges it again. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or an unconfirmed email answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - assessment + responses: + '200': + description: The notice version and the acknowledgement state of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalNotice' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + put: + operationId: AcknowledgeMyAssessmentSignalNotice + summary: Record that the current candidate read the signal notice. + description: |- + Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body carries the notice version the candidate was shown. The server stores the acknowledgement for the account and that version; the response carries the server time of the first acknowledgement. + + The operation needs no Idempotency-Key: it is idempotent. Repeating it for an acknowledged version changes nothing, keeps the first time, and answers 200, so a retry after a lost response succeeds. A version other than the one the server requires answers 409 state_conflict and stores nothing; the client reads the notice again. + + The acknowledgement is not a consent. It does not grant, replace, or hide C3, and it does not affect the signal operation or any score, category, or quota. The body carries no signal, answer, or clipboard data. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account (403 forbidden), then the version (409). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalNoticeAcknowledgement' + responses: + '200': + description: The stored acknowledgement, new or repeated. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalNotice' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '409': + $ref: '#/components/responses/StateConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts: + post: + operationId: CreateMyAssessmentAttempt + summary: Start a real, corrective, or training assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real assessment names a specialization, target grade, and task language; the server picks `demo_basic` or `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 minutes, has no category or target grade, and creates no qualification evidence or percentile. Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + + A specialization has at most one active real attempt. A new root attempt cannot start while one is active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its root, target a strictly lower grade not already attempted in that chain, and remain inside the root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its own item, practice, and session limits, but spends no additional root slot and cannot reset the chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can be tested at once. An expired or incomplete attempt does not create a free new chain; an insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside real-assessment availability, quotas, retry intervals, and qualification history. + + The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no work command. For a corrective attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits the attempt is also bounded by the item limit of its policy. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttemptCreate' + examples: + backend_junior_go: + $ref: '#/components/examples/AssessmentAttemptCreateBackendJunior' + corrective_backend_junior_go: + summary: Start a lower-grade assessment inside an existing correction chain + value: + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + demo_express: + summary: Start a short educational training run + value: + kind: demo_express + responses: + '201': + description: The attempt was created, or a retry with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + demo_basic_created: + $ref: '#/components/examples/AssessmentAttemptCreated' + corrective_created: + $ref: '#/components/examples/AssessmentCorrectiveAttemptCreated' + demo_express_created: + $ref: '#/components/examples/AssessmentExpressAttemptCreated' + '400': + $ref: '#/components/responses/AssessmentAttemptCreateValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '409': + $ref: '#/components/responses/AssessmentCreateConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}: + get: + operationId: GetMyAssessmentAttempt + summary: Read an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the stored attempt projection with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. This GET is read-only: it never starts or resumes a work session, consumes session quota, advances the version, or commits expiry or finalization. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + + When the deadline passes, this read still returns the stored state and deadline. A command or background transition commits the due outcome; if the stored state is still active, GetMyAssessmentResult answers 409 until that transition is committed. The client polls this operation while a practice is `pending`, but polling alone never changes attempt state. + + The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + responses: + '200': + description: The attempt. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + adaptive_resumed: + $ref: '#/components/examples/AssessmentAttemptResumed' + practice_pending: + $ref: '#/components/examples/AssessmentAttemptPracticePending' + practice_verdict_pending: + $ref: '#/components/examples/AssessmentAttemptPracticeVerdictPending' + sandbox_failed: + $ref: '#/components/examples/AssessmentAttemptSandboxFailed' + ready_to_finalize: + $ref: '#/components/examples/AssessmentAttemptReadyToFinalize' + additional_practice_pending: + $ref: '#/components/examples/AssessmentAttemptAdditionalPracticePending' + completed: + $ref: '#/components/examples/AssessmentAttemptCompleted' + insufficient_bank: + $ref: '#/components/examples/AssessmentAttemptInsufficientBank' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/sessions: + post: + operationId: StartMyAssessmentAttemptSession + summary: Start or resume a work session for the current candidate's attempt. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version the candidate last read. The server checks ownership, idempotency, and `expected_version` atomically before starting a session; a stale version answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the stored response. + + Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this command to start the next session. Calling it while a session is already active returns the current attempt without consuming another session or advancing its version. Starting a session advances the version once. The command cannot extend `expires_at` or `chain_deadline`. + + If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it. + + One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in another window. That refusal is not stored under the Idempotency-Key, because it lasts only until the other page closes or stops renewing. A real attempt that nobody holds is not refused. + + The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + - $ref: '#/components/parameters/AttemptClient' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttemptSessionStart' + example: + expected_version: 7 + responses: + '200': + description: The current attempt after starting or resuming work, or after a due terminal transition was committed. A replay returns the stored body. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + resumed: + $ref: '#/components/examples/AssessmentAttemptResumed' + terminal: + $ref: '#/components/examples/AssessmentAttemptCompleted' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentCommandConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/signals: + post: + operationId: RecordMyAssessmentAttemptSignals + summary: Store a bounded batch of client-reported assessment signals. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt, remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks every item_instance_id against that attempt, and commits the receipt and any events in one transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express remains a separate training mode and receives no signal storage or grade effect. + + The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents, arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers. Client timestamps must be within five minutes before attempt creation and five minutes after the database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed with the assessment attempt or account; this release does not promise an independent expiry schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses. + + A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt without storing another batch; using that key with another body answers 422. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalBatch' + responses: + '200': + description: The stored or replayed receipt. A saturated receipt explicitly says that none of this batch's events was stored. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentSignalReceipt' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '413': + $ref: '#/components/responses/PayloadTooLarge' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/work-session: + put: + operationId: HoldMyAssessmentWorkSession + summary: Hold the single active work session of a real assessment attempt for this page. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page at a time. The page that works on the attempt calls this operation when the candidate starts or resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until `held_until`. + + - If nobody holds the work session, the previous holder released it, or its hold expired, the page becomes the holder and the answer is 200. + - If the same page holds it, the hold is renewed and the answer is 200. + - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops renewing and its hold expires. The client tells the candidate that the attempt is open in another window and does not show the task. + + The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a candidate who closes a page, reloads, or opens the attempt on another device can continue when the hold is released or has expired (at most two minutes after the last renewal). It is not a security boundary: a client that never calls this operation is refused only while another page holds the session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound to the attempt; it never stores or returns either value. A change of the User-Agent digest during an attempt is a weak server signal for a manual review, never an automatic decision. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the hold (409 state_conflict). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/AttemptClientRequired' + responses: + '200': + description: The page holds the work session until `held_until`. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentWorkSession' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: ReleaseMyAssessmentWorkSession + summary: Release the work session that this page holds. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can open the attempt in another window at once instead of waiting for the hold to expire. The request is idempotent and reveals nothing: it answers 204 whether this page held the session, another page holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a lost response succeeds. A page that is killed without calling it loses the hold within two minutes. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the release (204). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/AttemptClientRequired' + responses: + '204': + description: This page no longer holds the work session. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/answers: + post: + operationId: SubmitMyAssessmentAnswer + summary: Answer the current item or submit a practice of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + + Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. + + The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + + A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. + + Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. + + One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not stored under the Idempotency-Key and is checked before the stored answer is replayed. + + Repeats and conflicts, per item: + - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. + - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. + - A different answer for an item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412. + - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline transition may be committed, but this request never starts a work session), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + - $ref: '#/components/parameters/AttemptClient' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAnswerSubmission' + examples: + choice: + $ref: '#/components/examples/AssessmentChoiceAnswer' + order: + $ref: '#/components/examples/AssessmentOrderAnswer' + number: + $ref: '#/components/examples/AssessmentNumberAnswer' + string: + $ref: '#/components/examples/AssessmentStringAnswer' + find_error: + $ref: '#/components/examples/AssessmentFindErrorAnswer' + configuration: + $ref: '#/components/examples/AssessmentConfigurationAnswer' + practice: + $ref: '#/components/examples/AssessmentPracticeAnswer' + responses: + '200': + description: The answer was stored, or this exact answer was already stored, and the response is the attempt with the next item. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + accepted: + $ref: '#/components/examples/AssessmentAnswerAccepted' + practice_submitted: + $ref: '#/components/examples/AssessmentAttemptPracticeVerdictPending' + '400': + $ref: '#/components/responses/AssessmentAnswerValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentCommandConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs: + post: + operationId: CreateMyAssessmentPracticeRun + summary: Start a debug run of a practice solution. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the practice item of the attempt and carries the language, the source, and up to ten tests of the candidate. + + A debug run executes the solution in the isolated sandbox against the public examples of the task and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes neither the practice state, the verdict, nor the attempt version; the graded solution is submitted with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed asynchronously: the response is 202 with the run `queued`, and the client polls GetMyAssessmentPracticeRun. The source is never echoed. + + The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. + + Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten waiting runs and submissions together; when it is full the server answers 503 service_unavailable with Retry-After and stores nothing. When code practice is not enabled on this server, the server answers 503 service_unavailable without Retry-After and stores nothing. + + Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), the solution against the item (400 with a pointer such as `/language` or `/source_code`), the limits (429), then the queue (503). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PracticeRunCreate' + examples: + run: + summary: A Python solution with one test of the candidate. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + language: python + source_code: | + print(sum(map(int, input().split()))) + tests: + - input: | + 2 3 + expected_output: | + 5 + responses: + '202': + description: The run is queued, or this request was already accepted and the stored run is returned. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PracticeRun' + examples: + queued: + summary: A queued run. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: queued + created_at: '2026-10-05T09:30:00Z' + finished_at: null + failure_reason: null + result: null + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}: + get: + operationId: GetMyAssessmentPracticeRun + summary: Read a debug run of a practice solution. + description: |- + Requires the session cookie of a candidate account. Returns the state of a debug run started with CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. This GET is read-only. + + A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is not readable here. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - name: run_id + in: path + required: true + description: Identifier of a debug run of this attempt. + schema: + type: string + format: uuid + responses: + '200': + description: The run. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PracticeRun' + examples: + finished: + summary: A finished run whose test of the candidate failed. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: finished + created_at: '2026-10-05T09:30:00Z' + finished_at: '2026-10-05T09:30:04Z' + failure_reason: null + result: + outcome: wrong_answer + compile_diagnostic: null + tests: + - source: example + index: 1 + outcome: accepted + time_ms: 21 + memory_kb: 9216 + diagnostic: null + - source: candidate + index: 1 + outcome: wrong_answer + time_ms: 20 + memory_kb: 9180 + diagnostic: null + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/finalize: + post: + operationId: FinalizeMyAssessmentAttempt + summary: Ask for the grade decision of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + + Finalize is a work command and requires an active session. After `idle_timeout_seconds` of inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest `expected_version`; finalize never starts a session. GET attempt and result operations do not change state. A command or background transition may commit a due deadline outcome. + + Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: + - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. + - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. + - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. + + A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it. + + An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentFinalization' + examples: + finalize: + $ref: '#/components/examples/AssessmentFinalization' + responses: + '200': + description: 'The attempt after the decision: `completed`, with the result available from GetMyAssessmentResult, or `additional_practice_pending` when an adaptive attempt offers an additional practice.' + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentAttempt' + examples: + demo_basic_completed: + $ref: '#/components/examples/AssessmentAttemptCompleted' + additional_practice_offered: + $ref: '#/components/examples/AssessmentAttemptAdditionalPracticePending' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentFinalizeConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/result: + get: + operationId: GetMyAssessmentResult + summary: Read the result of an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, bank, and algorithm versions, decision, previously confirmed grade, calibration status and limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time as a separate label, and allowed next steps. A corrective result also carries the root attempt and its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later policy, bank, or algorithm version never changes a result. + + Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. + + An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. This GET is read-only and never commits a due transition. If a deadline has passed but the due transition is not yet stored by a command or background worker, the attempt remains active for this read and answers 409; wait for the transition and retry. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + responses: + '200': + description: The result. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentResult' + examples: + demo_basic: + $ref: '#/components/examples/AssessmentDemoBasicResult' + adaptive_confirmed: + $ref: '#/components/examples/AssessmentAdaptiveResult' + adaptive_not_confirmed: + $ref: '#/components/examples/AssessmentNotConfirmedResult' + insufficient_bank: + $ref: '#/components/examples/AssessmentInsufficientBankResult' + corrective: + $ref: '#/components/examples/AssessmentCorrectiveResult' + demo_express: + $ref: '#/components/examples/AssessmentExpressResult' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentResultNotReady' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/organizations: + get: + operationId: ListMyOrganizations + summary: List the organizations available to the current account. + description: |- + Requires the session cookie of an employer account. The account comes from the session, never from a request parameter, so the response holds only the caller's own memberships and no request can name another account. + + Returns a page of the organizations in which the caller has an `active` membership, newest membership first with the organization identifier as the tie-breaker, with cursor pagination. Each item names the organization (`OrganizationSummary`) and holds the caller's role and state in it (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not list its organization, so an organization the caller cannot enter is never named, and one that the caller was removed from disappears from the list at once. + + The list is the directory of the active organization context. The context is not stored on the server: every organization-scoped operation names its organization in the path `org_id`, and the server checks that identifier against the caller's active membership on every request, so a switch between organizations is a different `org_id` in the client's routes and cannot outlive a revoked membership. A client picks the context from this list, may remember the last choice in the browser as a convenience, and must read the list again after any answer 404 `not_found` from an organization path. An account with several memberships sees all of them here and works in one at a time; the rights and the data of the organizations stay separate. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden. An employer account without an organization gets an empty page, which tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - organization + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the organizations available to the current account. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/MyOrganizationList' + examples: + one_organization: + $ref: '#/components/examples/MyOrganizationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations: + post: + operationId: CreateOrganization + summary: Create an organization; the caller becomes its owner. + description: |- + Requires the session cookie of an employer account with a confirmed email, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the session: the body has no owner, membership, role, verification, or version field, and unknown fields fail validation. + + The server creates the organization and the owner membership of the caller (role `owner`, state `active`) in one transaction, so an organization never exists without its owner. The organization starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be requested: the creator of a company with a corporate domain, a long description, or many representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of the server that do not exist yet. Only `name` is required; the rest of the card can be completed with UpdateOrganization. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second organization. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. Two requests with different keys are two organizations; the product may limit the number of organizations per account (open question), which would answer 409 `state_conflict` without a change of the schema. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a website that is not an https URL of a host name, `/name` for a name with surrounding whitespace). The general rate limit can answer 429 with Retry-After before any check; 429 is never stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - organization + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationCreate' + examples: + name_only: + $ref: '#/components/examples/OrganizationCreateNameOnly' + complete_card: + $ref: '#/components/examples/OrganizationCreateCompleteCard' + responses: + '201': + description: The organization was created with the caller as its owner, or a retry with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Organization' + examples: + name_only: + $ref: '#/components/examples/OrganizationNameOnly' + complete_card: + $ref: '#/components/examples/OrganizationCompleteCard' + '400': + $ref: '#/components/responses/OrganizationValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '409': + $ref: '#/components/responses/IdempotencyInProgress' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}: + get: + operationId: GetOrganization + summary: Read an organization managed by the caller. + description: |- + Requires the session cookie of a verified employer account with an active owner membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing. + + Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - organization + parameters: + - $ref: '#/components/parameters/OrganizationId' + responses: + '200': + description: The organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Organization' + examples: + name_only: + $ref: '#/components/examples/OrganizationNameOnly' + complete_card: + $ref: '#/components/examples/OrganizationCompleteCard' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + patch: + operationId: UpdateOrganization + summary: Change the profile of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the organization (the FR07 matrix gives this to no other role), so a member with another role answers 403 forbidden. The role comes from the server-side membership; the body has no organization, membership, role, owner, or verification field. + + Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. + + The body can change the profile only. The verification level, its basis, the card, the members, and every role are not fields of it, and unknown fields fail validation, so the owner can neither raise the trust level of the organization nor the rights of anyone by editing the profile; a longer description, a verified-looking website, or a new representative leaves the level unchanged. The level and the roles change only through processes of the server. + + Versions: every committed change creates version `expected_version + 1` and answers 200 with the organization. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the organization again and reapplies its edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for needs. A body that changes nothing when applied to the current profile keeps the version and answers 200 with the current organization even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a change that already succeeded is harmless. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403 forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - organization + parameters: + - $ref: '#/components/parameters/OrganizationId' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationUpdate' + examples: + complete_card: + $ref: '#/components/examples/OrganizationUpdateCompleteCard' + responses: + '200': + description: The organization after the change, or the current organization when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Organization' + examples: + complete_card: + $ref: '#/components/examples/OrganizationCompleteCard' + '400': + $ref: '#/components/responses/OrganizationValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '412': + $ref: '#/components/responses/OrganizationVersionConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/needs: + get: + operationId: ListOrganizationNeeds + summary: List the needs of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the membership that the server holds for the session account, never from the request. In the MVP only the owner of the organization works with needs; the other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of this contract. The list holds only the needs that the role may read. + + Returns a page of need summaries, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. A summary has the current version, the target specialization and grade with their confirmation state, and the readiness; GetOrganizationNeed returns the requirements and the recommendations. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member whose role does not allow reading needs answers 403 forbidden. A malformed `org_id`, `limit`, or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - need + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the needs of the organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NeedList' + examples: + last_page: + $ref: '#/components/examples/NeedListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + post: + operationId: CreateOrganizationNeed + summary: Create a need of an organization from a form, a text, or both. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The organization comes from the path and the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization may create a need; the other roles of PRD FR07 are planned. + + A need does not require a vacancy: `vacancy_id` is optional and nullable. When it is given, it must name a vacancy of the same organization; until vacancies exist in the contract, any vacancy identifier answers 400 with the pointer `/vacancy_id`, the same for an unknown vacancy and one of another organization. + + Only `title` is required. A field is sent as a decision `{value, status}` and a list item as `{name or text, status}`; on creation the status must be `confirmed`, and the value becomes a confirmed manual value. When `source_text` is given, the server extracts suggestions for the absent fields with deterministic rules and a dictionary before it answers, so creation works while the ML service is disabled; every suggestion has the status `extracted`, the origin extracted_from_text, a quote where the extractor found one, and the extractor version, and it waits for a member to confirm it. A field that the text does not state stays `unknown` with null value and source; the server never guesses a grade, a format, or a salary. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value. + + The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation. + + Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer: `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/required_skills/1/name` for a repeated skill, `/grade/status` or `/required_skills/0/status` for `extracted`, which a new need cannot have, or `/vacancy_id`), then the salary limit (429). The schema already rejects unknown fields such as `rec_score`, `members`, or `candidate_minimum`, a field sent as a bare value instead of `{value, status}`, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. The general rate limit can answer 429 with Retry-After before any check. 429 is never stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - need + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NeedCreate' + examples: + manual_without_vacancy: + $ref: '#/components/examples/NeedCreateManual' + from_text: + $ref: '#/components/examples/NeedCreateFromText' + responses: + '201': + description: The need was created as version 1, or a retry with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Need' + examples: + manual_without_vacancy: + $ref: '#/components/examples/NeedManualWithoutVacancy' + from_text_with_unknown_skill: + $ref: '#/components/examples/NeedExtractedWithUnknownSkill' + '400': + $ref: '#/components/responses/NeedValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/IdempotencyInProgress' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/needs/{need_id}: + get: + operationId: GetOrganizationNeed + summary: Read the current version of a need of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the server-side membership, never from the request. In the MVP only the owner of the organization reads needs; the other roles of PRD FR07 are planned. + + Returns the current version of the need: `version`, the requirements with the confirmation state and provenance of each field (`status`, and `source` with the origin, the quote, the version whose text the quote belongs to, and the extractor version), the readiness with `missing_fields`, and the category recommendations of the server. A field with status `unknown` has null value and source; an `extracted` value is a suggestion that waits for confirmation and never feeds search or recommendations. + + Versions: every committed change creates a new immutable `version`, and this operation always returns the latest one. `requirements_version` is the version in which the confirmed requirements were last changed; a change of the title, the vacancy link, the text, or suggestions only keeps it. Search runs, selection snapshots, and invitations refer to a need by its identifier and `requirements_version`, so they keep the requirements they used, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions (PRD FR10) are planned as separate operations that return the same NeedRequirementSet for a given version; they add no field here. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown need, and a need of another organization all answer 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the need answers 403 forbidden. An `org_id` or `need_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - need + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/NeedId' + responses: + '200': + description: The current version of the need. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Need' + examples: + manual_without_vacancy: + $ref: '#/components/examples/NeedManualWithoutVacancy' + from_text_with_unknown_skill: + $ref: '#/components/examples/NeedExtractedWithUnknownSkill' + confirmed: + $ref: '#/components/examples/NeedConfirmedAfterUpdate' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + patch: + operationId: UpdateOrganizationNeed + summary: Confirm, change, or delete requirements of a need. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The organization and the role come from the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization changes needs; the technical expert, who may refine the requirements of assigned needs under PRD FR07, is planned. + + Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; a field decision and each list are replaced entirely and never merged. This keeps every field one optional value in the generated server and client, without nested partial updates. + + Each requirement field is sent as a decision `{value, status}` and each list item as `{name or text, status}`, so confirmation is always explicit: + - Confirm a suggestion: send its stored value with `confirmed`. It keeps its origin and quote. + - Keep a suggestion open: send its stored value with `extracted`, or leave the field out. `extracted` with any other value, or for a field or item without a stored suggestion, answers 400 with the pointer of that `status`, for example `/grade/status` or `/required_skills/2/status`. A client that sends back an unchanged form therefore never confirms a suggestion by accident. + - Change: send another value with `confirmed`. It becomes a confirmed manual value, and its quote is dropped. + - Delete: send null for a nullable field, which makes it `unknown` (or unlinks `vacancy_id`), or leave the item out of a skill or task list, which deletes it. An empty skill or task list deletes every item; a list sent as null answers 400. A deleted requirement really changes the requirements that search uses, not only an explanation, and a deleted suggestion is not proposed again by a later extraction. + - Text: a different `source_text` extracts again. New suggestions replace only the `extracted` values and items of the fields not named in the body; confirmed values are never overwritten, and a suggested skill whose name is already in either skill list is skipped. Null removes the text and keeps every value. + + Versions: every committed change creates version `expected_version + 1` as an immutable snapshot and answers 200 with it. `requirements_version` becomes the new version only when a confirmed requirement was confirmed, changed, or removed. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the need again and reapplies its unsaved edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for the questionnaire. Concurrent changes therefore never overwrite each other silently. + + The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains. + + Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - need + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/NeedId' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/NeedUpdate' + examples: + confirm_suggestions: + $ref: '#/components/examples/NeedUpdateConfirmSuggestions' + responses: + '200': + description: The need after the change, or the current need when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Need' + examples: + confirmed: + $ref: '#/components/examples/NeedConfirmedAfterUpdate' + '400': + $ref: '#/components/responses/NeedValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '412': + $ref: '#/components/responses/NeedVersionConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/matches: + post: + operationId: SearchOrganizationMatches + summary: Search the current organization-visible candidate bank. + description: |- + Requires the session cookie of an employer account with an active owner membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The organization comes from the path and the active server-side membership. Hidden profiles, revoked or missing C2 publication, and the organization's visibility restrictions are applied before any result is returned. + + The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An empty bank filter searches all otherwise eligible specializations, returning each specialization separately. + + A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, but each group returns at most the versioned per-group limit and no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of the organization (a candidate it already viewed inside the window costs nothing again, so repeating the search or opening the card afterwards does not charge twice) and appears in the candidate's access history with the fields actually returned. When the allowance ends, the entries already counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, and it carries no count. No new error is returned for an exhausted allowance. + + Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier. + + The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. + + Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed requirements snapshot and the stored vector of the candidate's published card text (roles, recognized stack, and published projects with the public metadata of their verified repositories). The search never calls the ML service: vectors are computed in the background after a change, and an entry whose vectors are missing, stale for the current model, or not computed because ML is unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence` lists, for a need search, the confirmed requirements whose closest published card item reaches a similarity band of the versioned policy; it names a project only by the title that the candidate published with the `projects` card field and says whether its repository is a verified public one, never the repository address or owner. Showing a project title records the `projects` field in the candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - organization + parameters: + - $ref: '#/components/parameters/OrganizationId' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/MatchSearchRequest' + examples: + by_need: + $ref: '#/components/examples/SearchByNeed' + by_bank_filters: + $ref: '#/components/examples/SearchByBank' + responses: + '200': + description: Organization-visible candidates in separate match groups. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/MatchSearchResponse' + examples: + three_groups: + $ref: '#/components/examples/ThreeGroups' + empty: + $ref: '#/components/examples/Empty' + ml_unavailable: + $ref: '#/components/examples/MLUnavailable' + cohort_below_30: + $ref: '#/components/examples/CohortBelow30' + truncated: + $ref: '#/components/examples/Truncated' + semantic_evidence: + $ref: '#/components/examples/SemanticEvidence' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}: + get: + operationId: GetOrganizationCandidateCard + summary: Read one currently visible anonymous candidate card. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data. + + `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server resolves it against the current visible cohort, rechecks active membership, effective C2 publication, and the candidate's hiding settings on every request, and applies the cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle, a handle from another organization, a closed or revoked publication, a profile hidden from this organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found. + + The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever available, are a separate operation and require the current explicit C4 grant and contact-access policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks this read immediately. Republishing does not reopen an earlier contact grant. + + Every allowed employer card read is recorded in the access history and consumes the organization's current product-policy card-view quota. A repeated view within the quota window is allowed by the existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/CandidateHandle' + responses: + '200': + description: The current anonymous card for this organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AnonymousCardContent' + examples: + published: + $ref: '#/components/examples/OrganizationAnonymousCandidateCard' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence: + get: + operationId: GetOrganizationCandidateEvidence + summary: Read the permitted skill evidence of one currently visible candidate card. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data. + + `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server runs the same checks as the card read on every request: active membership, effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In addition the card must publish the `categories` field and show at least one category after the cohort rules, because the evidence explains those categories and discloses nothing beyond them. An unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden from this organization, a profile suppressed by the minimum cohort, and a card without categories all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read immediately, and a cached response proves nothing. + + The response lists, for each category of the card, the one visible fact that supports its confirmed grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is a demonstration, not a validated measurement. It carries no identifier of the fact, event, result, or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band, or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no key that joins it to a person, but it is not unlinkable: with the other values of the card it can narrow a small pool of candidates. + + Reading the evidence is a view of the candidate card: it consumes the organization's current card-view quota with the same distinct-card rule and is recorded in the access history with the `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - evidence + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/CandidateHandle' + responses: + '200': + description: The permitted evidence of this candidate card for this organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationEvidence' + examples: + permitted: + $ref: '#/components/examples/OrganizationCandidateEvidence' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations: + get: + operationId: ListOrganizationInvitations + summary: List the invitations of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the membership that the server holds for the session account, never from the request. In the MVP only the owner of the organization works with invitations, as with needs; the other roles of the PRD FR07 matrix are planned and change no field of this contract. + + Returns a page of invitation summaries in every state, drafts included, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. A summary names the candidate only by the opaque `candidate_handle` and has the state, the versions, the role, the salary range, the deadline, and the contact access without any contact value. A declined invitation shows the state `declined` without the reason or the comment. Filters by state and need are planned and add optional parameters. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member whose role does not allow reading invitations answers 403 forbidden. A malformed `org_id`, `limit`, or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the invitations of the organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitationList' + examples: + last_page: + $ref: '#/components/examples/OrganizationInvitationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + post: + operationId: CreateOrganizationInvitation + summary: Create an invitation draft for one candidate. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The organization comes from the path and the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization may create an invitation. + + The draft is addressed to one person from a search result of this organization: `candidate_handle` is the opaque handle of that card, never an email address, a phone number, or an account identifier. The server resolves the handle for this organization only. An unknown handle, a handle of another organization, and a profile that the organization may no longer see, because the candidate revoked the publication C2 or hid the profile from it, all answer 400 with the pointer `/candidate_handle`, so a handle never reveals which case applies. `need` is optional: a direct invitation has none, and a need given must be a need of the organization with a `requirements_version` that it has had, otherwise 400 with the pointer `/need`. `response_period_days` is 3, 7, or 14 and defaults to 7. + + The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation. + + Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer: `/candidate_handle`, `/need`, `/terms/salary/salary_to` for a reversed range or a width outside 10-40%, `/terms/location` for the `office` or `hybrid` format without a place of work, or `/terms/tech_stack/1` for a repeated technology), then the salary limit (429). The schema already rejects a missing term or package condition, a salary bound that is not a positive multiple of 1000, an unknown currency, period, or tax basis, and unknown fields such as `state`, `version`, `salary_fit`, `candidate_email`, or `salary_minimum`. The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitationCreate' + examples: + valid_invitation: + $ref: '#/components/examples/InvitationCreateFromNeed' + responses: + '201': + description: The draft was created as version 1 with terms version 1, or a retry with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + draft: + $ref: '#/components/examples/OrganizationInvitationDraft' + '400': + $ref: '#/components/responses/InvitationValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/IdempotencyInProgress' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}: + get: + operationId: GetOrganizationInvitation + summary: Read an invitation of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the server-side membership, never from the request. In the MVP only the owner of the organization reads invitations. + + Returns the invitation with the current terms version, the state, the deadline, the coarse salary indicator `salary_fit`, and `contact_access`. The candidate appears only as the opaque `candidate_handle`: before and after an acceptance this response never carries the candidate's name, email address, phone number, or other contact, the exact salary minimum, or the reason and comment of a decline. Contact values come only from GetOrganizationInvitationContacts while `contact_access.status` is `available`. Reading earlier terms versions is planned as a separate operation. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the invitation answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + responses: + '200': + description: The invitation in its current state. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + draft: + $ref: '#/components/examples/OrganizationInvitationDraft' + delivered: + $ref: '#/components/examples/OrganizationInvitationDelivered' + accepted: + $ref: '#/components/examples/OrganizationInvitationAccepted' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + patch: + operationId: UpdateOrganizationInvitation + summary: Change the terms, the need link, or the response period of a draft. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body has no organization, membership, or role field. In the MVP only the owner of the organization changes drafts. + + Only a `draft` can change; any other state answers 409 state_conflict. After sending, the only change of the terms is the one raise of the upper salary bound through RaiseOrganizationInvitationSalary. The candidate of a draft cannot change: a draft for another candidate is a new draft. + + Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged. `terms` is always sent complete and replaces the terms as a whole, with the same validation as on creation, so a package condition is never dropped by omission. `need` sent as null unlinks the need. + + Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older. + + Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitationUpdate' + examples: + change_terms: + $ref: '#/components/examples/InvitationUpdateTerms' + responses: + '200': + description: The draft after the change, or the current draft when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + updated: + $ref: '#/components/examples/OrganizationInvitationDraftUpdated' + '400': + $ref: '#/components/responses/InvitationValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/send: + post: + operationId: SendOrganizationInvitation + summary: Send a draft to the candidate's inbox. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations. + + Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. + + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; the pause after a no deal is planned, because no operation produces the state `no_deal` yet. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found), the repeat of a completed send (200), the version (412), the state, the visibility of the candidate, the pending limit and the pause (409 state_conflict), then the quota (429). 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationCommand' + examples: + send: + $ref: '#/components/examples/InvitationSendCommand' + responses: + '200': + description: The invitation in the candidate's inbox with the state `delivered` and its deadline, or the invitation in its current state when it was already sent. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + delivered: + $ref: '#/components/examples/OrganizationInvitationDelivered' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise: + post: + operationId: RaiseOrganizationInvitationSalary + summary: Raise the upper salary bound of a sent invitation once. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization changes invitations. + + After sending, the salary base is fixed and the lower bound never decreases; the upper bound may be raised exactly once in the whole history of the invitation (PRD FR13). The body carries only the new `salary_to`, so the request cannot change the lower bound, the currency, the period, or the tax basis. The new bound must be above the current one and keep the width of the range from 10% to 40% of its midpoint, otherwise 400 validation_failed with the pointer `/salary_to`. The raise creates the next terms version with every other term unchanged and the next invitation version; the candidate sees the new terms, and an acceptance that names the previous terms version answers 412 version_conflict. The deadline does not change. The raise follows its own once-only rule and does not count against the organization-wide daily limit of three range settings, but it counts against the withheld counter of `salary_fit` (five settings within seven days), because it moves the upper bound that the indicator compares. + + Allowed in `delivered`, `viewed`, and `accepted`, and in the planned states `counter`, `interview_scheduled`, `interviewed`, and `no_deal`, where FR13 lets a raise open an early repeated final. During `negotiation`, after `terms_agreed`, in a terminal state, in a `draft` (change the draft instead), and after the raise was used, the server answers 409 state_conflict. A raise after an acceptance changes neither the accepted terms version of the grant nor the grant. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a raise to the same `salary_to` that was already applied answers 200 with the current invitation even with a new key or an older `expected_version`. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat of an applied raise (200), a terminal state (409 state_conflict, whatever the version), the version (412), any other state that does not allow a raise and the used raise (409 state_conflict), then the bound and the width (400). The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationSalaryRaise' + examples: + raise: + $ref: '#/components/examples/InvitationSalaryRaiseCommand' + responses: + '200': + description: The invitation with the raised upper bound and the next terms version, or the current invitation when the same raise was already applied. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + raised: + $ref: '#/components/examples/OrganizationInvitationSalaryRaised' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw: + post: + operationId: WithdrawOrganizationInvitation + summary: Withdraw an invitation. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization withdraws invitations. + + Moves an unfinished invitation to the terminal state `withdrawn` (PRD FR12): a `draft`, which the candidate never sees, a `delivered` or `viewed` invitation before the answer, an `accepted` one, and the planned stages up to `negotiation`. The process closes and no further transition happens in it. Withdrawing a delivered invitation frees its place in the pending limit of the need but never returns the weekly quota. Withdrawing never revokes the consent C4 or a grant that already exists: an accepted invitation keeps its `contact_access`, because only the candidate closes the access, by revoking C4, cancelling the participation, or closing the visibility. + + `withdrawn` differs from `cancelled_by_candidate`: the organization withdraws, and the grant stays; the candidate cancels through CancelMyInvitation, and the grant of this invitation is revoked. A terminal invitation (`declined`, `expired`, `cancelled_by_candidate`) answers 409 state_conflict, even with a stale `expected_version`, so the organization sees the final state at once. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a withdrawal of an invitation that is already `withdrawn` answers 200 with it even with a new key or an older `expected_version`. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a withdrawn invitation (200), a terminal state (409 state_conflict, whatever the version), then the version (412). The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationCommand' + examples: + withdraw: + $ref: '#/components/examples/InvitationWithdrawCommand' + responses: + '200': + description: The invitation in the state `withdrawn`. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/OrganizationInvitation' + examples: + withdrawn: + $ref: '#/components/examples/OrganizationInvitationWithdrawn' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts: + get: + operationId: GetOrganizationInvitationContacts + summary: Read the contacts that the candidate disclosed to the organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. + + This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B. + + Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one. + + Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/InvitationId' + responses: + '200': + description: The contacts that the active grant of this invitation covers. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ContactDisclosure' + examples: + email_only: + $ref: '#/components/examples/InvitationContactsEmailOnly' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations: + get: + operationId: ListMyInvitations + summary: List the invitations addressed to the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns a page of the candidate's inbox, newest first by delivery time with the identifier as the tie-breaker, with cursor pagination: every invitation that was delivered to this candidate, in any later state, including withdrawn and expired ones. Drafts and invitations addressed to other candidates are never listed. + + A summary has the organization, the state, the versions, the role, the salary range, the work formats, and the deadline. Listing never records a view: the state `delivered` stays until ViewMyInvitation records that the candidate opened the terms. Responsiveness metrics of the organization and filters by state are planned and add fields or optional parameters. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the invitations of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitationList' + examples: + last_page: + $ref: '#/components/examples/CandidateInvitationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}: + get: + operationId: GetMyInvitation + summary: Open the terms of an invitation addressed to the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session; the invitation must be addressed to this candidate. + + Returns the organization, the current terms version with the full terms, the state, and the deadline. While an acceptance is possible (`delivered` or `viewed` before the deadline), `contact_consent` holds the published text of the consent C4 for this organization and the kinds of contact that the profile holds, with nothing preselected; otherwise it is null. It is null as well when the profile holds no contact: a grant must cover at least one field, so the client asks the candidate to add a contact to the profile before accepting. After an answer the response holds the candidate's own decline or the contact grant that the acceptance created, with the selected kinds, its status, and whether the organization can read it now (`readable`, with `blocked_by` `visibility` when the profile is not published or is hidden from the organization), never contact values. The response never carries the candidate's handle, the need of the organization, the salary indicator of the organization, or any contact or salary minimum of the candidate. + + Reading has no side effect on the invitation: it never records a view. The client records that the candidate opened the terms with ViewMyInvitation, an explicit command, so a prefetch, a retry, or a cache refresh never changes the state that the organization sees. The only change a read can cause is the due expiry: a read at the deadline or later first applies the server transition to `expired` with `invitation_timeout`, which would happen without the read as well, and the response shows it. Reading earlier terms versions is planned as a separate operation. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found, so identifiers cannot be enumerated. An `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/MyInvitationId' + responses: + '200': + description: The invitation in its current state. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + delivered: + $ref: '#/components/examples/CandidateInvitationDelivered' + viewed: + $ref: '#/components/examples/CandidateInvitationViewed' + accepted: + $ref: '#/components/examples/CandidateInvitationAccepted' + declined: + $ref: '#/components/examples/CandidateInvitationDeclined' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/view: + post: + operationId: ViewMyInvitation + summary: Record that the current candidate opened the terms of an invitation. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body. + + The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. + + The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found. An `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/MyInvitationId' + responses: + '200': + description: The invitation, now `viewed` when it was `delivered`, otherwise in its current state. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + viewed: + $ref: '#/components/examples/CandidateInvitationViewed' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/accept: + post: + operationId: AcceptMyInvitation + summary: Accept the current terms and disclose the selected contacts. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. + + Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values. + + Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. + + 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/MyInvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationAcceptance' + examples: + email_only: + $ref: '#/components/examples/InvitationAcceptEmailOnly' + stale_terms: + $ref: '#/components/examples/InvitationAcceptStaleTerms' + responses: + '200': + description: The accepted invitation with the contact grant, or the same invitation when this acceptance was already made. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + accepted: + $ref: '#/components/examples/CandidateInvitationAccepted' + visibility_blocked: + $ref: '#/components/examples/CandidateInvitationAcceptedVisibilityBlocked' + '400': + $ref: '#/components/responses/InvitationAcceptValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/decline: + post: + operationId: DeclineMyInvitation + summary: Decline an invitation with a structured reason. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. + + Allowed in `delivered`, `viewed`, and the planned `counter`, before `response_deadline_at`. Moves the invitation to the terminal state `declined` with the reason and the optional comment; no consent and no access arise (PRD FR12). A timely decline counts as an answer for the responsiveness metrics, not as a consent or a hire. The reason is one of InvitationDeclineReason, including the neutral `other`; no reason requires a comment. + + Visibility: the organization sees only the state `declined` and `responded_at`. It never sees the reason or the comment of an individual decline, because a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned); the comment is never shown to the organization, published, logged, or sent in a notification. The candidate reads both back in `decline`. A new invitation of the same organization to this candidate is possible only after the 30-day pause. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a decline of an invitation that is already `declined` with the same reason and comment answers 200 with it even with a new key or an older `expected_version`. A terminal state, another reason or comment on a declined invitation, and a command at the deadline or later answer 409 state_conflict even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 version_conflict. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a declined invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the version), the version (412), then any other state that does not allow a decline (409 state_conflict). The schema rejects an unknown reason, an empty comment or one of only white space, a comment over 500 characters, and unknown fields. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/MyInvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationDeclineRequest' + examples: + other_without_comment: + $ref: '#/components/examples/InvitationDeclineOther' + with_comment: + $ref: '#/components/examples/InvitationDeclineWithComment' + responses: + '200': + description: The declined invitation with the candidate's own reason, or the same invitation when this decline was already made. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + declined: + $ref: '#/components/examples/CandidateInvitationDeclined' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/invitations/{invitation_id}/cancel: + post: + operationId: CancelMyInvitation + summary: Cancel the participation in an invitation and revoke its contact grant. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. + + Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations. + + Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a cancellation of an invitation that is already `cancelled_by_candidate` answers 200 with it even with a new key or an older `expected_version`. A terminal state other than `cancelled_by_candidate` answers 409 state_conflict even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 version_conflict. The deadline does not limit a cancellation. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a cancelled invitation (200), a terminal state (409 state_conflict, whatever the version), then the version (412). The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: '#/components/parameters/MyInvitationId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InvitationCommand' + examples: + cancel: + $ref: '#/components/examples/InvitationCancelCommand' + responses: + '200': + description: The invitation in the state `cancelled_by_candidate` with its grant revoked. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CandidateInvitation' + examples: + cancelled: + $ref: '#/components/examples/CandidateInvitationCancelled' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/InvitationCommandConflict' + '412': + $ref: '#/components/responses/InvitationVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/notifications: + get: + operationId: ListMyNotifications + summary: List the inbox of the current candidate. + description: |- + Requires the session cookie of a candidate account with a confirmed email. The recipient comes from the session, never from a request parameter, so the response holds only the caller's own items. Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The inbox is the in-platform delivery state of a notification. An item exists as soon as the event reached the platform, whether or not any email was sent, and an email that failed or was never sent does not block it. The inbox stores a reference to the event, not its text: the `content` of every item is resolved from the current source for this recipient on this read. When the source is gone or the recipient may not see it now (for example the candidate hid the organization), the item stays in the list with `content` null, and no earlier text is shown. An event that is delivered twice is one item. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the inbox of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + examples: + page: + $ref: '#/components/examples/NotificationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/notifications/{notification_id}/read: + post: + operationId: MarkMyNotificationRead + summary: Mark an item of the inbox of the current candidate as read. + description: |- + Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request has no body. + + The command is idempotent by its effect: the first mark stores the read time and every repeat returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no content, so marking an item whose content is no longer available still works. It changes no other item. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/NotificationId' + responses: + '200': + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationReadReceipt' + examples: + read: + $ref: '#/components/examples/NotificationReadReceipt' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/notifications: + get: + operationId: ListOrganizationNotifications + summary: List the inbox of the current employer in one organization. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role. The recipient comes from the session and the organization from the path and the membership that the server holds, never from the request. Returns only the items addressed to the caller in this organization, newest delivery first with the identifier as the tie-breaker, with cursor pagination. An item of the same account in another organization, and an item of another member, are never listed. The response is `Cache-Control: no-store`. + + Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email never blocks an item, and the `content` of every item is resolved from the current source for this recipient on this read. An employer sees content only while the membership is active. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the inbox of the current employer in the organization. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationList' + examples: + page: + $ref: '#/components/examples/NotificationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/organizations/{org_id}/notifications/{notification_id}/read: + post: + operationId: MarkOrganizationNotificationRead + summary: Mark an item of the inbox of the current employer in one organization as read. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session and the organization from the path and the server-side membership. The request has no body. + + The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The item must belong to the caller in this organization. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization, an unknown organization, an item of another account, an item of another organization, and an unknown identifier all answer 404 not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: '#/components/parameters/OrganizationId' + - $ref: '#/components/parameters/NotificationId' + responses: + '200': + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/NotificationReadReceipt' + examples: + read: + $ref: '#/components/examples/NotificationReadReceipt' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/consents: + get: + operationId: ListMyConsents + summary: List the consents of the current account with their history. + description: |- + Requires the session cookie of a candidate or an employer account. The subject comes from the session, never from a request parameter, so the response holds only the caller's own consents: no request can name another account, and records of other accounts are never listed. Returns a page of the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with cursor pagination. + + The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. + + Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. + + Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - consent + parameters: + - name: state + in: query + required: false + description: Lists only the records in this state; omit it for the whole history. + schema: + $ref: '#/components/schemas/ConsentState' + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the consent ledger of the current account. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentRecordList' + examples: + history: + $ref: '#/components/examples/ConsentRecordListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/consents/{purpose}: + put: + operationId: GrantMyConsent + summary: Record an explicit consent grant from settings. + description: |- + Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. The body names the current text version the user read and requires `accepted: true`; the server verifies that version is still current and stores the hash of the exact text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. + + C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the same current version returns the existing record; after revocation a grant creates a new record and never reopens a publication or restores an older grant. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Independent consent being granted. C4 is not available here. + schema: + $ref: '#/components/schemas/ConsentSettingsPurpose' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentSettingsGrantRequest' + responses: + '200': + description: The created or existing consent record. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentRecord' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed, or an employer tried to grant a candidate-only purpose. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: RevokeMyConsent + summary: Revoke a non-scoped consent from settings. + description: |- + Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, including superseded records, and never changes another purpose. Repeating a revocation is harmless and creates no duplicate event. + + Revoking c2 immediately closes the stored publication and records privacy history in the same transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; an external FSP deletion adapter is not available yet. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope. + schema: + $ref: '#/components/schemas/ConsentSettingsRevokePurpose' + responses: + '204': + description: Consent revoked, or it was already revoked. + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed, or an employer account tried to revoke candidate consent. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/consents/c4/organizations/{org_id}: + delete: + operationId: RevokeMyOrganizationContactConsent + summary: Revoke C4 for one organization. + description: Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The server revokes every unrevoked C4 record for this subject and organization, using the fields stored on those records to request downstream grant revocation. It does not affect another organization. Repeating the request is harmless and creates no duplicate event. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: org_id + in: path + required: true + description: Organization whose stored C4 grants this account revokes. A well-formed identifier outside the account's stored records changes nothing and does not reveal whether that organization exists. + schema: + type: string + format: uuid + responses: + '204': + description: C4 revoked for this organization, or no active C4 was present. + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed, or the caller is not a candidate. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/account-deletion-requests: + post: + operationId: RequestMyAccountDeletion + summary: Revoke C1 and request account deletion. + description: Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. In one transaction, revokes any active C1 record, creates or returns the subject's active durable deletion request, and writes the outbox intent. The API does not delete the account synchronously. Repeating the request returns the same active request; a later C1 grant never cancels it. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + responses: + '202': + description: The durable account-deletion request is queued for processing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/ConsentDeletionRequest' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + description: CSRF or Origin validation failed. + $ref: '#/components/responses/CsrfCheckFailed' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy: + get: + operationId: GetMyPrivacySettings + summary: Read the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns the publication of the candidate card, the search status, and the number of hidden organizations in one read. The response is `Cache-Control: no-store`. + + A profile is closed by default. A candidate who never published reads `publication.state` `closed` with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or an assessment changes these settings. The C2 consent, the search status, and the hidden organizations are three independent settings: the C2 record in the consent ledger proves that the candidate accepted the publication text, the publication records which fields are published, and the search status is a statement of the candidate that is not a consent. A change of one never changes another, and none of them ever makes the candidate more visible by itself: the search status lapses to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + '200': + description: The visibility settings of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PrivacySettings' + examples: + new_candidate: + $ref: '#/components/examples/NewCandidatePrivacySettings' + published_and_looking: + $ref: '#/components/examples/PublishedCandidatePrivacySettings' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/publication: + put: + operationId: SetMyPublication + summary: Publish or close the anonymous candidate card. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. + + Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + + The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first publication. If it is not the current version the server answers 412 version_conflict and changes nothing. The version travels in the body rather than in If-Match because the generated client cannot read the ETag header yet. A body that equals the stored setting changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a retry after a lost response succeeds without an Idempotency-Key. A version above the current one never existed and always answers 412. Every change is recorded in the settings history with its time, the fields, and the C2 record. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), rules that depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown card field, and more fields than there are groups; a published state with no field, and a closed state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never repeat a submitted value. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicationUpdate' + examples: + publish: + $ref: '#/components/examples/PublicationUpdatePublish' + close: + $ref: '#/components/examples/PublicationUpdateClose' + responses: + '200': + description: The saved publication with its new version, or the current one when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/Publication' + examples: + published: + $ref: '#/components/examples/PublishedPublication' + '400': + $ref: '#/components/responses/PrivacyValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '409': + $ref: '#/components/responses/PublicationConsentRequired' + '412': + $ref: '#/components/responses/PrivacyVersionConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/preview: + get: + operationId: GetMyCardPreview + summary: Preview the anonymous card that organizations would read. + description: |- + Requires the session cookie of a candidate account. Returns a private preview of the permitted anonymous-card fields from the current profile, publication, and consent ledger. The response is `Cache-Control: no-store`. + + The preview creates no view or access record and is never shown to an organization. While the profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an organization's pseudonym. Organization-specific visibility filters and cohort checks can further generalize or suppress the card when an organization reads it. + + `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount. + + `evidence` shows what an organization would read in the evidence section of the card (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an empty list when the card shows no category or no visible fact supports one. The preview applies no organization or cohort, so an organization can still receive less. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + '200': + description: The anonymous card as organizations would read it now. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CardPreview' + examples: + published: + $ref: '#/components/examples/PublishedCardPreview' + closed: + $ref: '#/components/examples/ClosedCardPreview' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/search-status: + put: + operationId: SetMySearchStatus + summary: Set or confirm the search status of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. The status is a statement of the candidate and never a consent. It changes neither the C2 consent, nor the publication, nor the hidden organizations, and it does not close or open any contact grant; a candidate whose profile is closed who sets `looking` becomes visible to no one. + + `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from the `search_status` section of the effective product policy (30 days in the demo policy, `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it replaces the confirmation time with now and advances the version, also after a lapse. The body carries no time, interval, or policy version. + + After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The lapse is computed and written nowhere, so it needs no job, it can never make the candidate more visible, and it never touches the publication or the hidden organizations. A reminder before the lapse is a planned notification, not a part of this operation. + + Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the status; a stale or non-existent version answers 412 version_conflict and changes nothing. `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. `looking` always changes the stored confirmation, so a retry of a confirmation whose response was lost with the old version answers 412 and the client reads the status again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), an unchanged `not_looking` (200), then a stale version (412). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SearchStatusUpdate' + examples: + looking: + $ref: '#/components/examples/SearchStatusUpdateLooking' + responses: + '200': + description: The saved search status with its new version, or the current one when the body changes nothing. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SearchStatus' + examples: + looking: + $ref: '#/components/examples/LookingSearchStatus' + lapsed: + $ref: '#/components/examples/LapsedSearchStatus' + '400': + $ref: '#/components/responses/PrivacyValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '412': + $ref: '#/components/responses/PrivacyVersionConflict' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/hidden-organizations: + get: + operationId: ListMyHiddenOrganizations + summary: List the organizations that the candidate hides the profile from. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records and no request can name another account. Returns a page of the hidden organizations, newest first with the organization identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The records belong to the candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, no card, no contact read. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the hidden organizations of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/HiddenOrganizationList' + examples: + page: + $ref: '#/components/examples/HiddenOrganizationListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/hidden-organizations/{org_id}: + put: + operationId: HideOrganization + summary: Hide the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body: the path names the organization and the candidate comes from the session. The hiding is a record that belongs to the candidate and references the organization; it changes neither the C2 consent, nor the publication, nor the search status. + + The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. + + Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate may name an organization in their own card-access history or an existing hidden-organization record. Invitation visibility will be added with the invitation workflow, and a candidate lookup remains planned. The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it. + + A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. + + Hiding an organization that holds an active contact grant of the candidate revokes that grant with the reason `visibility_closed` in the same transaction (planned together with the invitation operations). Lifting the hiding never reopens a grant. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), the organization and its visibility to the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like every visibility change, hiding needs a verified email (a usecase requirement). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/HiddenOrganizationId' + responses: + '200': + description: 'The organization is hidden from the candidate profile: the new record or the one that existed.' + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/HiddenOrganization' + examples: + hidden: + $ref: '#/components/examples/HiddenOrganizationRecord' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/HiddenOrganizationLimit' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: UnhideOrganization + summary: Lift the hiding of the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or does not exist, so the operation reveals nothing about the organization, and a repeat after a lost response succeeds. The record is deleted, the settings history keeps the event `organization_unhidden` only when a record was deleted. + + Lifting the hiding makes the candidate readable by that organization again only if the profile is published and the organization otherwise may read it. It changes neither the C2 consent, nor the publication, nor the search status, and it never reopens a contact grant that the hiding closed. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), then the deletion (204). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/HiddenOrganizationId' + responses: + '204': + description: The organization is not hidden from the candidate profile. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/history: + get: + operationId: ListMyPrivacyHistory + summary: List the changes of the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records. Returns a page of the settings history, newest first with the event identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The history is append-only evidence of what the candidate published, hid, and announced, and when. A publication event keeps the published fields and the C2 record behind them, which is what the consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the field set). A revocation of C2 and a lapse of the search status are computed and are not events here; the consent history shows the revocation. The history never contains a profile value. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the settings history of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/PrivacyEventList' + examples: + page: + $ref: '#/components/examples/PrivacyEventListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/privacy/access-history: + get: + operationId: ListMyCardAccessHistory + summary: List the accesses of organizations to the card of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A retained access record permits the candidate to see the organization's identifier and current name and to hide their profile from it. The nullable organization field is preserved for records whose organization cannot be presented. The entries carry no employee identity, search query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does not erase earlier permitted accesses from the history. + + Successful organization card reads are recorded transactionally with the visibility and quota checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an accepted workflow status alone never authorizes contact access. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the accesses to the card of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/CardAccessList' + examples: + page: + $ref: '#/components/examples/CardAccessListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/evidence: + get: + operationId: ListMyEvidence + summary: List the skill evidence of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own facts. Returns a page, newest event first with the fact identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in the same transaction that stores the result. Each fact names its source (the event and the result, which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that was passed with its basis and calibration, the attribution, the date, the visibility, and the trust level. An online assessment without a reliable confirmation of the identity has trust 1. One source event is one fact: its skills are tags of that fact, so several tags never make several facts. + + The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed attempt, a result without a reviewed category source, and an express training run (`demo_express`) create no fact, so reading the list before and after an express run shows no new fact. The list includes facts the candidate hid, with `visibility` `hidden`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another candidate, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - evidence + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the skill evidence of the current candidate. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/EvidenceFactList' + examples: + page: + $ref: '#/components/examples/EvidenceFactListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/support-cases: + get: + operationId: ListMySupportCases + summary: List the support cases of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns a page of the cases that this account created, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. Each item is a summary with the number, type, status, object reference, category, response target, and decision outcome; it has no description and no history, which GetMySupportCase returns with the full case. Cases of other accounts are never listed, including cases of other members of the same organization. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add optional parameters. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: '#/components/parameters/PageLimit' + - $ref: '#/components/parameters/PageCursor' + responses: + '200': + description: A page of the cases of the current account. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCaseList' + examples: + last_page: + $ref: '#/components/examples/SupportCaseListPage' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + default: + $ref: '#/components/responses/Problem' + post: + operationId: CreateMySupportCase + summary: Open a support case, a complaint, an appeal, or a manual assessment request. + description: |- + Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The author is the account of the session; the body has no user, account, or organization field. A case is reachable from any screen, including a screen that denies access to an assessment: being refused an action never removes the path to a case about it. + + The client sends only what the user states: `type`, a non-blank `description`, and the fields of the type. It never sets the status, the decision, the outcome, the priority, the response target, the rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and change no existing one. + + Types, accounts, and allowed references: + + | Type | Accounts | Object reference | Other fields | + | --- | --- | --- | --- | + | `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | + | `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation | + | `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none | + | `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none | + | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` | + + An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. + + Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object. + + Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment, and an object accepts one open complaint; open means not `resolved` or `closed`. A second one answers 409 state_conflict. A grade appeal of an attempt that is still active also answers 409. Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with Retry-After and creates nothing. + + Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer `/description`. This check comes with the implementation; generated Zod accepts a description of NEL, and the server stays authoritative. + + The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the 201 already shows that status with both events; a support case and a complaint stay `submitted`. Each case gets a response target from the product policy version and the configured business calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a policy value for support and complaints. The target is an operational goal, not a deadline set by law. A manual assessment fixes the published rubric version of the category, or null when the category has none yet; the expert assesses with the same rubric as the automated assessment, and the request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt. + + Replies: the case itself is the channel. Support replies and decisions appear in the public `history` and `decision`. The server may also notify the verified email address of the account that the case changed, with the case number and a link, never with the description, the reply, or assessment details. No request field names another address or contact, so the operation cannot send mail to an address that the user typed. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same number and creates nothing, so a lost response never opens a second case. The replay is the snapshot stored at creation, following the repository convention; the client reads the current status and history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A different body with the same key answers 422 idempotency_key_reused. 400, 403, and 429 are never stored. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer account with a type other than `support`), the per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a complaint reason that requires an invitation), the object reference (404 not_found), then the state of the object and the limits (409 state_conflict). The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - support + parameters: + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCaseCreate' + examples: + manual_assessment: + $ref: '#/components/examples/SupportCaseCreateManualAssessment' + own_grade_appeal: + $ref: '#/components/examples/SupportCaseCreateGradeAppeal' + appeal_of_manual_assessment: + $ref: '#/components/examples/SupportCaseCreateCategoryAppeal' + test_unavailable: + $ref: '#/components/examples/SupportCaseCreateTestUnavailable' + salary_terms_complaint: + $ref: '#/components/examples/SupportCaseCreateComplaint' + responses: + '201': + description: The case was created, with the status `submitted` or, for an appeal or a manual assessment, `waiting_expert`; or a retry with the same Idempotency-Key replayed the stored creation response. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCase' + examples: + manual_assessment: + $ref: '#/components/examples/SupportCaseManualAssessmentCreated' + '400': + $ref: '#/components/responses/SupportCaseValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/SupportCaseCreateConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/support-cases/{case_id}: + get: + operationId: GetMySupportCase + summary: Read a support case of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns the case with its number, type, object reference, status, response target, decision, and public history. The owner reads the case whatever happened to the object since then: a revoked access, a closed invitation, or a refused test never hides the case from its author. + + The case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. `decision` is null until the case is `resolved`. + + The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. + + The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: '#/components/parameters/SupportCaseId' + responses: + '200': + description: The case. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/SupportCase' + examples: + manual_assessment_created: + $ref: '#/components/examples/SupportCaseManualAssessmentCreated' + grade_appeal_resolved: + $ref: '#/components/examples/SupportCaseGradeAppealResolved' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs: + post: + operationId: CreateMyAssessmentLab + summary: Start the lab of the current lab item of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the current item, whose content has the format `lab`. + + The server asks the lab provisioner for a lab of the variant fixed for this item instance and answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt version, the current item, or any answer. + + One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may start a new one while the item is current; after `submitted` or `expired` the item cannot start another lab (409 state_conflict). + + Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 service_unavailable with Retry-After, for example `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. The attempt deadline keeps running in both cases. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the item (404 not_found for an unknown attempt or item, or one of another candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit (429), then the availability of labs and the capacity (503). Following the Idempotency-Key convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, and 503 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabCreate' + examples: + start: + summary: Start the lab of the current item. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + responses: + '200': + description: The item already has an active lab; it is returned and no second lab is started. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + '201': + description: The lab was requested and is provisioning. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + examples: + provisioning: + summary: A lab of two routers that is being prepared. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: provisioning + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: '2026-10-11T09:00:00Z' + ready_at: null + expires_at: '2026-10-11T09:45:00Z' + finished_at: null + failure_reason: null + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentCommandConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}: + get: + operationId: GetMyAssessmentLab + summary: Read the lab of an assessment attempt item. + description: |- + Requires the session cookie of a candidate account. Returns the state of a lab started with CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after the submission, or ended. It never contains a node address, a credential, the seed, the checker state, or the result of the check. This GET is read-only; the server may record a due timer transition, such as `ready` to `expired`, before it answers. + + A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer 404 not_found. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + responses: + '200': + description: The lab. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + examples: + ready: + summary: A ready lab whose consoles can be opened. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: ready + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: '2026-10-11T09:00:00Z' + ready_at: '2026-10-11T09:00:40Z' + expires_at: '2026-10-11T09:45:00Z' + finished_at: null + failure_reason: null + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/Forbidden' + '404': + $ref: '#/components/responses/NotFound' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions: + post: + operationId: CreateMyAssessmentLabConsoleSession + summary: Open a console session of one node of a ready lab. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body names a node of the lab by its task name. + + The response describes one console session: the client opens a WebSocket to `websocket_path` on the same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin check, and the server relays the serial console of the node through the lab provisioner. The response never carries a node address, a port, a password, a key, or a token; the browser never connects to a node or to the provisioner. Console traffic is not stored as an answer and is not logged. + + The WebSocket relay is planned together with the candidate interface of labs; this contract fixes the session shape it uses. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 service_unavailable without Retry-After; nothing was opened). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabConsoleSessionCreate' + examples: + r1: + summary: Open the console of r1. + value: + node: r1 + responses: + '201': + description: The console session was opened. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabConsoleSession' + examples: + opened: + summary: A console session of r1. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + node: r1 + websocket_path: /api/v1/me/assessment-lab-consoles/0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + expires_at: '2026-10-11T09:02:00Z' + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/StateConflict' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission: + post: + operationId: SubmitMyAssessmentLab + summary: Submit the lab of the current lab item as its answer. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version last read and the answer with format `lab`, which names the lab. + + The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, which moves to the next item. Neither response says whether the answer was correct, and the candidate never sees the checker criteria or their results. + + When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the candidate may start a new lab of the item while it is current. A failure of the infrastructure is never scored as a wrong answer. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the lab in the path, the item is not current, the attempt is terminal, or its work session ended), then the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: '#/components/parameters/AssessmentAttemptId' + - $ref: '#/components/parameters/IdempotencyKey' + - name: lab_id + in: path + required: true + description: Identifier of the lab to submit. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLabSubmission' + examples: + submit: + summary: Submit the lab as the answer of its item. + value: + expected_version: 7 + answer: + format: lab + lab_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + responses: + '202': + description: The submission was accepted and the lab is being checked. + headers: + Cache-Control: + $ref: '#/components/headers/CacheControlNoStore' + content: + application/json: + schema: + $ref: '#/components/schemas/AssessmentLab' + examples: + checking: + summary: A submitted lab whose nodes are being checked. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: checking + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: '2026-10-11T09:00:00Z' + ready_at: '2026-10-11T09:00:40Z' + expires_at: '2026-10-11T09:45:00Z' + finished_at: null + failure_reason: null + '400': + $ref: '#/components/responses/ValidationFailed' + '401': + $ref: '#/components/responses/Unauthenticated' + '403': + $ref: '#/components/responses/CsrfCheckFailedOrForbidden' + '404': + $ref: '#/components/responses/NotFound' + '409': + $ref: '#/components/responses/AssessmentCommandConflict' + '412': + $ref: '#/components/responses/AssessmentVersionConflict' + '422': + $ref: '#/components/responses/UnprocessableContent' + '429': + $ref: '#/components/responses/TooManyRequests' + '503': + $ref: '#/components/responses/ServiceUnavailable' + default: + $ref: '#/components/responses/Problem' components: schemas: + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. + items: + $ref: '#/components/schemas/ProblemFieldError' + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - 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, or an `expected_version` field in the request body, does not match the current version; nothing was changed. + - 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. + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later. + 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 + - service_unavailable + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + Timestamp: + type: string + format: date-time + description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema. + examples: + - '2026-10-05T09:30:00Z' + PageInfo: + type: object + description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - 'null' + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. + 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: the assessment. The expected grade is the `self_assessed_grade` saved in the questionnaire, and this step offers it first; only an assessment result confirms a grade. A successful SaveMyQuestionnaire moves the account from candidate_questionnaire to this step and leaves every other saved step unchanged. + - 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 + ConsentSettingsPurpose: + type: string + description: Consent text that an authenticated account can read and accept in settings. C4 is scoped to an invitation and organization, so it is not available through the general settings flow. + enum: + - c1 + - c2 + - c3 + - c5 + ConsentSettingsRevokePurpose: + type: string + description: Consent that can be revoked through the general settings flow. C1 uses the account deletion request, and C4 must be revoked for one organization. + enum: + - c2 + - c3 + - c5 + 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/ConsentPurposeCode' + 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: One-time token copied from the verification link and the password chosen for the registration that issued it. The password is never included in the link. + additionalProperties: false + required: + - token + - password + properties: + token: + $ref: '#/components/schemas/VerificationToken' + password: + type: string + minLength: 1 + maxLength: 128 + description: Password chosen for the registration that issued this token. It is sent in the request body and never appears in the verification link. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. + 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' + DirectionCode: + type: string + description: |- + Stable code of a professional direction, the group that a specialization belongs to. + + - development: Development. + - infrastructure: Infrastructure. + - data: Data. + - security: Security. + - quality: Quality. + + Adding a value is a contract change. + enum: + - development + - infrastructure + - data + - security + - quality + SpecializationCode: + type: string + description: |- + Stable code of a specialization. A category is a specialization together with a confirmed grade; programming languages and the technology stack are separate attributes and never form a category of their own, so Backend with Go is the category `backend`, not `go`. Algorithms is a shared assessment module, not a specialization, and has no code here. + + - backend: Backend (development). + - frontend: Frontend (development). + - mobile: Mobile (development). + - network_engineer: Network Engineer (infrastructure). + - devops_sre: DevOps/SRE (infrastructure). + - data_analyst: Data Analyst (data). + - ds_ml: DS/ML (data). + - information_security: Information security (security). + - qa: QA (quality). + + Adding a value is a contract change; renaming or removing one is a breaking change. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + GradeCode: + type: string + description: 'Grade of the MVP scale in ascending order: `intern`, `junior`, `middle`, `senior`. The same codes describe a self-assessed grade, which the candidate states, and a confirmed grade, which only an assessment result establishes. Lead and Architect are planned after the MVP; adding a value is a contract change.' + enum: + - intern + - junior + - middle + - senior + TaskLanguage: + type: string + description: Programming language in which assessment tasks of a specialization are offered and solved. It is the language of the task bank, not the candidate's platform stack, and it never forms a separate category. Only banks that offer a choice of language define task languages; the first Backend bank offers Python and Go. Adding a value is a contract change. + enum: + - python + - go + TestAvailabilityStatus: + type: string + description: Whether an assessment can start for the specialization. `available` means that a published task bank exists for at least one grade, listed in `TestAvailability.grades`. `in_development` means that no grade of the specialization has a published bank yet; the specialization can still be chosen in the questionnaire, but no assessment starts and no category can be confirmed for it. Presence in the catalog or in demo data never means that a test is ready. + enum: + - available + - in_development + TestAvailability: + type: object + description: Assessment availability of a specialization, derived by the server from the published task banks at the time of the request. The MVP opens an assessment only for a category, a specialization and a grade, that has a published bank. `status` is `available` exactly when `grades` is not empty; for `in_development` both `grades` and `task_languages` are empty. + additionalProperties: false + required: + - status + - grades + - task_languages + - note + properties: + status: + $ref: '#/components/schemas/TestAvailabilityStatus' + grades: + type: array + maxItems: 10 + uniqueItems: true + description: Grades of the specialization with a published task bank, in ascending order. Only these categories can be assessed and confirmed. + items: + $ref: '#/components/schemas/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages that the published bank offers for this specialization. Empty when the bank does not offer a choice of language, as for Network Engineer, or when no bank is published. The questionnaire accepts only these languages for the specialization. + items: + $ref: '#/components/schemas/TaskLanguage' + note: + type: + - string + - 'null' + minLength: 1 + maxLength: 300 + description: Short Russian note for the candidate, for example why the test is not available yet, or null. Plain text; the client shows it as text, never as HTML. + CatalogSpecialization: + type: object + description: Specialization in the catalog with its assessment availability. + additionalProperties: false + required: + - code + - title + - test_availability + properties: + code: + $ref: '#/components/schemas/SpecializationCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + test_availability: + $ref: '#/components/schemas/TestAvailability' + CatalogDirection: + type: object + description: Professional direction with its specializations. Each specialization belongs to exactly one direction. + additionalProperties: false + required: + - code + - title + - specializations + properties: + code: + $ref: '#/components/schemas/DirectionCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + specializations: + type: array + minItems: 1 + maxItems: 20 + description: Specializations of the direction in display order. + items: + $ref: '#/components/schemas/CatalogSpecialization' + CatalogGrade: + type: object + description: Grade of the scale with its display name. + additionalProperties: false + required: + - code + - title + properties: + code: + $ref: '#/components/schemas/GradeCode' + title: + type: string + minLength: 1 + maxLength: 100 + description: Display name in Russian. Plain text. + SpecializationCatalog: + type: object + description: Catalog of directions, specializations, and the grade scale that the questionnaire and the assessment use. The catalog is reference data and identical for every caller; it contains no personal data. + additionalProperties: false + required: + - directions + - grades + properties: + directions: + type: array + minItems: 1 + maxItems: 20 + description: Directions in display order. + items: + $ref: '#/components/schemas/CatalogDirection' + grades: + type: array + minItems: 1 + maxItems: 10 + description: Grade scale in ascending order. + items: + $ref: '#/components/schemas/CatalogGrade' + QuestionnaireVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the candidate questionnaire. A candidate without a saved questionnaire has version 0; every save that changes the questionnaire advances it by one. + examples: + - 3 + StackTag: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: 'Free technology tag of the candidate''s stack, for example PostgreSQL, Kubernetes, or Django. A tag is a descriptive attribute: it never forms a category, never selects the task language, and never changes a grade, so a tag such as "Senior" has no effect on any category. It has no leading or trailing whitespace and no line breaks. The server compares tags without regard to letter case. Clients show tags as text, never as HTML.' + WorkFormat: + type: string + description: 'Acceptable work format: `remote`, `office`, or `hybrid`.' + enum: + - remote + - office + - hybrid + WorkContext: + type: object + description: 'Working context of the candidate''s search. It holds no personal data such as an address or a city; location, relocation, and salary expectations belong to the candidate profile (`ProfileTerms`). The acceptable work formats live only here: the profile does not repeat them.' + additionalProperties: false + required: + - work_formats + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Acceptable work formats. + items: + $ref: '#/components/schemas/WorkFormat' + CandidateExperience: + type: object + description: 'Experience that the candidate states for one specialization, in whole months. It is self-reported context: it never adds assessment points and never confirms a grade. The work history entries of the candidate profile (`ProfileExperienceItem`) are a different, detailed claim: the two are saved separately and the server neither adds the entries up nor fills them from these totals.' + additionalProperties: false + required: + - commercial_months + - academic_months + properties: + commercial_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of commercial work in the specialization. + academic_months: + type: integer + format: int32 + minimum: 0 + maximum: 600 + description: Months of study, internships, or academic projects in the specialization. + QuestionnaireSpecialization: + type: object + description: 'One specialization chosen by the candidate with the candidate''s self-assessment. `self_assessed_grade` is a claim: it influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never becomes a confirmed grade. A confirmed grade, and with it a category, comes only from an assessment result and is never part of the questionnaire; unknown fields such as `confirmed_grade` or `category` are rejected. Task languages and the stack are attributes of the chosen specialization, not categories. The candidate profile states the same kind of claim in the `roles` of `CandidateProfile` (`ProfileRoleItem.self_assessed_grade`): the questionnaire value starts the assessment and the profile value is what the profile shows, the two are saved separately, and neither is ever a confirmed grade.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - task_languages + - stack + - experience + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + self_assessed_grade: + $ref: '#/components/schemas/GradeCode' + task_languages: + type: array + maxItems: 2 + uniqueItems: true + description: Task languages in which the candidate wants to solve assessment tasks of this specialization. Each value must be one of `test_availability.task_languages` of the specialization in the current catalog; any other value answers 400 validation_failed with a pointer to it. Empty when the bank offers no choice of language. + items: + $ref: '#/components/schemas/TaskLanguage' + stack: + type: array + maxItems: 20 + uniqueItems: true + description: Technology tags of the candidate in this specialization. + items: + $ref: '#/components/schemas/StackTag' + experience: + description: Stated experience, or null when the candidate did not state it. + oneOf: + - $ref: '#/components/schemas/CandidateExperience' + - type: 'null' + CandidateQuestionnaire: + type: object + description: 'Questionnaire of the current candidate: the chosen specializations with self-assessed grades and the working context. It never contains a confirmed grade or a category; those come only from assessment results. A candidate who has not saved the questionnaire yet gets version 0, no specializations, and null `work_context` and `updated_at`.' + additionalProperties: false + required: + - version + - specializations + - work_context + - updated_at + properties: + version: + $ref: '#/components/schemas/QuestionnaireVersion' + specializations: + type: array + maxItems: 2 + description: Chosen specializations in the order the candidate gave them, each specialization at most once. Each one is assessed independently. + items: + $ref: '#/components/schemas/QuestionnaireSpecialization' + work_context: + description: Working context, or null before the first save. + oneOf: + - $ref: '#/components/schemas/WorkContext' + - type: 'null' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + CandidateQuestionnaireUpdate: + type: object + description: Complete new state of the questionnaire. It replaces the stored specializations and working context as a whole. Unknown fields are rejected, so a request cannot set a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - specializations + - work_context + properties: + expected_version: + $ref: '#/components/schemas/QuestionnaireVersion' + specializations: + type: array + minItems: 1 + maxItems: 2 + description: One or two chosen specializations. The schema limits the count; the server also requires each specialization to appear at most once and answers a repeated one with 400 validation_failed and the pointer of the repeated item's `specialization`, for example `/specializations/1/specialization`. + items: + $ref: '#/components/schemas/QuestionnaireSpecialization' + work_context: + $ref: '#/components/schemas/WorkContext' + ProfileVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the candidate profile. A candidate who has not saved the profile has version 0; every save that changes the profile advances it by one. The client sends the version it read as `expected_version`. + examples: + - 4 + ProfileItemStatus: + type: string + description: |- + Confirmation state of a profile list item, and the decision that a request sends for a field or an item. + + - confirmed: the candidate typed the value or confirmed a suggestion. Only confirmed values leave the profile, for example into a disclosure. + - extracted: a suggestion that the server took from an imported document or source. Nobody has confirmed it yet, so it is a claim of trust level 0 that no other feature uses. + + A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value; a client that submits an unchanged form therefore confirms nothing by accident. An item is never `unknown`: a missing item is simply absent from the list. + enum: + - confirmed + - extracted + ProfileClaimStatus: + type: string + description: |- + Confirmation state of a single profile field. + + - confirmed: the candidate typed the value or confirmed a suggestion. + - extracted: the server proposed the value from an imported document or source and the candidate has not confirmed it. It is a claim of trust level 0. + - unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a zero salary or a relocation answer. + enum: + - confirmed + - extracted + - unknown + ProfileClaimOrigin: + type: string + description: |- + Where the value of a profile field or item came from. The server sets it; a request never sends it. + + - manual: the candidate typed the value in the form. `quote` and `extraction_version` are null. + - extracted_from_resume: planned; the server extracted the value from an uploaded resume with the deterministic rules or the ML service. No MVP operation produces it, and no profile requires a resume. + - imported: planned; the value was copied from an external source such as the FSP account of the candidate. No MVP operation produces it, and no profile requires such a link. + + Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change. + enum: + - manual + - extracted_from_resume + - imported + ProfileClaimTrustLevel: + type: integer + format: int32 + minimum: 0 + maximum: 0 + description: 'Trust level of a profile claim. Every claim of the profile has trust level 0, whatever its origin: a manual value, an imported value, and a value that the candidate confirmed are all unverified statements. Confirming a suggestion changes its status, never its trust level. Higher levels belong to evidence, such as an assessment result or a confirmation by a third party, which are separate resources and never write a level into a profile claim.' + examples: + - 0 + ProfileClaimQuote: + type: string + minLength: 1 + maxLength: 300 + description: Exact excerpt of the imported document that the value was extracted from, so the candidate can check it. It may contain personal data of the candidate. It may contain line breaks. Plain text; clients show it as text, never as HTML. + ProfileClaimSource: + type: object + description: 'Provenance and confirmation of one profile value: its origin, the trust level, the excerpt it was extracted from, the extractor version, and the time the candidate confirmed it. Read-only; the server derives it and a request cannot set it. The imported document or source itself is not referenced: the profile never requires a file, the ML service, or an FSP account, and a later link to them is an additive field.' + additionalProperties: false + required: + - origin + - trust_level + - quote + - extraction_version + - confirmed_at + properties: + origin: + $ref: '#/components/schemas/ProfileClaimOrigin' + trust_level: + $ref: '#/components/schemas/ProfileClaimTrustLevel' + quote: + description: Excerpt of the imported document that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt. + oneOf: + - $ref: '#/components/schemas/ProfileClaimQuote' + - type: 'null' + extraction_version: + description: Extractor version for an extracted or imported value, or null for a manual value. + oneOf: + - $ref: '#/components/schemas/NeedVersionLabel' + - type: 'null' + confirmed_at: + description: Time the candidate typed or confirmed the value, or null while the value is an unconfirmed suggestion. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + ProfileLocationName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: City or region where the candidate lives or wants to work, as free text. It is personal data of the candidate and never a street address. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + ProfileSalaryMinimum: + type: object + description: 'The lowest salary that the candidate accepts, in whole rubles with its base: the currency, the pay period, and the tax basis. It is private to the candidate: no organization reads it, and the invitation only shows a compatibility indicator that the server derives from it. It is personal data. The amount is a positive multiple of 1000.' + additionalProperties: false + required: + - amount + - currency + - period + - tax_basis + properties: + amount: + $ref: '#/components/schemas/RubAmount' + currency: + $ref: '#/components/schemas/CurrencyCode' + period: + $ref: '#/components/schemas/SalaryPeriod' + tax_basis: + $ref: '#/components/schemas/SalaryTaxBasis' + ProfileSoftSkill: + type: string + minLength: 1 + maxLength: 50 + pattern: ^\S(?:.*\S)?$ + description: Soft skill as the candidate wrote it, for example "Mentoring" or "Negotiation". The platform has no soft skill taxonomy, so the text is free; it never changes a category or a grade. It has no leading or trailing whitespace and no line breaks. The server compares skills without regard to letter case. Plain text; clients show it as text, never as HTML. + ProfileEmployerName: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Name of the employer in one experience entry, as the candidate wrote it. It is personal data of the candidate's career. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + ProfileExperienceSummary: + type: string + minLength: 1 + maxLength: 1000 + description: Tasks and results of the candidate in one experience entry. It describes the work rather than a job title. It may contain line breaks and personal data of the candidate; it must not contain personal data of other people. Plain text; clients show it as text, never as HTML. + ProfileYearMonth: + type: string + minLength: 7 + maxLength: 7 + pattern: ^[0-9]{4}-(0[1-9]|1[0-2])$ + description: Calendar month in the `YYYY-MM` format, for example 2024-03. An experience period has month precision only, so the contract holds no exact date of employment. The server rejects a month that lies in the future. + examples: + - 2024-03 + ProfileFullNameClaim: + type: object + description: Full name of the candidate with its confirmation state and provenance. The value is personal data. It is disclosed to one organization only through the contact grant of the consent C4 and never appears in an organization-visible schema. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ContactFullName' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfileEmailClaim: + type: object + description: 'Contact email of the candidate with its confirmation state and provenance. It is personal data. It is a contact channel that the candidate gives, not the login of the account: the two may differ, the server never sends mail to it and never verifies it. `value` and `source` are null exactly when `status` is `unknown`.' + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/EmailAddress' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfilePhoneClaim: + type: object + description: Contact phone number of the candidate with its confirmation state and provenance. It is personal data, stored in the E.164 format of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ContactPhoneNumber' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfileTelegramClaim: + type: object + description: Telegram username of the candidate with its confirmation state and provenance. It is personal data, stored with the leading @ of the contact disclosure. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ContactTelegramUsername' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfileLocationClaim: + type: object + description: Place of the candidate with its confirmation state and provenance. It is personal data. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ProfileLocationName' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfileRelocationClaim: + type: object + description: Whether the candidate is ready to relocate, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; the server never assumes an answer. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + type: + - boolean + - 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfileSalaryMinimumClaim: + type: object + description: Lowest acceptable salary with its confirmation state and provenance. It is personal data that no organization reads. `value` and `source` are null exactly when `status` is `unknown`; the server never substitutes zero or a market estimate. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/ProfileClaimStatus' + value: + oneOf: + - $ref: '#/components/schemas/ProfileSalaryMinimum' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/ProfileClaimSource' + - type: 'null' + ProfileContacts: + type: object + description: Contact channels of the candidate. Each channel is a claim of its own, and the candidate fills in any subset. The kinds are the ones that the contact disclosure (consent C4) can pass on, with the same value formats, so a disclosure never has to convert or drop a stored value; adding a kind, such as a link to a code repository, is a contract change in both places. Contacts leave the profile only through a contact grant, never in a card or a search result. All values are personal data. + additionalProperties: false + required: + - email + - phone + - telegram + properties: + email: + $ref: '#/components/schemas/ProfileEmailClaim' + phone: + $ref: '#/components/schemas/ProfilePhoneClaim' + telegram: + $ref: '#/components/schemas/ProfileTelegramClaim' + ProfileTerms: + type: object + description: 'Conditions that the candidate wants: the place, readiness to relocate, and the lowest salary. Acceptable work formats are not repeated here; they are the `work_formats` of the questionnaire `WorkContext`, the only place that holds them. These are the candidate''s wishes, never the terms of an invitation, which an organization offers and which the invitation contract describes.' + additionalProperties: false + required: + - location + - relocation + - salary_minimum + properties: + location: + $ref: '#/components/schemas/ProfileLocationClaim' + relocation: + $ref: '#/components/schemas/ProfileRelocationClaim' + salary_minimum: + $ref: '#/components/schemas/ProfileSalaryMinimumClaim' + ProfileStackItem: + type: object + description: 'One technology tag of the candidate''s stack with its confirmation state and provenance. The profile stack is one list for the whole profile; the questionnaire holds the tags of each chosen specialization with the same `StackTag` meaning, and the two lists are independent: the server never copies one into the other. A tag is a descriptive attribute and never forms a category.' + additionalProperties: false + required: + - tag + - status + - source + properties: + tag: + $ref: '#/components/schemas/StackTag' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/schemas/ProfileClaimSource' + ProfileSoftSkillItem: + type: object + description: One soft skill of the candidate with its confirmation state and provenance. It is a claim; no assessment checks it. + additionalProperties: false + required: + - skill + - status + - source + properties: + skill: + $ref: '#/components/schemas/ProfileSoftSkill' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/schemas/ProfileClaimSource' + ProfileRoleItem: + type: object + description: 'One role of the candidate: a specialization of the catalog with the grade that the candidate claims for it. `self_assessed_grade` is a claim, the same one that the questionnaire calls `self_assessed_grade` for its at most two chosen specializations: it influences nothing but the display and never becomes a confirmed grade or a category. The questionnaire value starts the assessment and the profile value is what the profile shows; the two are saved separately and the server never copies one into the other. A confirmed grade comes only from an assessment result and appears in `confirmed_categories` of the profile, never in a role; unknown fields such as `confirmed_grade` or `category` are rejected.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - status + - source + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + self_assessed_grade: + description: Grade that the candidate claims in the specialization, or null when the candidate names none. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/schemas/ProfileClaimSource' + ProfileExperienceItem: + type: object + description: 'One entry of the candidate''s work history with its confirmation state and provenance. An entry describes the work by its specialization and tasks rather than by a job title, and it is a claim of trust level 0. It is different from the `CandidateExperience` of the questionnaire, which holds only the total months of commercial and academic experience of a chosen specialization as a hint for the assessment: the two are saved separately, and the server neither adds the entries up for the questionnaire nor fills the entries from it. An entry is personal data.' + additionalProperties: false + required: + - employer_name + - specialization + - started_on + - ended_on + - summary + - status + - source + properties: + employer_name: + description: Employer of the entry, or null when the candidate gives none. + oneOf: + - $ref: '#/components/schemas/ProfileEmployerName' + - type: 'null' + specialization: + $ref: '#/components/schemas/SpecializationCode' + started_on: + $ref: '#/components/schemas/ProfileYearMonth' + ended_on: + description: Last month of the work, or null when the candidate still works there. It is not earlier than `started_on`. + oneOf: + - $ref: '#/components/schemas/ProfileYearMonth' + - type: 'null' + summary: + description: Tasks and results of the entry, or null when the candidate gives none. + oneOf: + - $ref: '#/components/schemas/ProfileExperienceSummary' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/schemas/ProfileClaimSource' + ProfileExperienceOverlapStatus: + type: string + description: Whether the candidate confirmed that two overlapping periods are genuine parallel work. + enum: + - needs_confirmation + - confirmed + ProfileExperienceOverlap: + type: object + description: One pair of work history entries whose inclusive month ranges overlap. The indices refer to the experience array in this profile version. `confirmed` records an explicit acknowledgement for this pair of dates; otherwise the pair needs confirmation before a changed profile can be saved. + additionalProperties: false + required: + - first_index + - second_index + - status + properties: + first_index: + type: integer + minimum: 0 + maximum: 19 + second_index: + type: integer + minimum: 1 + maximum: 19 + status: + $ref: '#/components/schemas/ProfileExperienceOverlapStatus' + ProfileExperiencePeriod: + type: object + description: The exact month range of an experience entry, copied into a confirmation. + additionalProperties: false + required: + - started_on + - ended_on + properties: + started_on: + $ref: '#/components/schemas/ProfileYearMonth' + ended_on: + description: Last month of work, or null when the period is open-ended. + oneOf: + - $ref: '#/components/schemas/ProfileYearMonth' + - type: 'null' + ProfileParallelPeriodConfirmation: + type: object + description: Explicit acknowledgement that the two indexed experience periods are genuine parallel work. The indices and exact ranges must match the submitted experience array; expected_version binds the acknowledgement to the profile version the candidate read. + additionalProperties: false + required: + - first_index + - second_index + - first_period + - second_period + properties: + first_index: + type: integer + minimum: 0 + maximum: 19 + second_index: + type: integer + minimum: 1 + maximum: 19 + first_period: + $ref: '#/components/schemas/ProfileExperiencePeriod' + second_period: + $ref: '#/components/schemas/ProfileExperiencePeriod' + ProfileConfirmedCategory: + type: object + description: 'A category that an assessment result confirmed: the specialization with the confirmed grade. It is read-only and derived by the server from the assessment results of the candidate; no request carries it and the profile storage holds no such column, so neither a form nor an import can write a confirmed grade. It is separate from the claims of the profile and from the self-assessed grades in `roles`. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category that is not a validated measurement.' + additionalProperties: false + required: + - specialization + - grade + - basis + - confirmed_at + - attempt_id + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + basis: + $ref: '#/components/schemas/EvidenceBasis' + confirmed_at: + $ref: '#/components/schemas/Timestamp' + attempt_id: + type: string + format: uuid + description: Assessment attempt whose result confirmed the grade. The attempt belongs to the candidate. + CandidateProfile: + type: object + description: |- + The private profile of the current candidate: full name and contacts, stack, roles, work experience, soft skills, projects, and desired terms, each value with its confirmation state and provenance. It is personal data that only the candidate reads. It is never an organization-visible schema: an organization sees a candidate only through the anonymous card and, after an accepted invitation, through the contact grant, and no organization schema refers to this one. + Every value is a claim of trust level 0. The `self_assessed_grade` of a role is what the candidate says; the `confirmed_categories` list is what assessment results established, and the two are never mixed. A candidate who has not saved the profile gets version 0, every single field `unknown`, empty lists, and null `updated_at`. + The profile is manual by nature and complete without a file: no field requires a resume, the ML service, or an FSP account, and a candidate with none of them has the same fields. Work formats live in the questionnaire; a candidate's assessment starts from the questionnaire, not from this profile. + additionalProperties: false + required: + - version + - full_name + - contacts + - stack + - roles + - experience + - experience_overlaps + - soft_skills + - projects + - terms + - confirmed_categories + - updated_at + properties: + version: + $ref: '#/components/schemas/ProfileVersion' + full_name: + $ref: '#/components/schemas/ProfileFullNameClaim' + contacts: + $ref: '#/components/schemas/ProfileContacts' + stack: + type: array + maxItems: 30 + description: Technology tags in the order the candidate gave them, each tag at most once without regard to letter case. + items: + $ref: '#/components/schemas/ProfileStackItem' + roles: + type: array + maxItems: 9 + description: Roles in the order the candidate gave them, each specialization at most once. + items: + $ref: '#/components/schemas/ProfileRoleItem' + experience: + type: array + maxItems: 20 + description: Work history entries in the order the candidate gave them. + items: + $ref: '#/components/schemas/ProfileExperienceItem' + experience_overlaps: + type: array + maxItems: 190 + description: Every pair of overlapping experience periods, with its confirmation status. The indices refer to this version's experience array. + items: + $ref: '#/components/schemas/ProfileExperienceOverlap' + soft_skills: + type: array + maxItems: 10 + description: Soft skills in the order the candidate gave them, each skill at most once without regard to letter case. + items: + $ref: '#/components/schemas/ProfileSoftSkillItem' + projects: + type: array + maxItems: 10 + description: Projects in the order the candidate gave them, each repository address at most once. + items: + $ref: '#/components/schemas/ProfileProjectItem' + terms: + $ref: '#/components/schemas/ProfileTerms' + confirmed_categories: + type: array + maxItems: 9 + description: Categories that assessment results confirmed, at most one per specialization, in catalog order. Read-only and empty until an assessment confirms a grade. + items: + $ref: '#/components/schemas/ProfileConfirmedCategory' + updated_at: + description: Time of the last change, or null before the first save. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + ProfileFullNameInput: + type: object + description: Decision about the full name in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/ContactFullName' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileEmailInput: + type: object + description: Decision about the contact email in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/EmailAddress' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfilePhoneInput: + type: object + description: Decision about the contact phone number in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/ContactPhoneNumber' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileTelegramInput: + type: object + description: Decision about the Telegram username in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/ContactTelegramUsername' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileLocationInput: + type: object + description: Decision about the place in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/ProfileLocationName' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileRelocationInput: + type: object + description: Decision about readiness to relocate in a request; see CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + type: boolean + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileSalaryMinimumInput: + type: object + description: Decision about the lowest salary in a request; see CandidateProfileUpdate for the rules of `status`. The value is personal data. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/ProfileSalaryMinimum' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileContactsInput: + type: object + description: 'Decisions about the contact channels in a request. A channel sent as null is unknown: it is removed if it was set.' + additionalProperties: false + required: + - email + - phone + - telegram + properties: + email: + oneOf: + - $ref: '#/components/schemas/ProfileEmailInput' + - type: 'null' + phone: + oneOf: + - $ref: '#/components/schemas/ProfilePhoneInput' + - type: 'null' + telegram: + oneOf: + - $ref: '#/components/schemas/ProfileTelegramInput' + - type: 'null' + ProfileTermsInput: + type: object + description: 'Decisions about the desired terms in a request. A field sent as null is unknown: it is removed if it was set.' + additionalProperties: false + required: + - location + - relocation + - salary_minimum + properties: + location: + oneOf: + - $ref: '#/components/schemas/ProfileLocationInput' + - type: 'null' + relocation: + oneOf: + - $ref: '#/components/schemas/ProfileRelocationInput' + - type: 'null' + salary_minimum: + oneOf: + - $ref: '#/components/schemas/ProfileSalaryMinimumInput' + - type: 'null' + ProfileStackItemInput: + type: object + description: Decision about one stack tag in a request; see CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - tag + - status + properties: + tag: + $ref: '#/components/schemas/StackTag' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileSoftSkillItemInput: + type: object + description: Decision about one soft skill in a request; see CandidateProfileUpdate for the rules of `status`. + additionalProperties: false + required: + - skill + - status + properties: + skill: + $ref: '#/components/schemas/ProfileSoftSkill' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileRoleItemInput: + type: object + description: 'Decision about one role in a request; see CandidateProfileUpdate for the rules of `status`. The object has no confirmed grade and no category: unknown fields are rejected.' + additionalProperties: false + required: + - specialization + - self_assessed_grade + - status + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + self_assessed_grade: + description: Grade that the candidate claims, or null when the candidate names none. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileExperienceItemInput: + type: object + description: Decision about one work history entry in a request; see CandidateProfileUpdate for the rules of `status`. The server also requires `ended_on` not to precede `started_on` and no month to lie in the future, and answers 400 with the pointer of the month. + additionalProperties: false + required: + - employer_name + - specialization + - started_on + - ended_on + - summary + - status + properties: + employer_name: + oneOf: + - $ref: '#/components/schemas/ProfileEmployerName' + - type: 'null' + specialization: + $ref: '#/components/schemas/SpecializationCode' + started_on: + $ref: '#/components/schemas/ProfileYearMonth' + ended_on: + oneOf: + - $ref: '#/components/schemas/ProfileYearMonth' + - type: 'null' + summary: + oneOf: + - $ref: '#/components/schemas/ProfileExperienceSummary' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + CandidateProfileUpdate: + type: object + description: |- + Complete new state of the candidate profile. It replaces every stored value as a whole: a single field sent as null is unknown and is removed, and a list replaces the stored list; only `projects` may be omitted, which keeps the stored projects. The body is personal data. + Each value carries a decision `status`. `confirmed` sets a manual value or confirms a stored suggestion; confirming a suggestion with exactly its stored value keeps its origin and quote, and any other value makes the claim manual. `extracted` keeps a stored suggestion unconfirmed and is accepted only with exactly the stored value; any other use answers 400 with the pointer of that status, for example `/stack/1/status`. The provenance, the trust level, and the confirmed categories are not part of the request, and unknown fields are rejected, so a request can neither mark a claim as verified nor write a confirmed grade or a category. + additionalProperties: false + required: + - expected_version + - full_name + - contacts + - stack + - roles + - experience + - soft_skills + - terms + properties: + expected_version: + $ref: '#/components/schemas/ProfileVersion' + full_name: + oneOf: + - $ref: '#/components/schemas/ProfileFullNameInput' + - type: 'null' + contacts: + $ref: '#/components/schemas/ProfileContactsInput' + stack: + type: array + maxItems: 30 + description: Technology tags. The schema limits the count; the server also answers 400 with the pointer of a tag that repeats an earlier one without regard to letter case, for example `/stack/2/tag`. + items: + $ref: '#/components/schemas/ProfileStackItemInput' + roles: + type: array + maxItems: 9 + description: Roles. The server answers 400 with the pointer of a role whose specialization repeats an earlier one, for example `/roles/1/specialization`. + items: + $ref: '#/components/schemas/ProfileRoleItemInput' + experience: + type: array + maxItems: 20 + description: Work history entries. + items: + $ref: '#/components/schemas/ProfileExperienceItemInput' + confirmed_parallel_periods: + type: array + maxItems: 190 + description: Explicit acknowledgements for overlapping periods. Each pair must use distinct in-range indices and repeat the exact normalized started_on and ended_on values of those entries in this body. A changed or reordered period needs a new acknowledgement. The server retains a previous acknowledgement only for the same indices and dates. Duplicate pairs and pairs that do not overlap are rejected. + items: + $ref: '#/components/schemas/ProfileParallelPeriodConfirmation' + soft_skills: + type: array + maxItems: 10 + description: Soft skills. The server answers 400 with the pointer of a skill that repeats an earlier one without regard to letter case. + items: + $ref: '#/components/schemas/ProfileSoftSkillItemInput' + projects: + type: array + maxItems: 10 + description: 'Projects. Unlike the other lists this one is optional: a body without `projects` keeps the stored projects unchanged, so a client that does not know the section never deletes it, and an array, including an empty one, replaces the stored list. A new or changed repository address schedules a server check on the public GitHub API after the save commits; the save itself never waits for GitHub.' + items: + $ref: '#/components/schemas/ProfileProjectItemInput' + terms: + $ref: '#/components/schemas/ProfileTermsInput' + AssessmentMode: + type: string + description: |- + Method of an assessment attempt. For a real assessment, the server selects demo_basic or adaptive from the published bank. A candidate may explicitly request demo_express, which uses a separate training policy and creates no qualification evidence. + + - demo_basic: a fixed form of reviewed demo items scored by their keys against the pass mark of the versioned basic grading policy. It computes no ability estimate, standard error, or probability, so every uncertainty field of its result is null, its thresholds are uncalibrated, and its decision is binary: it never offers an additional practice. + - adaptive: the adaptive test on task families with an ability estimate, its standard error, and the probability of reaching the grade threshold, as the versioned assessment policy defines them. A probability in the band below confirmation offers one additional practice in the same attempt. + - demo_express: an interactive 3 to 5 minute training run under a separate policy. It does not assign a category or percentile, count toward the real-assessment quota, or create qualification evidence. + + Adding a value is a contract change. + enum: + - demo_basic + - demo_express + - adaptive + AssessmentAttemptVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of an assessment attempt. A new attempt has version 1, and each committed change advances it by exactly one: an accepted answer, a practice submission or resubmission, a verdict, a decision of finalize, an explicit work-session start, and a server-side transition such as expiry or automatic finalization. Reads never change the attempt. A rejected command and a repeat that stores nothing leave it unchanged. Commands send the version they read as `expected_version`.' + examples: + - 4 + AssessmentAttemptState: + type: string + description: |- + Lifecycle state of an attempt and the commands it accepts. + + - in_progress: items are being answered; `current_item` is the item to answer. Accepts SubmitMyAssessmentAnswer for that item. + - practice_pending: the item part is finished, and the main practice has no finished verdict yet: it is not submitted, its verdict is pending in the sandbox, or the sandbox failed and the practice can be submitted again. Accepts SubmitMyAssessmentAnswer with the practice item while its status is `not_started` or `failed`. No grade is confirmed while the practice is unfinished, even when the adaptive stop rule has already ended the item part. + - additional_practice_pending: adaptive only. Finalize found the probability of reaching the grade in the band below confirmation, so the attempt offers one additional practice without spending a new attempt; it keeps the time and session limits of the attempt. Accepts SubmitMyAssessmentAnswer with the additional practice item while its status is `not_started` or `failed`, and FinalizeMyAssessmentAttempt in the same statuses, which declines the offer and decides `not_confirmed` with the current evidence. + - ready_to_finalize: every required part is done, including a submitted additional practice with a finished verdict. Accepts FinalizeMyAssessmentAttempt. + - completed: a decision was made; the result is available. + - expired: the time or session limit passed before the candidate finished the required parts. The result is available and confirms no grade. + - insufficient_bank: the published bank could not supply the items required for coverage within the limit, and the attempt ended without a confirmed grade instead of repeating families. The result is available. + + When `expires_at` passes or the session limit is reached, a read returns the stored state without changing it. A command or background transition commits any due outcome and advances the version. A practice submitted before the limit and still `pending` is graded first. Then `ready_to_finalize` becomes `completed`; `additional_practice_pending` with the additional practice not submitted is finalized as declined and becomes `completed` with `not_confirmed`; `in_progress` and `practice_pending` become `expired`, with the result reason `expired` or `practice_incomplete`; and when the latest submission of a practice ended `failed`, the attempt becomes `expired` with the reason `sandbox_unavailable`, which is not the candidate's fault. `completed`, `expired`, and `insufficient_bank` are terminal and accept no command except the repeat of finalize described on FinalizeMyAssessmentAttempt. Adding a value is a contract change. + enum: + - in_progress + - practice_pending + - additional_practice_pending + - ready_to_finalize + - completed + - expired + - insufficient_bank + AssessmentVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Opaque identifier of a published version, for example `backend-demo.2026-10.1`. Clients show it as text and never parse it. + AssessmentVersions: + type: object + description: Versions fixed when the attempt was created. They never change during the attempt, and a result is always reproduced from the stored answers with these versions; a later policy, bank, or algorithm version does not rewrite it. + additionalProperties: false + required: + - policy_version + - bank_version + - algorithm_version + properties: + policy_version: + type: integer + format: int32 + minimum: 1 + description: 'Number of the `product` policy version whose assessment rules apply: thresholds, stop rules, item limits, time and session limits, and retry intervals.' + bank_version: + $ref: '#/components/schemas/AssessmentVersionLabel' + algorithm_version: + $ref: '#/components/schemas/AssessmentVersionLabel' + AssessmentSessions: + type: object + description: |- + Work sessions of the attempt, as the policy version limits them, for example two sessions within the time limit. + + Session 1 starts with attempt creation. After it ends due to `idle_timeout_seconds` of inactivity, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. GetMyAssessmentAttempt and GetMyAssessmentResult are read-only and never start a session. The session command checks the attempt deadline and `max_sessions`; when either limit has passed, it records the due terminal transition and returns the resulting attempt. Reads of terminal attempts do not change them. + additionalProperties: false + required: + - used + - max + - idle_timeout_seconds + properties: + used: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Sessions started so far, including the current one. + max: + type: integer + format: int32 + minimum: 1 + maximum: 10 + idle_timeout_seconds: + type: integer + format: int32 + minimum: 60 + maximum: 86400 + description: Inactivity after which the current session ends. + AssessmentAttemptCreate: + description: Start a real assessment, a corrective attempt in an existing chain, or an explicit training run. The required `kind` discriminator selects one of the three request shapes; `mode` remains server-selected for real assessments. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedAttemptCreate' + - $ref: '#/components/schemas/AssessmentCorrectiveAttemptCreate' + - $ref: '#/components/schemas/AssessmentExpressAttemptCreate' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedAttemptCreate' + corrective: '#/components/schemas/AssessmentCorrectiveAttemptCreate' + demo_express: '#/components/schemas/AssessmentExpressAttemptCreate' + AssessmentAttemptSessionStart: + type: object + description: Start or resume a work session using the attempt version last read by the candidate. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + AssessmentItemId: + type: string + format: uuid + description: Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed. + AssessmentOptionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque identifier of a choice option or an order element within one item instance. It is unrelated to the position or correctness of the option. + AssessmentOption: + type: object + description: Choice option or order element. Plain text. + additionalProperties: false + required: + - id + - text + properties: + id: + $ref: '#/components/schemas/AssessmentOptionId' + text: + type: string + minLength: 1 + maxLength: 2000 + description: Text of the option; the client shows it as text, never as HTML. + ChoiceItemContent: + type: object + description: Choose one option, or several when `multiple` is true. The content never says which options are correct or how many are. + additionalProperties: false + required: + - format + - options + - multiple + properties: + format: + type: string + enum: + - choice + options: + type: array + minItems: 2 + maxItems: 10 + description: Options in the order of this instance. + items: + $ref: '#/components/schemas/AssessmentOption' + multiple: + type: boolean + description: 'Whether more than one option may be selected. It is a property of the task family, fixed for every variant, and never derived from the key: a multiple-choice variant may have a single correct option.' + NumberItemContent: + type: object + description: Enter a number, optionally in the given unit. + additionalProperties: false + required: + - format + - unit + properties: + format: + type: string + enum: + - number + unit: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + description: Unit of the expected value, for example `ms`, or null. + StringItemContent: + type: object + description: Enter a short string, such as a command, a header name, or an address. + additionalProperties: false + required: + - format + - max_length + properties: + format: + type: string + enum: + - string + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 500 + description: Maximum length of the answer in characters. It is an input limit of the task family, never derived from the key, so it does not reveal the length of the correct answer. + OrderItemContent: + type: object + description: Put every element into the right order. The elements arrive in the order of this instance, which is never the answer. + additionalProperties: false + required: + - format + - elements + properties: + format: + type: string + enum: + - order + elements: + type: array + minItems: 2 + maxItems: 20 + items: + $ref: '#/components/schemas/AssessmentOption' + CodeLine: + type: object + description: One numbered line of a code or configuration fragment. Plain text. + additionalProperties: false + required: + - number + - text + properties: + number: + type: integer + format: int32 + minimum: 1 + maximum: 500 + text: + type: string + maxLength: 1000 + FindErrorItemContent: + type: object + description: Find the lines with the error in a code or configuration fragment and select up to `max_selections` line numbers. + additionalProperties: false + required: + - format + - syntax + - lines + - max_selections + properties: + format: + type: string + enum: + - find_error + syntax: + type: + - string + - 'null' + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Highlighting hint such as `go`, `python`, or `cisco_ios`, or null. + lines: + type: array + minItems: 1 + maxItems: 500 + description: Lines numbered from 1 in order. + items: + $ref: '#/components/schemas/CodeLine' + max_selections: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Maximum number of lines the answer may select. It is a limit of the task family, fixed for every variant and never derived from the key; it is not the number of wrong lines. + ConfigurationItemContent: + type: object + description: Write or fix a configuration. The server checks the submitted text with the computed key or reference check of the task family; it never executes it as code. + additionalProperties: false + required: + - format + - syntax + - initial_config + - max_length + properties: + format: + type: string + enum: + - configuration + syntax: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9_+-]+$ + description: Configuration syntax such as `cisco_ios`, `nginx`, or `yaml`. + initial_config: + type: string + maxLength: 20000 + description: Starting text to edit; empty when the candidate writes it from scratch. + max_length: + type: integer + format: int32 + minimum: 1 + maximum: 20000 + description: Maximum length of the submitted configuration in characters, an input limit of the task family that is never derived from the key. + PracticeExample: + type: object + description: 'Public example of the practice task: an input and its expected output. Hidden checks are never listed.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeItemContent: + type: object + description: Code practice. The candidate submits one final solution, which runs in the isolated sandbox against three groups of hidden checks. The content lists only the statement, the allowed languages, and public examples; hidden checks, their inputs, and seeds never reach the client. + additionalProperties: false + required: + - format + - languages + - public_examples + - max_source_length + properties: + format: + type: string + enum: + - practice + languages: + type: array + maxItems: 2 + uniqueItems: true + description: Languages the solution may use. Empty when the task does not offer a choice; the submission then sends a null language. + items: + $ref: '#/components/schemas/TaskLanguage' + public_examples: + type: array + maxItems: 10 + items: + $ref: '#/components/schemas/PracticeExample' + max_source_length: + type: integer + format: int32 + minimum: 1 + maximum: 65536 + description: Maximum length of the solution source in characters. + ItemContent: + description: 'Format-specific part of an item, selected by `format`. It holds only what the candidate needs to answer: never an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check. Limits such as `multiple`, `max_selections`, and `max_length` belong to the format or the task family and never reveal the key.' + oneOf: + - $ref: '#/components/schemas/ChoiceItemContent' + - $ref: '#/components/schemas/NumberItemContent' + - $ref: '#/components/schemas/StringItemContent' + - $ref: '#/components/schemas/OrderItemContent' + - $ref: '#/components/schemas/FindErrorItemContent' + - $ref: '#/components/schemas/ConfigurationItemContent' + - $ref: '#/components/schemas/PracticeItemContent' + - $ref: '#/components/schemas/LabItemContent' + AssessmentItem: + type: object + description: 'Item instance served to the candidate. The variant is fixed when it is first served: a reload, a retried request, or a resumed session returns the same instance with the same text and option order. The item never says whether an earlier answer was correct, and seed items, which are not scored, are indistinguishable from scored ones.' + additionalProperties: false + required: + - id + - sequence + - prompt + - content + properties: + id: + $ref: '#/components/schemas/AssessmentItemId' + sequence: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: Position of the item in the attempt, from 1. + prompt: + type: string + minLength: 1 + maxLength: 20000 + description: Statement in Russian. Plain text with line breaks; the client shows it as text, never as HTML. + content: + $ref: '#/components/schemas/ItemContent' + AssessmentProgress: + type: object + description: Progress of the item part. It counts seed items like scored ones, so it does not reveal which items are scored. An adaptive attempt may end its item part before `max_items` by its stop rule. A finalize refused as premature does not list the unfinished parts; the client reads them here, in `current_item`, and in `practices`. + additionalProperties: false + required: + - answered_items + - max_items + properties: + answered_items: + type: integer + format: int32 + minimum: 0 + maximum: 100 + max_items: + type: integer + format: int32 + minimum: 1 + maximum: 100 + description: 'Item limit of the attempt: the form size in demo_basic, or the policy limit of scored and seed items together in adaptive.' + PracticeKind: + type: string + description: |- + Role of a practice in the attempt. + + - main: the practice that every attempt with practice requires before a decision. + - additional: adaptive only; offered by finalize when the probability of reaching the grade is in the band below confirmation. It continues the same attempt and spends no new attempt. + + Adding a value is a contract change. + enum: + - main + - additional + PracticeStatus: + type: string + description: |- + State of a practice. + + - not_started: no solution was submitted yet. + - pending: the submitted solution is queued or running in the sandbox. + - finished: the sandbox ran the solution and returned a verdict; `verdict` holds it. Every outcome caused by the solution itself, such as a compilation error, a runtime error, a time limit, or a memory limit, is `finished` with the affected groups not passed. + - failed: the sandbox infrastructure could not run the solution, for example because its queue was full or an executor broke, independently of the solution. The failure is not the candidate's and consumes nothing; the practice can be submitted again. + enum: + - not_started + - pending + - finished + - failed + PracticeFailureReason: + type: string + description: 'Why the sandbox infrastructure returned no verdict: `sandbox_busy` when its queue was full, `sandbox_error` for an infrastructure failure such as a broken executor. Neither depends on the solution; a solution that fails to compile, crashes, or exceeds a limit gets a `finished` verdict instead, so a failure never acts as an oracle for hidden checks.' + enum: + - sandbox_busy + - sandbox_error + PracticeGroupResult: + type: object + description: Outcome of one hidden check group. It never contains the checks themselves. + additionalProperties: false + required: + - group + - passed + properties: + group: + type: integer + format: int32 + minimum: 1 + maximum: 3 + passed: + type: boolean + PracticeVerdict: + type: object + description: 'Verdict of a practice solution on the hidden checks: the score 0-3, one point for each passed group. The hidden checks, their inputs and outputs, error output, and seeds are never returned.' + additionalProperties: false + required: + - score + - max_score + - groups + properties: + score: + type: integer + format: int32 + minimum: 0 + maximum: 3 + max_score: + type: integer + format: int32 + minimum: 3 + maximum: 3 + groups: + type: array + minItems: 3 + maxItems: 3 + items: + $ref: '#/components/schemas/PracticeGroupResult' + AssessmentPractice: + type: object + description: Practice of the attempt. Its verdict is shown only after the submission; the solution time is kept as a separate label and never enters the ability estimate or the grade decision. + additionalProperties: false + required: + - kind + - item_id + - status + - submitted_at + - verdict + - failure_reason + properties: + kind: + $ref: '#/components/schemas/PracticeKind' + item_id: + $ref: '#/components/schemas/AssessmentItemId' + status: + $ref: '#/components/schemas/PracticeStatus' + submitted_at: + description: Time of the latest submission, or null before the first one. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + verdict: + description: The verdict when `status` is `finished`, otherwise null. + oneOf: + - $ref: '#/components/schemas/PracticeVerdict' + - type: 'null' + failure_reason: + description: The reason when `status` is `failed`, otherwise null. + oneOf: + - $ref: '#/components/schemas/PracticeFailureReason' + - type: 'null' + PracticeRunTest: + type: object + description: 'One test of the candidate for a debug run: an input and the output the candidate expects. It is compared with the checker of the task.' + additionalProperties: false + required: + - input + - expected_output + properties: + input: + type: string + maxLength: 10000 + expected_output: + type: string + maxLength: 10000 + PracticeRunCreate: + type: object + description: Debug run of a practice solution against the public examples of the task and up to ten tests of the candidate. It never runs a hidden check and never changes the practice state, the verdict, or the attempt version. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + - language + - source_code + properties: + item_id: + $ref: '#/components/schemas/AssessmentItemId' + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + source_code: + type: string + minLength: 1 + maxLength: 65536 + tests: + type: array + maxItems: 10 + description: Tests of the candidate, run after the public examples. + items: + $ref: '#/components/schemas/PracticeRunTest' + PracticeRunState: + type: string + description: |- + State of a debug run. + + - queued: the run waits in the sandbox queue. + - running: the sandbox runs it. + - finished: `result` holds the outcome of the public examples and the tests of the candidate. + - failed: the sandbox infrastructure could not run it, independently of the solution; `failure_reason` is `sandbox_error`. Start a new run. + + Adding a value is a contract change. + enum: + - queued + - running + - finished + - failed + PracticeRunOutcome: + type: string + description: Outcome of a run or one of its tests. Every outcome caused by the solution, such as a compilation error, a crash, or a limit, is a finished run with this outcome; an infrastructure failure is a failed run instead. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + PracticeRunTestSource: + type: string + description: 'Where a test of a debug run comes from: a public example of the task or a test of the candidate.' + enum: + - example + - candidate + PracticeRunTestResult: + type: object + description: Outcome of one evaluated test. The tests of a source stop at the first failed one, so later tests of that source are not listed. + additionalProperties: false + required: + - source + - index + - outcome + - time_ms + - memory_kb + - diagnostic + properties: + source: + $ref: '#/components/schemas/PracticeRunTestSource' + index: + type: integer + format: int32 + minimum: 1 + maximum: 10 + description: Position of the test in its source, from 1. + outcome: + $ref: '#/components/schemas/PracticeRunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + diagnostic: + description: Truncated error output of a failed test, or null. + oneOf: + - type: string + maxLength: 2048 + - type: 'null' + PracticeRunResult: + type: object + description: Result of a debug run on the public examples and the tests of the candidate. It never contains a hidden check, its outcome, or the score. + additionalProperties: false + required: + - outcome + - compile_diagnostic + - tests + properties: + outcome: + $ref: '#/components/schemas/PracticeRunOutcome' + compile_diagnostic: + description: The compiler message when `outcome` is `compile_error`, otherwise null. + oneOf: + - type: string + maxLength: 4096 + - type: 'null' + tests: + type: array + maxItems: 20 + items: + $ref: '#/components/schemas/PracticeRunTestResult' + PracticeRun: + type: object + description: Debug run of a practice solution. It shows only the public examples and the tests of the candidate; hidden checks are never run, listed, or scored by a debug run. + additionalProperties: false + required: + - id + - item_id + - state + - created_at + - finished_at + - failure_reason + - result + properties: + id: + type: string + format: uuid + description: Identifier of the run. + item_id: + $ref: '#/components/schemas/AssessmentItemId' + state: + $ref: '#/components/schemas/PracticeRunState' + created_at: + $ref: '#/components/schemas/Timestamp' + finished_at: + description: Time the run reached `finished` or `failed`, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + failure_reason: + description: '`sandbox_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/components/schemas/PracticeFailureReason' + - type: 'null' + result: + description: The result when `state` is `finished`, otherwise null. + oneOf: + - $ref: '#/components/schemas/PracticeRunResult' + - type: 'null' + AssessmentAttempt: + description: Candidate view of a real assessment, a corrective real assessment, or a demo_express training run. The variants keep training output separate from qualification attempts. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedAttempt' + - $ref: '#/components/schemas/AssessmentCorrectiveAttempt' + - $ref: '#/components/schemas/AssessmentExpressAttempt' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedAttempt' + corrective: '#/components/schemas/AssessmentCorrectiveAttempt' + demo_express: '#/components/schemas/AssessmentExpressAttempt' + ChoiceAnswer: + type: object + description: 'Selected options of a choice item: exactly one unless the item allows several. Two answers are equal when they select the same set of options, in any order.' + additionalProperties: false + required: + - format + - option_ids + properties: + format: + type: string + enum: + - choice + option_ids: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentOptionId' + NumberAnswer: + type: object + description: Numeric answer in the unit of the item. Two answers are equal when their decoded values are numerically equal, so 254 and 254.0 are the same answer. + additionalProperties: false + required: + - format + - number + properties: + format: + type: string + enum: + - number + number: + type: number + format: double + x-ogen-type: lincodex/backend/internal/adapter/primary/http/apitypes.AssessmentNumber + StringAnswer: + type: object + description: String answer, at most the `max_length` of the item. Two answers are equal only when their texts are identical; no trimming, case folding, or Unicode normalization applies to that comparison. + additionalProperties: false + required: + - format + - text + properties: + format: + type: string + enum: + - string + text: + type: string + minLength: 1 + maxLength: 500 + OrderAnswer: + type: object + description: Every element of the item exactly once, in the chosen order. Two answers are equal only when the sequences are identical. + additionalProperties: false + required: + - format + - element_ids + properties: + format: + type: string + enum: + - order + element_ids: + type: array + minItems: 2 + maxItems: 20 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentOptionId' + FindErrorAnswer: + type: object + description: Selected line numbers, at most the `max_selections` of the item. Two answers are equal when they select the same set of lines, in any order. + additionalProperties: false + required: + - format + - line_numbers + properties: + format: + type: string + enum: + - find_error + line_numbers: + type: array + minItems: 1 + maxItems: 10 + uniqueItems: true + items: + type: integer + format: int32 + minimum: 1 + maximum: 500 + ConfigurationAnswer: + type: object + description: Submitted configuration text, at most the `max_length` of the item. Two answers are equal only when their texts are identical, including whitespace and line breaks. + additionalProperties: false + required: + - format + - config + properties: + format: + type: string + enum: + - configuration + config: + type: string + minLength: 1 + maxLength: 20000 + PracticeAnswer: + type: object + description: Practice solution. It runs in the isolated sandbox without network access, secrets, or business data. Two submissions are equal only when the language is the same and the source texts are identical. The source is never echoed in a response or a problem. + additionalProperties: false + required: + - format + - language + - source_code + properties: + format: + type: string + enum: + - practice + language: + description: One of the `languages` of the practice item, or null when the item offers none. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + source_code: + type: string + minLength: 1 + maxLength: 65536 + AssessmentAnswer: + description: 'Candidate answer, selected by `format`, which must equal the format of the answered item. It carries only the answer: no score, duration, correctness flag, or seed. The server records the times itself and scores the answer with the key of the fixed item instance. Each format defines when two answers are equal, which decides whether a repeated submission is the same answer.' + oneOf: + - $ref: '#/components/schemas/ChoiceAnswer' + - $ref: '#/components/schemas/NumberAnswer' + - $ref: '#/components/schemas/StringAnswer' + - $ref: '#/components/schemas/OrderAnswer' + - $ref: '#/components/schemas/FindErrorAnswer' + - $ref: '#/components/schemas/ConfigurationAnswer' + - $ref: '#/components/schemas/PracticeAnswer' + AssessmentAnswerSubmission: + type: object + description: Answer to one item of the attempt. Unknown fields are rejected, so a request cannot send a score, a duration, or a correctness flag. + additionalProperties: false + required: + - expected_version + - item_id + - answer + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + item_id: + $ref: '#/components/schemas/AssessmentItemId' + answer: + $ref: '#/components/schemas/AssessmentAnswer' + AssessmentSignalEvent: + description: One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention. + oneOf: + - $ref: '#/components/schemas/AssessmentFocusLossSignal' + - $ref: '#/components/schemas/AssessmentClipboardSignal' + - $ref: '#/components/schemas/AssessmentFullscreenExitSignal' + - $ref: '#/components/schemas/AssessmentCaptureSignal' + discriminator: + propertyName: kind + mapping: + focus_loss: '#/components/schemas/AssessmentFocusLossSignal' + copy: '#/components/schemas/AssessmentClipboardSignal' + paste: '#/components/schemas/AssessmentClipboardSignal' + cut: '#/components/schemas/AssessmentClipboardSignal' + fullscreen_exit: '#/components/schemas/AssessmentFullscreenExitSignal' + screenshot_key: '#/components/schemas/AssessmentCaptureSignal' + devtools_open: '#/components/schemas/AssessmentCaptureSignal' + AssessmentFocusLossSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - duration_ms + properties: + kind: + type: string + enum: + - focus_loss + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + duration_ms: + type: integer + format: int32 + minimum: 1 + maximum: 259200000 + description: Client-measured duration away from the assessment tab or window, in milliseconds. + AssessmentClipboardSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + - size_bytes + properties: + kind: + type: string + enum: + - copy + - paste + - cut + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + size_bytes: + type: integer + format: int32 + minimum: 0 + maximum: 2147483647 + description: Size only; clipboard and selection contents are never transmitted or retained. For `paste` it is the UTF-8 byte count of the pasted plain text plus the byte size of pasted files, counted on the device from the paste event. For `copy` and `cut` it is the selection length in UTF-16 code units taken from the selection offsets of a form field, or zero when the field offsets are unavailable; it is an approximate size and the selected text is not read. The server applies no conversion and treats the value as an order-of-magnitude indicator. + AssessmentFullscreenExitSignal: + type: object + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - fullscreen_exit + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + AssessmentSignalBatch: + type: object + description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events. + additionalProperties: false + required: + - events + properties: + events: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/components/schemas/AssessmentSignalEvent' + AssessmentSignalReceipt: + type: object + description: Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, or result band. + additionalProperties: false + required: + - status + - accepted_events + - received_at + properties: + status: + type: string + enum: + - accepted + - saturated + description: '`saturated` means no event from this batch was stored because the attempt''s bounded evidence storage is full.' + accepted_events: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of events stored from this batch; zero when saturated. + received_at: + $ref: '#/components/schemas/Timestamp' + AssessmentFinalization: + type: object + description: Command to finalize the attempt. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + AssessmentOutcome: + type: string + description: |- + Grade decision of the attempt. + + - confirmed: the target grade is confirmed by the rule of the recorded policy version. + - not_confirmed: the evidence is below the rule, including an adaptive attempt whose probability stayed below confirmation after the additional practice, or whose additional practice was declined or not submitted in time. The previously confirmed grade, if any, stays in force. + - not_determined: the attempt gives no decision; `not_determined_reason` says why. The previously confirmed grade stays in force. + + A failed, expired, or flagged attempt never lowers a confirmed grade. + enum: + - confirmed + - not_confirmed + - not_determined + AssessmentNotDeterminedReason: + type: string + description: |- + Why an attempt gives no decision. One root quota slot is reserved when a real root attempt starts; corrective checks in its chain do not reserve another slot. + + - expired: the time or session limit passed before the candidate finished the item part. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - practice_incomplete: the item part was done, but the candidate did not submit the main practice before the limit. Retry timing follows the recorded policy; a correction uses the existing root slot and does not reset the chain deadline or 30/90-day timers. + - insufficient_bank: the bank could not supply required coverage. A preflight refusal creates no attempt or root slot; a bank failure in an existing chain does not create a free new chain or another root slot. + - sandbox_unavailable: the latest submission of a required or additional practice ended `failed` because of the sandbox infrastructure, and the limit passed before a verdict. It is a platform fault and does not create a new root slot or a free chain. + enum: + - expired + - practice_incomplete + - insufficient_bank + - sandbox_unavailable + AssessmentStrength: + type: string + description: 'Strength of an adaptive confirmation: `high` or `medium`, by the probability bands of the recorded policy version.' + enum: + - high + - medium + CalibrationStatus: + type: string + description: 'Whether the thresholds of the recorded policy version are empirically calibrated. `uncalibrated` results are provisional: their thresholds come from expert judgement, and their probabilities are not claimed to be calibrated.' + enum: + - uncalibrated + - calibrated + AssessmentLimitation: + type: string + description: |- + Known limitation of the method behind a real-assessment result, shown with the result. + + - uncalibrated_thresholds: the thresholds are not yet validated on a pilot. + - demo_bank: the result comes from the small reviewed demo bank. + - practice_not_included: the attempt had no code practice because the sandbox was not enabled. + - unproctored: the attempt was taken online without supervision. + Adding a value is a contract change. + enum: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored + AssessmentInterval: + type: object + description: Interval on the ability scale. + additionalProperties: false + required: + - low + - high + properties: + low: + type: number + format: double + high: + type: number + format: double + AssessmentUncertainty: + type: object + description: 'Ability estimate of an adaptive attempt and its uncertainty: the EAP estimate on the specialization scale, its standard error, the 95% interval, and the probability of reaching the target grade threshold. The interval is reported but is not a separate stop condition.' + additionalProperties: false + required: + - theta + - standard_error + - interval_95 + - p_grade + properties: + theta: + type: number + format: double + standard_error: + type: number + format: double + minimum: 0 + interval_95: + $ref: '#/components/schemas/AssessmentInterval' + p_grade: + type: number + format: double + minimum: 0 + maximum: 1 + description: Probability of reaching the threshold of the target grade. + BasicScore: + type: object + description: Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass mark comes from that policy version and never from the handler. + additionalProperties: false + required: + - points + - max_points + - pass_points + properties: + points: + type: integer + format: int32 + minimum: 0 + max_points: + type: integer + format: int32 + minimum: 1 + pass_points: + type: integer + format: int32 + minimum: 1 + AssessmentGap: + type: object + description: Domain of the specialization where the evidence was weak. + additionalProperties: false + required: + - domain + - title + properties: + domain: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9_]+$ + description: Stable domain code of the bank blueprint. + title: + type: string + minLength: 1 + maxLength: 200 + description: Display name in Russian. Plain text. + AssessmentDurations: + type: object + description: 'Working time recorded by the server. It is a separate label: it never enters the ability estimate or the grade decision.' + additionalProperties: false + required: + - items_seconds + - practice_seconds + properties: + items_seconds: + type: integer + format: int32 + minimum: 0 + practice_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 0 + description: Time on all practices with a verdict, or null when no practice has one. + AssessmentPracticeResult: + type: object + description: Verdict of one practice of the attempt. + additionalProperties: false + required: + - kind + - verdict + properties: + kind: + $ref: '#/components/schemas/PracticeKind' + verdict: + $ref: '#/components/schemas/PracticeVerdict' + AssessmentNextAction: + type: string + description: |- + Step that the candidate may take next. + + - retake_same_grade: test the same grade again from `available_at`. + - take_lower_grade: test the lower `grade`. After a failure, including the first test, it is allowed at once, outside the same-grade retry interval. + - accept_lower_grade: accept the lower `grade` on the evidence of this attempt, when the data are sufficient (the command is planned). + - take_higher_grade: test the higher `grade` from `available_at`. A first confirmation is not a promotion, so after it `available_at` is null; after a promotion the next one waits for the promotion interval of the policy. + enum: + - retake_same_grade + - take_lower_grade + - accept_lower_grade + - take_higher_grade + AssessmentNextStep: + type: object + description: Step that the server allows after this result, computed when it was decided. + additionalProperties: false + required: + - action + - grade + - available_at + properties: + action: + $ref: '#/components/schemas/AssessmentNextAction' + grade: + $ref: '#/components/schemas/GradeCode' + available_at: + description: First time the step is allowed, or null when it is allowed now. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + AssessmentResult: + description: Immutable result of a terminal assessment attempt. The result shape distinguishes real grade decisions from demo_express training output. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedResult' + - $ref: '#/components/schemas/AssessmentCorrectiveResult' + - $ref: '#/components/schemas/AssessmentExpressResult' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedResult' + corrective: '#/components/schemas/AssessmentCorrectiveResult' + demo_express: '#/components/schemas/AssessmentExpressResult' + AssessmentRealResult: + description: A completed root or corrective result. Training-only demo_express results are excluded from qualification history. + oneOf: + - $ref: '#/components/schemas/AssessmentQualifiedResult' + - $ref: '#/components/schemas/AssessmentCorrectiveResult' + discriminator: + propertyName: kind + mapping: + root: '#/components/schemas/AssessmentQualifiedResult' + corrective: '#/components/schemas/AssessmentCorrectiveResult' + AssessmentCategoryDecisionView: + type: object + description: Category decision captured when this result was stored. It is absent from legacy v1 results because their current grade cannot be inferred later. It never exposes review identifiers, private answers, or the candidate's current category after this decision. + additionalProperties: false + required: + - status + - previous_confirmed_grade + - current_confirmed_grade + - method + - source + - calibration_status + properties: + status: + type: string + enum: + - not_eligible + - not_confirmed + - assigned + - unchanged + previous_confirmed_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + current_confirmed_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + method: + oneOf: + - type: string + enum: + - demo_basic_pass_mark + - type: 'null' + source: + oneOf: + - type: string + enum: + - synthetic_demo + - type: 'null' + calibration_status: + oneOf: + - $ref: '#/components/schemas/CalibrationStatus' + - type: 'null' + AssessmentResultHistoryPage: + type: object + description: Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending. Legacy v1 results omit category_decision. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 50 + items: + $ref: '#/components/schemas/AssessmentRealResult' + page: + $ref: '#/components/schemas/PageInfo' + AssessmentGradeAvailabilityStatus: + type: string + description: |- + Whether an attempt for the grade can start now. + + - available: CreateMyAssessmentAttempt can start it. + - active_attempt: the specialization has an active attempt; resume it by `active_attempt_id`. + - cooldown: a retry or promotion interval or the attempt limit of the policy blocks it until `available_at`. Attempts that ended as `insufficient_bank` or `sandbox_unavailable` never cause it. + - insufficient_bank: no published bank of the category, or not enough unseen families to cover the blueprint for this candidate. The server never fills the gap by repeating families. + enum: + - available + - active_attempt + - cooldown + - insufficient_bank + AssessmentGradeAvailability: + type: object + description: Availability of an attempt for one grade of a specialization, with the limits that an attempt would have, so the client can show them before the start. The limit fields are null when the status is `insufficient_bank` or the policy defines no such limit. + additionalProperties: false + required: + - grade + - status + - mode + - available_at + - time_limit_seconds + - max_sessions + - max_items + - practice_required + properties: + grade: + $ref: '#/components/schemas/GradeCode' + status: + $ref: '#/components/schemas/AssessmentGradeAvailabilityStatus' + mode: + description: Real-assessment mode that the server would use, or null when the status is `insufficient_bank`. `demo_express` is not a category assessment and is never returned here. + oneOf: + - $ref: '#/components/schemas/AssessmentRealMode' + - type: 'null' + available_at: + description: When the status is `cooldown`, the first time the attempt can start; otherwise null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + time_limit_seconds: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: Time from the start to `expires_at`. + max_sessions: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 10 + description: Session limit within the time limit. + max_items: + type: + - integer + - 'null' + format: int32 + minimum: 1 + maximum: 100 + description: Item limit, as in `AssessmentProgress.max_items`. + practice_required: + type: + - boolean + - 'null' + description: Whether the attempt would include a main code practice. + AssessmentSpecializationAvailability: + type: object + description: Assessment state of one questionnaire specialization. Specializations are assessed independently, with independent retry intervals. + additionalProperties: false + required: + - specialization + - confirmed_grade + - confirmed_basis + - active_attempt_id + - grades + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmed_grade: + description: Currently confirmed grade of the specialization, or null. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + confirmed_basis: + description: What the confirmed grade rests on, or null exactly when `confirmed_grade` is null. `synthetic_demo` marks a demonstration category, which is not a validated measurement and must not be shown as a real confirmation. + oneOf: + - $ref: '#/components/schemas/EvidenceBasis' + - type: 'null' + active_attempt_id: + type: + - string + - 'null' + format: uuid + description: Identifier of the active attempt of the specialization, or null. + grades: + type: array + maxItems: 10 + description: Every grade of the scale in ascending order. + items: + $ref: '#/components/schemas/AssessmentGradeAvailability' + AssessmentAvailability: + type: object + description: Assessment availability for the specializations of the current candidate's questionnaire, derived at the time of the request. + additionalProperties: false + required: + - specializations + properties: + specializations: + type: array + maxItems: 2 + description: Questionnaire specializations in questionnaire order. + items: + $ref: '#/components/schemas/AssessmentSpecializationAvailability' + NeedVersion: + type: integer + format: int64 + minimum: 1 + description: Version of an employer need. Creation makes version 1, and every committed change of the need advances it by exactly one, including a change made by the server, such as a planned asynchronous ML suggestion. Each version is an immutable snapshot of the need. `requirements_version` names the version whose confirmed requirements are current, so a change that leaves them unchanged creates a need version without a new requirements version. + examples: + - 2 + NeedTitle: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Short name of the need inside the organization, for example "Backend for the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + NeedSourceText: + type: string + minLength: 1 + maxLength: 10000 + description: 'Free description of the team''s tasks as the employer wrote or pasted it. The server extracts proposed requirements from it; the text itself is never a requirement. It may contain line breaks. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of candidates. The server stores it as written: it may contain requirements that discriminate by a protected characteristic, and the extractor never turns such a requirement into a need field. Exclusions, the requirements that a candidate must not meet, are planned as a separate additive field with the Labor Code article 64 check.' + NeedValueStatus: + type: string + description: |- + Confirmation state of one need field. + + - confirmed: a member of the organization entered the value or confirmed it. Only confirmed values feed readiness, category recommendations, search, and invitations. + - extracted: the server proposed the value from the need text or an import, and nobody has confirmed it yet. It is a suggestion: it never feeds search or recommendations and never counts as an answer in readiness. + - unknown: the field has no value. `value` and `source` are null. The server never fills an unknown field with a default or a guess, such as a Senior grade, the remote format, or a zero salary. + enum: + - confirmed + - extracted + - unknown + NeedItemStatus: + type: string + description: 'Confirmation state of a list item, and the decision that a request sends for a field or an item: `confirmed` or `extracted`, with the meaning of NeedValueStatus. A request sends `confirmed` to confirm a suggestion or to set a manual value, and `extracted` only to keep a stored suggestion unconfirmed with exactly its stored value. An item is never `unknown`; a list with no confirmed item is what readiness reports as missing.' + enum: + - confirmed + - extracted + NeedValueOrigin: + type: string + description: |- + Where the value of a field or item came from. The server sets it; a request never sends it. + + - manual: a member of the organization typed the value in the form. `quote`, `extraction_version`, and `extracted_in_version` are null. + - extracted_from_text: the server extracted the value from `source_text`, with the deterministic rules and dictionary or, planned, with the ML service. `extraction_version` names the extractor version. + - imported: planned; the value was copied from a linked vacancy or an import. No MVP operation produces it. + + Confirming an extracted value keeps its origin and quote; changing the value makes it `manual`. Adding a value is a contract change. + enum: + - manual + - extracted_from_text + - imported + NeedSourceQuote: + type: string + minLength: 1 + maxLength: 300 + description: Exact excerpt of the `source_text` that the value was extracted from, so a reviewer can check it. It may contain line breaks. Plain text; clients show it as text, never as HTML. + NeedVersionLabel: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Opaque identifier of a published extractor or algorithm version, for example `need-rules.2026-10.1`. Clients show it as text and never parse it. + NeedValueSource: + type: object + description: 'Provenance of a value: its origin, the quote it was extracted from, the need version whose text the quote belongs to, and the extractor version. Read-only; the server derives it and a request cannot set it.' + additionalProperties: false + required: + - origin + - quote + - extracted_in_version + - extraction_version + properties: + origin: + $ref: '#/components/schemas/NeedValueOrigin' + quote: + description: Excerpt of the need text that supports the value, or null for a manual value and for an extracted value that the extractor did not tie to one excerpt. + oneOf: + - $ref: '#/components/schemas/NeedSourceQuote' + - type: 'null' + extracted_in_version: + description: Need version whose `source_text` the value was extracted from and the quote is an excerpt of, or null for a manual value. A confirmed value keeps it after the text changes, so its quote may be absent from the current `source_text`. + oneOf: + - $ref: '#/components/schemas/NeedVersion' + - type: 'null' + extraction_version: + description: Extractor version for an extracted or imported value, or null for a manual value. + oneOf: + - $ref: '#/components/schemas/NeedVersionLabel' + - type: 'null' + SkillName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Name of a skill or technology as the employer gave it, for example Go, PostgreSQL, or Temporal. It has no leading or trailing whitespace and no line breaks. The server compares names without regard to letter case. Plain text; clients show it as text, never as HTML. + SkillTaxonomyCode: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9][a-z0-9_.+#-]*$ + description: Code of a skill in the platform skill taxonomy, for example `postgresql`. The server assigns it from the taxonomy; clients never send it and never derive it from the name. + NeedTaskText: + type: string + minLength: 1 + maxLength: 300 + pattern: ^\S(?:.*\S)?$ + description: One work task of the team, for example "Move the payout service to an event model". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + NeedDomainName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Business domain of the work, for example payments or logistics, as free text. Plain text without line breaks; clients show it as text, never as HTML. + NeedLocationName: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Place of work for the office or hybrid format, for example a city, as free text. It describes the employer's office, never a candidate's address. Plain text without line breaks; clients show it as text, never as HTML. + RubAmount: + type: integer + format: int64 + minimum: 1000 + maximum: 100000000 + multipleOf: 1000 + description: Amount of money in whole rubles. A salary bound is positive and a multiple of 1000, the step that PRD FR13 sets for the bounds of a salary range and for the bids of the sealed final. + examples: + - 120000 + CurrencyCode: + type: string + description: ISO 4217 currency code. The MVP accepts only RUB; adding a value is a contract change. + enum: + - RUB + SalaryPeriod: + type: string + description: Pay period of a salary amount. The MVP uses only `month`; adding a value is a contract change. + enum: + - month + SalaryTaxBasis: + type: string + description: 'Tax basis of a salary amount: `net`, the amount paid out after personal income tax, or `gross`, the amount before it. The basis is always explicit; amounts in different bases are never compared directly.' + enum: + - net + - gross + SalaryRange: + type: object + description: 'Salary range `[A; B]` in whole rubles with its base: the currency, the pay period, and the tax basis (PRD FR13). The schema requires every field, bounds that are positive multiples of 1000, and the known currency, period, and basis. The server checks the cross-field rules in integer arithmetic: `salary_from < salary_to`, and a width `(B - A) / ((A + B) / 2)` from 10% to 40% inclusive, that is `20 * (B - A) >= A + B` and `5 * (B - A) <= A + B`. A violation answers 400 validation_failed with the pointer of `salary_to` in the request, for example `/salary/value/salary_to`. For example, `[95000; 105000]` has a width of exactly 10% and `[80000; 120000]` exactly 40%; both are accepted. The rules are the same for a need and an invitation.' + additionalProperties: false + required: + - salary_from + - salary_to + - currency + - period + - tax_basis + properties: + salary_from: + $ref: '#/components/schemas/RubAmount' + salary_to: + $ref: '#/components/schemas/RubAmount' + currency: + $ref: '#/components/schemas/CurrencyCode' + period: + $ref: '#/components/schemas/SalaryPeriod' + tax_basis: + $ref: '#/components/schemas/SalaryTaxBasis' + NeedSpecialization: + type: object + description: Target specialization of the need with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/NeedValueStatus' + value: + oneOf: + - $ref: '#/components/schemas/SpecializationCode' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/NeedValueSource' + - type: 'null' + NeedGrade: + type: object + description: Target grade of the need with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; a text that names no grade leaves the grade unknown instead of assuming one. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/NeedValueStatus' + value: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/NeedValueSource' + - type: 'null' + NeedDomain: + type: object + description: Business domain of the need with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/NeedValueStatus' + value: + oneOf: + - $ref: '#/components/schemas/NeedDomainName' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/NeedValueSource' + - type: 'null' + NeedWorkFormats: + type: object + description: Work formats that the employer offers, with their confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`; a known value lists one to three formats. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/NeedValueStatus' + value: + type: + - array + - 'null' + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + source: + oneOf: + - $ref: '#/components/schemas/NeedValueSource' + - type: 'null' + NeedLocation: + type: object + description: Place of work with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. Readiness requires a confirmed place only when the confirmed work formats include `office` or `hybrid`. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/NeedValueStatus' + value: + oneOf: + - $ref: '#/components/schemas/NeedLocationName' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/NeedValueSource' + - type: 'null' + NeedSalary: + type: object + description: Salary range that the employer offers, with its confirmation state and provenance. `value` and `source` are null exactly when `status` is `unknown`. A text without a salary leaves it unknown; the server never substitutes zero, a market estimate, or a range from another need. + additionalProperties: false + required: + - status + - value + - source + properties: + status: + $ref: '#/components/schemas/NeedValueStatus' + value: + oneOf: + - $ref: '#/components/schemas/SalaryRange' + - type: 'null' + source: + oneOf: + - $ref: '#/components/schemas/NeedValueSource' + - type: 'null' + NeedSkill: + type: object + description: 'One required or desired skill of the need. `taxonomy_code` is null for a skill that the platform taxonomy does not know: the server keeps the name as given, never maps it to a guessed code, and counts it as not covered in category recommendations.' + additionalProperties: false + required: + - name + - taxonomy_code + - status + - source + properties: + name: + $ref: '#/components/schemas/SkillName' + taxonomy_code: + oneOf: + - $ref: '#/components/schemas/SkillTaxonomyCode' + - type: 'null' + status: + $ref: '#/components/schemas/NeedItemStatus' + source: + $ref: '#/components/schemas/NeedValueSource' + NeedTask: + type: object + description: One work task of the team with its confirmation state and provenance. + additionalProperties: false + required: + - text + - status + - source + properties: + text: + $ref: '#/components/schemas/NeedTaskText' + status: + $ref: '#/components/schemas/NeedItemStatus' + source: + $ref: '#/components/schemas/NeedValueSource' + NeedSpecializationInput: + type: object + description: Decision about the specialization in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/SpecializationCode' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedGradeInput: + type: object + description: Decision about the grade in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/GradeCode' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedDomainInput: + type: object + description: Decision about the domain in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/NeedDomainName' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedWorkFormatsInput: + type: object + description: Decision about the work formats in a request; see NeedUpdate for the rules of `status`. Formats are compared as a set. + additionalProperties: false + required: + - value + - status + properties: + value: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedLocationInput: + type: object + description: Decision about the place of work in a request; see NeedUpdate for the rules of `status`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/NeedLocationName' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedSalaryInput: + type: object + description: Decision about the salary range in a request; see NeedUpdate for the rules of `status` and SalaryRange for the rules of the range, whose pointers are under `/salary/value`. + additionalProperties: false + required: + - value + - status + properties: + value: + $ref: '#/components/schemas/SalaryRange' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedSkillInput: + type: object + description: 'One skill of a list in a request. A name that equals, without regard to letter case, a skill of the current version in either skill list refers to that skill and keeps its origin, quote, and taxonomy code; this is how an extracted skill is confirmed or moved between the required and desired lists. Any other name is a new manual skill. `status` follows the rules of NeedUpdate: `extracted` for a name that is not a stored suggestion answers 400 validation_failed with the pointer of that `status`, for example `/required_skills/2/status`. A name repeated within or across the two skill lists answers 400 with the pointer of the later `name`.' + additionalProperties: false + required: + - name + - status + properties: + name: + $ref: '#/components/schemas/SkillName' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedTaskInput: + type: object + description: One task of the list in a request. A text equal to a task of the current version refers to that task and keeps its origin and quote; any other text is a new manual task. `status` and repeated texts follow the rules of NeedSkillInput. + additionalProperties: false + required: + - text + - status + properties: + text: + $ref: '#/components/schemas/NeedTaskText' + status: + $ref: '#/components/schemas/NeedItemStatus' + NeedRequirementSet: + type: object + description: Requirements of one need version, each with its confirmation state and provenance. Read-only; requests change them through the fields of NeedCreate and NeedUpdate. + additionalProperties: false + required: + - specialization + - grade + - required_skills + - desired_skills + - tasks + - domain + - work_formats + - location + - salary + properties: + specialization: + $ref: '#/components/schemas/NeedSpecialization' + grade: + $ref: '#/components/schemas/NeedGrade' + required_skills: + type: array + maxItems: 30 + description: Required skills; each has weight 2 in skill coverage. Only confirmed skills count. + items: + $ref: '#/components/schemas/NeedSkill' + desired_skills: + type: array + maxItems: 30 + description: Desired skills; each has weight 1 in skill coverage. Only confirmed skills count. + items: + $ref: '#/components/schemas/NeedSkill' + tasks: + type: array + maxItems: 20 + description: Work tasks of the team in the order given. + items: + $ref: '#/components/schemas/NeedTask' + domain: + $ref: '#/components/schemas/NeedDomain' + work_formats: + $ref: '#/components/schemas/NeedWorkFormats' + location: + $ref: '#/components/schemas/NeedLocation' + salary: + $ref: '#/components/schemas/NeedSalary' + NeedFieldName: + type: string + description: Name of a need field, equal to its property name in NeedRequirementSet and in the request bodies. Adding a value is a contract change. + enum: + - specialization + - grade + - required_skills + - desired_skills + - tasks + - domain + - work_formats + - location + - salary + NeedMissingReason: + type: string + description: 'Why a critical field is missing: `unknown`, the field has no value, or `unconfirmed`, it has only an extracted value or, for required skills, only extracted items that wait for confirmation.' + enum: + - unknown + - unconfirmed + NeedMissingField: + type: object + description: One critical field that has no confirmed value, with a specific question that the client shows next to the field. + additionalProperties: false + required: + - field + - reason + - question + properties: + field: + $ref: '#/components/schemas/NeedFieldName' + reason: + $ref: '#/components/schemas/NeedMissingReason' + question: + type: string + minLength: 1 + maxLength: 300 + description: Specific Russian question about the missing value, for example which grade is needed. Plain text; the client shows it as text, never as HTML. + NeedReadinessStatus: + type: string + description: '`complete` when every critical field has a confirmed value, otherwise `incomplete`.' + enum: + - complete + - incomplete + NeedReadinessReport: + type: object + description: Completeness of the critical fields, computed by the server for the current version. The critical fields are `specialization`, `grade`, `required_skills` (at least one confirmed skill), `work_formats`, `salary`, and `location` when the confirmed work formats include `office` or `hybrid`. An incomplete need is still a valid saved need; each later operation, such as search or an invitation, states which readiness it requires. + additionalProperties: false + required: + - status + - missing_fields + properties: + status: + $ref: '#/components/schemas/NeedReadinessStatus' + missing_fields: + type: array + maxItems: 9 + description: Critical fields without a confirmed value, each at most once, in the order of NeedFieldName. Empty exactly when `status` is `complete`. + items: + $ref: '#/components/schemas/NeedMissingField' + NeedRecommendationStatus: + type: string + description: |- + State of the category recommendations of the current requirements version. + + - computed: `categories` holds the recommendations computed from the confirmed requirements of `requirements_version`. + - pending: the computation for the current requirements version has not finished yet; `categories` is empty. Read the need again later. + - not_available: the current requirements have no confirmed required or desired skill to compute from; `categories` is empty. + enum: + - computed + - pending + - not_available + NeedSkillOverlap: + type: object + description: 'Skill coverage of a category: the weighted share of the confirmed skills of the need that the category taxonomy covers, with weight 2 for a required and 1 for a desired skill.' + additionalProperties: false + required: + - share + - covered_skills + - uncovered_skills + properties: + share: + type: number + format: double + minimum: 0 + maximum: 1 + description: Weighted share from 0 to 1, rounded to two decimals. + covered_skills: + type: array + maxItems: 60 + description: Confirmed skills of the need that the category covers. + items: + $ref: '#/components/schemas/SkillName' + uncovered_skills: + type: array + maxItems: 60 + description: Confirmed skills of the need that the category does not cover, including skills without a taxonomy code. + items: + $ref: '#/components/schemas/SkillName' + NeedMoneyStatus: + type: string + description: |- + How the salary component of a recommendation was obtained. + + - computed: at least five available candidates of the category have a known minimum comparable with the confirmed range; `share` is given. + - insufficient_data: fewer than five such candidates; the policy uses the neutral value 0.5 and `share` is null. + - no_salary: the need has no confirmed salary range; the policy uses the neutral value 0.5 and `share` is null. + - withheld: the organization changed salary ranges five times within seven days, so salary aggregates are withheld for seven days (PRD FR13, enforcement planned); the policy uses the neutral value 0.5 and `share` is null. + + An unknown candidate minimum never counts as zero. + enum: + - computed + - insufficient_data + - no_salary + - withheld + NeedMoneyFit: + type: object + description: Salary component of a recommendation. It is an aggregate over at least five candidates and never reveals a minimum of any candidate. + additionalProperties: false + required: + - status + - share + properties: + status: + $ref: '#/components/schemas/NeedMoneyStatus' + share: + type: + - number + - 'null' + format: double + minimum: 0 + maximum: 1 + description: 'Share of those candidates whose minimum is not above the upper bound of the range, rounded down to a multiple of 0.25 (one of 0, 0.25, 0.5, 0.75, 1), or null unless `status` is `computed`. The score and the ranking use this rounded value, never the exact share. A quarter step gives five levels: each probe of a new upper bound tells at most which quarter of the group accepts it, and in the smallest allowed group of five candidates a single minimum often does not move the value, while the share still separates a range that most candidates accept from one that few accept.' + NeedSupplyBand: + type: string + description: 'Number of available candidates of the category in the allowed detail: `fewer_than_5`, `from_5_to_29`, or `30_or_more`. Smaller groups are never counted exactly.' + enum: + - fewer_than_5 + - from_5_to_29 + - 30_or_more + NeedCategoryRecommendation: + type: object + description: 'One recommended category, a specialization with a grade, with its score and the reasons for it. The score is `0.5 * Overlap + 0.3 * Money + 0.2 * Supply` (PRD FR08) computed from the published components: the exact skill overlap, the money share rounded down to a quarter or the neutral 0.5, and `Supply = min(1, active / 30)` when at least five candidates are available. For a group of fewer than five, Supply enters the ranking as 0, the same for every such group, so neither the score nor the order reveals the exact size of a group below five.' + additionalProperties: false + required: + - specialization + - grade + - score + - skill_overlap + - money + - supply + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + score: + type: + - number + - 'null' + format: double + minimum: 0 + maximum: 1 + description: Recommendation score from 0 to 1, rounded half up to two decimals, or null when `supply` is `fewer_than_5`. Read-only; no request can set it. + skill_overlap: + $ref: '#/components/schemas/NeedSkillOverlap' + money: + $ref: '#/components/schemas/NeedMoneyFit' + supply: + $ref: '#/components/schemas/NeedSupplyBand' + NeedCategoryRecommendations: + type: object + description: 'Category recommendations computed by the server from the confirmed requirements of `requirements_version` with a versioned policy (PRD FR08). Read-only: no request can set a recommendation, a score, or one of its components. The server may recompute them for the same requirements version, for example for a new policy or a changed pool of available candidates, without a new need version; `computed_at` and `policy_version` then change. The policy version and the candidate group used are stored with each computation, so a later policy never rewrites it.' + additionalProperties: false + required: + - status + - requirements_version + - policy_version + - algorithm_version + - computed_at + - categories + properties: + status: + $ref: '#/components/schemas/NeedRecommendationStatus' + requirements_version: + $ref: '#/components/schemas/NeedVersion' + policy_version: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: Number of the policy version whose weights were applied, or null unless `status` is `computed`. + algorithm_version: + description: Version of the recommendation algorithm, or null unless `status` is `computed`. + oneOf: + - $ref: '#/components/schemas/NeedVersionLabel' + - type: 'null' + computed_at: + description: Time of the computation, or null unless `status` is `computed`. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + categories: + type: array + maxItems: 10 + description: Recommended categories, best first by the score described in NeedCategoryRecommendation. Empty unless `status` is `computed`. + items: + $ref: '#/components/schemas/NeedCategoryRecommendation' + Need: + type: object + description: 'Hiring need of an organization: what the team needs, independent of any published vacancy. It holds the current version of the requirements with their provenance, the readiness of the critical fields, and the category recommendations. It never contains membership data, a candidate''s personal data, or a candidate''s salary minimum.' + additionalProperties: false + required: + - id + - organization_id + - vacancy_id + - title + - source_text + - version + - requirements_version + - requirements + - readiness + - recommendations + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the need. + organization_id: + type: string + format: uuid + description: Organization that owns the need, equal to `org_id` of the path. It never changes. + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Linked vacancy of the same organization, or null. A need never requires a vacancy. + title: + $ref: '#/components/schemas/NeedTitle' + source_text: + description: Text the requirements were extracted from, or null. + oneOf: + - $ref: '#/components/schemas/NeedSourceText' + - type: 'null' + version: + $ref: '#/components/schemas/NeedVersion' + requirements_version: + description: Need version in which the current confirmed requirements were last changed, at most `version`. A change that confirms, changes, or removes a requirement makes it equal to the new `version`. A change of the title, the vacancy link, or the text, or of suggestions only, creates a new `version` but keeps `requirements_version`, so it invalidates neither the recommendations nor search results and selection snapshots. Search runs and selection snapshots (PRD FR10) refer to `(need id, requirements_version)`, and a new selection snapshot is due only when it changes. + allOf: + - $ref: '#/components/schemas/NeedVersion' + requirements: + $ref: '#/components/schemas/NeedRequirementSet' + readiness: + $ref: '#/components/schemas/NeedReadinessReport' + recommendations: + $ref: '#/components/schemas/NeedCategoryRecommendations' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + NeedSummary: + type: object + description: 'Need in a list: its identity, current version, target category fields, and readiness. Read the need for the requirements and the recommendations.' + additionalProperties: false + required: + - id + - vacancy_id + - title + - version + - specialization + - grade + - readiness + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the need. + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Linked vacancy, or null. + title: + $ref: '#/components/schemas/NeedTitle' + version: + $ref: '#/components/schemas/NeedVersion' + specialization: + $ref: '#/components/schemas/NeedSpecialization' + grade: + $ref: '#/components/schemas/NeedGrade' + readiness: + $ref: '#/components/schemas/NeedReadinessReport' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + NeedList: + type: object + description: One page of the needs of an organization, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Needs of the page. + items: + $ref: '#/components/schemas/NeedSummary' + page: + $ref: '#/components/schemas/PageInfo' + NeedCreate: + type: object + description: New need. Only `title` is required, so a need can start from a title, from a text, or from form fields, and with or without a vacancy. A field or list item given here must have `status` `confirmed` and becomes a confirmed manual value; `extracted` answers 400 with the pointer of that `status`, such as `/grade/status`, because a new need has no stored suggestion. A field that is absent is extracted from `source_text` when the text is given and is left unknown or empty otherwise. A nullable field sent as null, and a skill or task list sent as an empty list, stays unknown or empty and is not extracted; an empty `work_formats` value fails `minItems`. Unknown fields are rejected, so a request cannot set membership, a role, a status of the need, a provenance, readiness, a recommendation or its score, or a candidate's salary minimum. + additionalProperties: false + required: + - title + properties: + title: + $ref: '#/components/schemas/NeedTitle' + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Vacancy of the same organization to link, or null or absent for a need without a vacancy. + source_text: + oneOf: + - $ref: '#/components/schemas/NeedSourceText' + - type: 'null' + specialization: + oneOf: + - $ref: '#/components/schemas/NeedSpecializationInput' + - type: 'null' + grade: + oneOf: + - $ref: '#/components/schemas/NeedGradeInput' + - type: 'null' + required_skills: + type: array + maxItems: 30 + items: + $ref: '#/components/schemas/NeedSkillInput' + desired_skills: + type: array + maxItems: 30 + items: + $ref: '#/components/schemas/NeedSkillInput' + tasks: + type: array + maxItems: 20 + items: + $ref: '#/components/schemas/NeedTaskInput' + domain: + oneOf: + - $ref: '#/components/schemas/NeedDomainInput' + - type: 'null' + work_formats: + oneOf: + - $ref: '#/components/schemas/NeedWorkFormatsInput' + - type: 'null' + location: + oneOf: + - $ref: '#/components/schemas/NeedLocationInput' + - type: 'null' + salary: + oneOf: + - $ref: '#/components/schemas/NeedSalaryInput' + - type: 'null' + NeedUpdate: + type: object + description: 'Change of a need over the version the client read. Each field present in the body replaces that field as a whole; an absent field stays unchanged. Nested objects and lists are not merged: a field decision and each list are replaced entirely, and a stored item missing from a sent list is deleted. A nullable field sent as null becomes unknown, or unlinked for `vacancy_id`; a skill or task list sent empty deletes every item; a list sent as null fails validation. A field decision `{value, status}` and a list item follow the same rules: `confirmed` with the stored value confirms it and keeps its origin and quote, and `confirmed` with another value sets a confirmed manual value; `extracted` keeps a stored suggestion unconfirmed and is allowed only with exactly the stored suggested value, otherwise it answers 400 with the pointer of that `status`, such as `/grade/status` or `/required_skills/0/status`. A client that sends back an unchanged form therefore confirms nothing by accident: it sends each suggestion with `extracted`, or leaves the field out. Sending a different `source_text` extracts again: new suggestions replace only the `extracted` values and items of fields not named in this body; confirmed values are never overwritten, a suggested skill whose name is already in either skill list is skipped, and a suggestion that a member deleted is not proposed again for this need. Unknown fields are rejected, so a request cannot set membership, a role, a provenance, readiness, a recommendation or its score, or a candidate''s salary minimum.' + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/NeedVersion' + title: + $ref: '#/components/schemas/NeedTitle' + vacancy_id: + type: + - string + - 'null' + format: uuid + description: Vacancy of the same organization to link, or null to unlink. + source_text: + oneOf: + - $ref: '#/components/schemas/NeedSourceText' + - type: 'null' + specialization: + oneOf: + - $ref: '#/components/schemas/NeedSpecializationInput' + - type: 'null' + grade: + oneOf: + - $ref: '#/components/schemas/NeedGradeInput' + - type: 'null' + required_skills: + type: array + maxItems: 30 + items: + $ref: '#/components/schemas/NeedSkillInput' + desired_skills: + type: array + maxItems: 30 + items: + $ref: '#/components/schemas/NeedSkillInput' + tasks: + type: array + maxItems: 20 + items: + $ref: '#/components/schemas/NeedTaskInput' + domain: + oneOf: + - $ref: '#/components/schemas/NeedDomainInput' + - type: 'null' + work_formats: + oneOf: + - $ref: '#/components/schemas/NeedWorkFormatsInput' + - type: 'null' + location: + oneOf: + - $ref: '#/components/schemas/NeedLocationInput' + - type: 'null' + salary: + oneOf: + - $ref: '#/components/schemas/NeedSalaryInput' + - type: 'null' + SupportCaseNumber: + type: string + minLength: 14 + maxLength: 18 + pattern: ^SC-[0-9]{4}-[0-9]{6,10}$ + description: 'Human-readable case number that the server assigns on creation, for example `SC-2026-000123`: the prefix `SC`, the UTC year of creation, and a sequence number of at least six digits with leading zeros. The sequence is global and never reused, so the number is unique across every case and year and never changes. The user quotes it in letters and calls; the API addresses a case only by its `id`. Clients show the number as text and never parse it.' + examples: + - SC-2026-000123 + SupportCaseType: + type: string + description: |- + Kind of the case. It fixes the allowed object reference, the type-specific fields, the response target, and the queue that handles the case. + + - support: a question or a problem, for example an assessment that is not available or a failed sandbox run. Candidate and employer accounts. + - complaint: a complaint about an organization or an offer, including a breach of the salary terms or a disclosure of personal data (PRD FR18). Candidate accounts. + - grade_appeal: an appeal of a category the caller received: the result of one own assessment attempt, or the outcome of one own resolved manual assessment case. An expert reviews it, and the original result stays in the history. Candidate accounts. + - anticheat_appeal: an appeal of an anti-cheat review decision on one own assessment attempt. Candidate accounts. + - manual_assessment: a request for a manual assessment of a category by a subject expert with the same rubric, the alternative to automated categorization (consent C3). Candidate accounts. + enum: + - support + - complaint + - grade_appeal + - anticheat_appeal + - manual_assessment + SupportCaseStatus: + type: string + description: |- + Processing status of a case. Only the server changes it; no request field sets it. Adding a value is a contract change: generated clients reject an unknown value. + + - submitted: the case was accepted and waits in its queue. + - in_review: support or a moderator works on it. + - waiting_for_user: support asked the author for more detail. Not set yet: it starts with the planned operation that lets the author reply, and until then no case has this status. + - waiting_expert: a grade appeal, an anti-cheat appeal, or a manual assessment waits for a subject expert. The server sets it in the same transaction as the creation of such a case. The case stays here until a person decides; it is never resolved by the passing of time. + - resolved: terminal; a decision was made and `decision` holds its outcome and public reason. + - closed: terminal; the case ended without a decision on the merits, for example as a duplicate of another case. The last history event says why. + enum: + - submitted + - in_review + - waiting_for_user + - waiting_expert + - resolved + - closed + SupportCaseObjectType: + type: string + description: |- + Kind of object that a case refers to. Each case type accepts only some of them. Adding a value is a contract change: generated clients reject an unknown value. Planned values: `vacancy` and `application` with the vacancies and protected applications of PRD FR16, and a profile finding with profile analysis. + + - assessment_attempt: an assessment attempt of the caller. + - organization: an organization that the caller can see. + - invitation: an invitation addressed to the caller. Invitations are in the contract but not implemented yet; until they are, every invitation reference answers 404 not_found. + - support_case: another case of the caller, for example the resolved manual assessment that a grade appeal disputes. + enum: + - assessment_attempt + - organization + - invitation + - support_case + SupportCaseObjectReference: + type: object + description: Typed reference to an object that the case is about. The server checks on creation that the caller may see the object; an unknown object and an object of someone else both answer 404 not_found, so a reference never reveals whether another person's object exists. The case keeps only the type and the identifier, never a copy of the object. + additionalProperties: false + required: + - type + - id + properties: + type: + $ref: '#/components/schemas/SupportCaseObjectType' + id: + type: string + format: uuid + description: Identifier of the object. + SupportCaseAttemptReference: + type: object + description: Reference to an assessment attempt of the caller. Any other object type fails validation. + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + id: + type: string + format: uuid + description: Identifier of an assessment attempt of the caller. + SupportCaseGradeAppealReference: + type: object + description: 'Reference to the category that a grade appeal disputes: an assessment attempt of the caller in a terminal state, or a `manual_assessment` case of the caller that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - assessment_attempt + - support_case + id: + type: string + format: uuid + description: Identifier of the attempt or the case. + SupportCaseComplaintReference: + type: object + description: 'Reference to the object of a complaint: an organization that the caller can see or an invitation addressed to the caller. Any other object type fails validation.' + additionalProperties: false + required: + - type + - id + properties: + type: + type: string + enum: + - organization + - invitation + id: + type: string + format: uuid + description: Identifier of the organization or the invitation. + SupportCaseAssessmentTarget: + type: object + description: 'Category that the case is about: a specialization and a grade of the MVP scale. For a manual assessment it is the category to assess; for a support case it is optional context, for example the category whose test is not available.' + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + SupportCaseComplaintReason: + type: string + description: |- + Ground of a complaint (PRD FR18). + + - organization_conduct: conduct of the organization, for example fraudulent or abusive messages. + - offer_content: misleading or discriminatory content of an offer. Requires an invitation reference. + - salary_terms_violation: a breach of the salary terms of an offer. Requires an invitation reference. + - data_disclosure: a disclosure of the caller's personal data beyond what the caller granted. + - other: another ground, explained in the description. + enum: + - organization_conduct + - offer_content + - salary_terms_violation + - data_disclosure + - other + SupportCaseDescription: + type: string + minLength: 1 + maxLength: 4000 + pattern: \S + description: 'What the user asks or reports, as the user wrote it. It must contain at least one character that is not whitespace, so an empty or blank text fails validation with the pointer `/description`; it may contain line breaks. The pattern `\S` uses the ECMAScript white space set in both generated validators: ogen converts it to that set for Go, so a text made only of spaces such as U+00A0, U+2003, or U+3000 fails in the server schema and in Zod alike. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes; the server therefore also rejects a text whose every character is `unicode.IsSpace` or U+FEFF, with the same 400 and the pointer `/description`, while generated Zod accepts a text of NEL. Plain text; clients show it as text, never as HTML. The server stores it as written, shows it only to the author and to the staff of the queue, and never writes it to logs or notifications. Users should not put passwords or other people''s contact data into it. Generated Zod validators count UTF-16 code units, so the server stays authoritative for the length.' + examples: + - Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + SupportCasePublicText: + type: string + minLength: 1 + maxLength: 4000 + description: 'Text that support or a moderator wrote for the user: a public reply or the public reason of a decision. Plain text; clients show it as text, never as HTML. Internal notes of the staff are never public texts.' + SupportCaseCreateSupport: + type: object + description: New support case. Both the object reference and the assessment target are optional context; omit what does not apply. + additionalProperties: false + required: + - type + - description + properties: + type: + type: string + enum: + - support + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + $ref: '#/components/schemas/SupportCaseObjectReference' + assessment_target: + $ref: '#/components/schemas/SupportCaseAssessmentTarget' + SupportCaseCreateComplaint: + type: object + description: New complaint about an organization or an offer. + additionalProperties: false + required: + - type + - description + - complaint_reason + - object + properties: + type: + type: string + enum: + - complaint + description: + $ref: '#/components/schemas/SupportCaseDescription' + complaint_reason: + $ref: '#/components/schemas/SupportCaseComplaintReason' + object: + $ref: '#/components/schemas/SupportCaseComplaintReference' + SupportCaseCreateGradeAppeal: + type: object + description: 'New appeal of a category the caller received: the result of an own assessment attempt, or the outcome of an own resolved manual assessment.' + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - grade_appeal + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + $ref: '#/components/schemas/SupportCaseGradeAppealReference' + SupportCaseCreateAnticheatAppeal: + type: object + description: New appeal of an anti-cheat review decision on an own assessment attempt. + additionalProperties: false + required: + - type + - description + - object + properties: + type: + type: string + enum: + - anticheat_appeal + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + $ref: '#/components/schemas/SupportCaseAttemptReference' + SupportCaseCreateManualAssessment: + type: object + description: 'New request for a manual assessment of a category by a subject expert. A prior attempt of the same category is optional context: a failed first test or no attempt at all never blocks the request.' + additionalProperties: false + required: + - type + - description + - assessment_target + properties: + type: + type: string + enum: + - manual_assessment + description: + $ref: '#/components/schemas/SupportCaseDescription' + assessment_target: + $ref: '#/components/schemas/SupportCaseAssessmentTarget' + object: + $ref: '#/components/schemas/SupportCaseAttemptReference' + SupportCaseCreate: + description: 'New case, selected by `type`. Each type fixes its required fields and the object types it accepts. The body carries only what the user states: the request has no status, decision, outcome, priority, response target, assignee, moderator, rubric, or contact field, and every variant rejects unknown fields, so a client cannot set any of them. The user and the account come only from the session.' + oneOf: + - $ref: '#/components/schemas/SupportCaseCreateSupport' + - $ref: '#/components/schemas/SupportCaseCreateComplaint' + - $ref: '#/components/schemas/SupportCaseCreateGradeAppeal' + - $ref: '#/components/schemas/SupportCaseCreateAnticheatAppeal' + - $ref: '#/components/schemas/SupportCaseCreateManualAssessment' + SupportResponseTarget: + type: object + description: 'Operational target for the answer to the case (PRD FR18: a case gets a number, a status, and a response deadline). The server fixes it on creation from the product policy version and the configured business calendar; it is a goal of the team, not a deadline set by law. The target is met by the first public reply, a decision, or a closure for `support` and `complaint`, and only by a decision or a closure for the appeals and `manual_assessment`. Missing the target never closes the case, never decides it, and never changes a grade.' + additionalProperties: false + required: + - kind + - business_days + - due_at + - answered_at + - late + - policy_version + properties: + kind: + type: string + enum: + - operational_goal + description: Nature of the target. `operational_goal` is a goal of the team that clients label as such, never as a legal deadline. + business_days: + type: integer + format: int32 + minimum: 1 + maximum: 60 + description: Length of the target in business days of the policy version, for example 5 for a manual assessment and 10 for an appeal. + due_at: + $ref: '#/components/schemas/Timestamp' + answered_at: + description: Time the target was met, or null while it is not. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + late: + type: boolean + description: 'Whether the target was missed: it was met after `due_at`, or it is not met and `due_at` has passed at the time of the response.' + policy_version: + type: integer + format: int32 + minimum: 1 + description: Number of the `product` policy version that fixed the target. + SupportCaseDecisionOutcome: + type: string + description: |- + Outcome of a decision as the user sees it. The allowed outcomes depend on the case type. + + - upheld: the appeal or the complaint is upheld in full. + - partially_upheld: the appeal or the complaint is upheld in part. + - not_upheld: the appeal or the complaint is not upheld. + - answered: a support case was answered. + - assessed: the expert finished a manual assessment. The resulting category is part of the assessment results, not of the case. + enum: + - upheld + - partially_upheld + - not_upheld + - answered + - assessed + SupportCaseDecision: + type: object + description: 'Decision visible to the user. It exists only once the case is `resolved`. It holds the outcome and the public reason; it never names the moderator or the expert and never contains internal notes, evidence, sanctions against another party, or risk signals. An upheld grade appeal never rewrites the original result: the corrected result is a separate decision of the assessment, and both stay in the history of that attempt.' + additionalProperties: false + required: + - outcome + - reason + - decided_at + properties: + outcome: + $ref: '#/components/schemas/SupportCaseDecisionOutcome' + reason: + $ref: '#/components/schemas/SupportCasePublicText' + decided_at: + $ref: '#/components/schemas/Timestamp' + SupportCaseActorKind: + type: string + description: |- + Who caused an event, by kind only. A case never names or identifies a moderator, an expert, or a support agent; assessment experts and appeal moderators are `support` too. Adding a value is a contract change. + + - user: the author of the case. + - support: a person of the support, moderation, or expert staff. + - system: the server, for example on creation or when it routes the case. + enum: + - user + - support + - system + SupportCaseEventKind: + type: string + description: |- + Kind of a public history event. Adding a value is a contract change. A reply of the author, planned with `waiting_for_user`, is a `reply` with the actor `user`, and a later revision of a decision is another `decision` event, so neither needs a new value. + + - created: the case was created; `status` is `submitted`. For an appeal or a manual assessment, a `status_changed` event of the actor `system` to `waiting_expert` follows in the same transaction. + - status_changed: the status changed; `status` is the new status, and `message` may explain a closure. + - reply: support replied; `message` holds the reply and `status` is null. + - decision: a decision was made; `status` is `resolved` and `message` holds the public reason. + enum: + - created + - status_changed + - reply + - decision + SupportCaseEvent: + type: object + description: One public event of the case history. Internal notes, assignments, evidence requests, and risk signals are never history events. + additionalProperties: false + required: + - sequence + - kind + - actor + - occurred_at + - status + - message + properties: + sequence: + type: integer + format: int32 + minimum: 1 + description: Position of the event in the history, starting at 1 and increasing by one. + kind: + $ref: '#/components/schemas/SupportCaseEventKind' + actor: + $ref: '#/components/schemas/SupportCaseActorKind' + occurred_at: + $ref: '#/components/schemas/Timestamp' + status: + description: Status of the case after the event, or null for a reply. + oneOf: + - $ref: '#/components/schemas/SupportCaseStatus' + - type: 'null' + message: + description: Public text of the event, or null. + oneOf: + - $ref: '#/components/schemas/SupportCasePublicText' + - type: 'null' + SupportCase: + type: object + description: Case of the current account. It contains what the author sent, the public processing state, and the public history. It never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers or anti-cheat signals, risk signals, or contact data of another person. Fields that do not apply to the type are null. + additionalProperties: false + required: + - id + - number + - type + - status + - description + - object + - assessment_target + - complaint_reason + - rubric_version + - response_target + - decision + - history + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/components/schemas/SupportCaseNumber' + type: + $ref: '#/components/schemas/SupportCaseType' + status: + $ref: '#/components/schemas/SupportCaseStatus' + description: + $ref: '#/components/schemas/SupportCaseDescription' + object: + description: Object that the case is about, as sent on creation, or null when the case has none. + oneOf: + - $ref: '#/components/schemas/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of a manual assessment, the optional category of a support case, or null. + oneOf: + - $ref: '#/components/schemas/SupportCaseAssessmentTarget' + - type: 'null' + complaint_reason: + description: Ground of a complaint, or null for other types. + oneOf: + - $ref: '#/components/schemas/SupportCaseComplaintReason' + - type: 'null' + rubric_version: + type: + - integer + - 'null' + format: int32 + minimum: 1 + description: For a manual assessment, the version of the grading policy pinned by the server at creation. The exact reviewed category opening and rubric manifest are retained privately so the expert can use the same rubric as automated assessment. Null for other types and for a manual assessment without one unique current reviewed category; the case still waits in `waiting_expert`. + response_target: + $ref: '#/components/schemas/SupportResponseTarget' + decision: + description: Decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/components/schemas/SupportCaseDecision' + - type: 'null' + history: + type: array + minItems: 1 + maxItems: 200 + description: 'Every public event in the order it happened, starting with `created`; the list is never truncated. The server keeps a case within 200 events: it rejects a staff reply or status change that would leave no room for the terminal event, so a case always fits and can always be resolved or closed. Further correspondence goes into a new case that references this one as `support_case`.' + items: + $ref: '#/components/schemas/SupportCaseEvent' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + SupportCaseSummary: + type: object + description: 'Case in a list: the fields that a list of cases shows, without the description and the history. GetMySupportCase returns the full case.' + additionalProperties: false + required: + - id + - number + - type + - status + - object + - assessment_target + - response_target + - decision_outcome + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Case identifier. + number: + $ref: '#/components/schemas/SupportCaseNumber' + type: + $ref: '#/components/schemas/SupportCaseType' + status: + $ref: '#/components/schemas/SupportCaseStatus' + object: + description: Object that the case is about, or null. + oneOf: + - $ref: '#/components/schemas/SupportCaseObjectReference' + - type: 'null' + assessment_target: + description: Category of the case, or null. + oneOf: + - $ref: '#/components/schemas/SupportCaseAssessmentTarget' + - type: 'null' + response_target: + $ref: '#/components/schemas/SupportResponseTarget' + decision_outcome: + description: Outcome of the decision once the case is `resolved`, otherwise null. + oneOf: + - $ref: '#/components/schemas/SupportCaseDecisionOutcome' + - type: 'null' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + SupportCaseList: + type: object + description: One page of the cases of the current account, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Case summaries of the page. + items: + $ref: '#/components/schemas/SupportCaseSummary' + page: + $ref: '#/components/schemas/PageInfo' + InvitationVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of an invitation. Creation makes version 1, and every committed change advances it by exactly one: a change of the draft, a send, the first view, an answer, a salary raise, a withdrawal, a cancellation, and an expiry made by the server. Every command carries the version the client read as `expected_version`; a stale value answers 412 version_conflict and changes nothing.' + examples: + - 3 + InvitationTermsVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of the terms of an invitation. The terms of a version are an immutable snapshot: every committed change of the terms, in the draft or by the one raise of the upper salary bound after sending, creates the next terms version, and a change of anything else keeps it. An acceptance names the terms version it accepts, and the consent C4 and the contact grant record it.' + examples: + - 2 + InvitationState: + type: string + description: |- + State of an invitation (PRD FR12). The internal sending step is never visible: a successful send already answers with `delivered`. + + - draft: the organization prepares the terms. The candidate does not see the invitation. + - delivered: the invitation is in the candidate's inbox and the response deadline runs. + - viewed: the candidate opened the terms; ViewMyInvitation records it. The deadline is unchanged. + - counter: planned; the candidate sent the one counter offer. No MVP operation produces it. + - accepted: the candidate accepted the current terms version and gave the consent C4; the contact grant exists. + - interview_scheduled, interviewed, negotiation, terms_agreed, no_deal: planned stages after an acceptance (interview and the sealed final of FR13). No MVP operation produces them. + - declined: terminal; the candidate declined with a structured reason. No access arises. + - expired: terminal; a server deadline passed, see `expiry_reason`. No access arises. + - withdrawn: terminal; the organization withdrew the invitation. A grant that already exists is not revoked by it. + - cancelled_by_candidate: terminal; the candidate cancelled the participation. The grant of this invitation is revoked. + + Planned states are listed now so that generated clients accept them when their operations arrive. Adding another value is a contract change. + enum: + - draft + - delivered + - viewed + - counter + - accepted + - interview_scheduled + - interviewed + - negotiation + - terms_agreed + - no_deal + - declined + - expired + - withdrawn + - cancelled_by_candidate + InvitationExpiryReason: + type: string + description: |- + Why an invitation expired. Set exactly when the state is `expired`, null otherwise. + + - invitation_timeout: the candidate did not answer by `response_deadline_at`. No grant is created. + - negotiation_timeout: planned; the sealed final of FR13 closed without both bids. No MVP operation produces it. + enum: + - invitation_timeout + - negotiation_timeout + InvitationResponsePeriod: + type: integer + format: int32 + enum: + - 3 + - 7 + - 14 + description: 'Days the candidate has to answer, chosen by the organization in the draft from the product policy: 3, 7, or 14. The deadline starts at the first delivery and is never reset by an email, a view, or a counter offer.' + examples: + - 7 + CandidateHandle: + type: string + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Opaque reference to a candidate as one organization sees it, taken from the organization-scoped anonymous card. It is a versioned HMAC alias, not a candidate account or profile identifier; it contains no contact information and is meaningless to another organization. The server resolves it only against the current visible cohort of the organization in the path. Clients never parse or construct it. It is shared by the candidate-card read and invitations. + examples: + - cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + InvitationRoleTitle: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Name of the offered role, for example "Middle Go developer in the payments team". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + InvitationTeamDescription: + type: string + minLength: 1 + maxLength: 1000 + pattern: \S + description: Description of the team the candidate would join, such as its size, roles, and way of working. It may contain line breaks and has at least one character that is not white space. Plain text; clients show it as text, never as HTML. It describes the job and must not contain personal data of employees or candidates. + InvitationOfferType: + type: string + description: |- + Type of the offer. + + - full_time: employment with a full working week. + - part_time: employment with a part-time working week. + - contract: a fixed-term or project contract outside employment. + - internship: an internship. + + Adding a value is a contract change. + enum: + - full_time + - part_time + - contract + - internship + InvitationCommunicationChannel: + type: string + description: |- + Channel through which the organization will contact the candidate after an acceptance. + + - email: a letter to the email address the candidate disclosed. + - phone: a call or a text to the phone number the candidate disclosed. + - telegram: a message to the Telegram username the candidate disclosed. + - video_call: an invitation to a video call, sent through one of the disclosed contacts. + + The channel describes the organization's plan; the candidate decides which contacts to disclose, and the server never requires that the disclosed fields include the channel. + enum: + - email + - phone + - telegram + - video_call + InvitationCommunicationMethod: + type: object + description: How the organization will contact the candidate after an acceptance. It is part of the terms, so the candidate sees it before choosing which contacts to disclose. An invitation without it cannot exist, because the terms require it. + additionalProperties: false + required: + - channel + - details + properties: + channel: + $ref: '#/components/schemas/InvitationCommunicationChannel' + details: + description: Optional short note, for example the first step or the expected time of the first contact, or null. Plain text without line breaks; it never contains a link or a contact of an employee. + oneOf: + - $ref: '#/components/schemas/InvitationCommunicationNote' + - type: 'null' + InvitationCommunicationNote: + type: string + minLength: 1 + maxLength: 300 + pattern: ^\S(?:.*\S)?$ + description: Short note on the communication method, for example "A 30-minute call with the team lead within three working days". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + InvitationPackageItemText: + type: string + minLength: 1 + maxLength: 300 + pattern: ^\S(?:.*\S)?$ + description: Short description of a condition, for example "Quarterly bonus up to 20% of the salary". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + InvitationPackageItemProvided: + type: object + description: The condition is part of the offer, with its description. + additionalProperties: false + required: + - status + - description + properties: + status: + type: string + enum: + - provided + description: + $ref: '#/components/schemas/InvitationPackageItemText' + InvitationPackageItemNotProvided: + type: object + description: The organization states explicitly that the offer does not include the condition ("Не предусмотрено" in the interface). It has no description. + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - not_provided + InvitationPackageItem: + description: 'One required condition of the package, selected by `status`: `provided` with a description, or `not_provided` without one. Not providing a condition is an explicit choice: the field is required in the package, so an absent field fails validation instead of meaning "not provided": it answers 400 `required` with its pointer, such as `/terms/package/training`. A `provided` item without a description answers `required` with the pointer of the description, and a `not_provided` item with a description answers `invalid` with the pointer of the item. ogen selects the variant by the value of `status`.' + oneOf: + - $ref: '#/components/schemas/InvitationPackageItemProvided' + - $ref: '#/components/schemas/InvitationPackageItemNotProvided' + InvitationPackage: + type: object + description: 'Required section of the package (PRD FR12): the bonus, the equipment, the training, and the voluntary health insurance (ДМС). Every field is required and is either provided with a description or explicitly not provided. The work format of the package is the required `work_formats` term, which has no "not provided" variant. Adding a required condition is a breaking change; an optional one is additive.' + additionalProperties: false + required: + - bonus + - equipment + - training + - health_insurance + properties: + bonus: + $ref: '#/components/schemas/InvitationPackageItem' + equipment: + $ref: '#/components/schemas/InvitationPackageItem' + training: + $ref: '#/components/schemas/InvitationPackageItem' + health_insurance: + $ref: '#/components/schemas/InvitationPackageItem' + InvitationTerms: + type: object + description: 'Terms of an invitation: everything the candidate sees before deciding and before any contact is disclosed. The same schema is the request field of a draft and the stored snapshot of a terms version, so a response can be sent back unchanged. Every field is required; a field that may have no value says so with an explicit variant (`location` null for a remote role, a package item `not_provided`). The terms never contain data of the candidate: no contact, no salary minimum, and no indicator derived from it. The server checks the cross-field rules after the schema and answers 400 validation_failed with the pointer of the field: the salary rules of SalaryRange with `/terms/salary/salary_to`, a missing place of work for the `office` or `hybrid` format with `/terms/location`, and a repeated technology in `tech_stack` with the pointer of the later item.' + additionalProperties: false + required: + - role_title + - specialization + - grade + - offer_type + - tasks + - team + - tech_stack + - work_formats + - location + - communication_method + - salary + - package + properties: + role_title: + $ref: '#/components/schemas/InvitationRoleTitle' + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + offer_type: + $ref: '#/components/schemas/InvitationOfferType' + tasks: + type: array + minItems: 1 + maxItems: 20 + description: Work tasks of the role in the order given. + items: + $ref: '#/components/schemas/NeedTaskText' + team: + $ref: '#/components/schemas/InvitationTeamDescription' + tech_stack: + type: array + minItems: 1 + maxItems: 30 + uniqueItems: true + description: Technologies of the role. The server compares names without regard to letter case. + items: + $ref: '#/components/schemas/SkillName' + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + description: Work formats the organization offers; the candidate may choose any of them. + items: + $ref: '#/components/schemas/WorkFormat' + location: + description: Place of work for the `office` or `hybrid` format, or null when the only format is `remote`. It is required with either of those formats. + oneOf: + - $ref: '#/components/schemas/NeedLocationName' + - type: 'null' + communication_method: + $ref: '#/components/schemas/InvitationCommunicationMethod' + salary: + $ref: '#/components/schemas/SalaryRange' + package: + $ref: '#/components/schemas/InvitationPackage' + InvitationNeedReference: + type: object + description: 'Need of the same organization that the invitation was built from, with the requirements version used. A direct invitation has no need. The link is informational: the invitation keeps its own terms, which may differ from the need, and a later change of the need never changes them.' + additionalProperties: false + required: + - need_id + - requirements_version + properties: + need_id: + type: string + format: uuid + description: Identifier of a need of the organization in the path. + requirements_version: + description: '`requirements_version` of the need that the invitation refers to; it must be a version that the need has had.' + allOf: + - $ref: '#/components/schemas/NeedVersion' + InvitationSalaryFit: + type: string + description: |- + Coarse indicator for the organization of how the salary range relates to the candidate's hidden minimum (PRD FR13). It is the only information about the minimum that the organization receives; the exact minimum never appears in any response, log, or problem. The server compares the upper bound `B` with the lowest minimum the candidate set for the offered work formats, in integer arithmetic and only in the same tax basis. + + - within_range: the minimum is not above `B`. + - up_to_10_percent_above: the minimum is above `B` by at most 10%, that is `10 * minimum <= 11 * B`. + - above: the minimum is more than 10% above `B`. + - withheld: the organization made five indicator-relevant settings within seven days, so the indicator is off for seven days from the fifth. The response to the fifth setting already carries `withheld`, and so does every draft and invitation of the organization, existing ones included, until the period ends. + - not_available: the candidate set no minimum for the offered formats, or set it in the other tax basis. + + Every change that can move this indicator is an indicator-relevant setting: the range set on creation, and in a draft a change of either bound, of the tax basis, or of `work_formats`, since the minimum depends on the format. Each counts against the organization-wide limit of three settings a day (429) and against the withheld counter of five settings within seven days, together with the ranges of needs. The one raise of the upper bound of a sent invitation counts against the withheld counter but not against the daily limit, because FR13 gives it its own once-only rule. Switching the tax basis turns `not_available` into a band or back and so tells the organization the basis of the minimum; this is accepted, and the switch counts against the limit like any other setting. + + The server never rejects or changes a range because of the minimum: a rejection would itself reveal it. + enum: + - within_range + - up_to_10_percent_above + - above + - withheld + - not_available + InvitationContactAccessState: + type: string + description: |- + Whether the organization may read the candidate's contacts through GetOrganizationInvitationContacts now. + + - not_granted: the candidate has not accepted this invitation, so no grant exists. + - available: a grant from this invitation is active and the current consent and visibility allow the read. + - closed: a grant from this invitation exists but does not allow the read now: it was revoked (the candidate revoked C4, cancelled the participation, or revoked the publication C2 or hid the profile after the acceptance), or it was created while the visibility already did not allow the read. The organization is not told which. A revoked grant never becomes `available` again; a grant blocked from the start becomes `available` once the candidate's visibility allows the read, which only follows the candidate's own choice to publish the profile or unhide it for the organization. Since every visibility change after a grant exists revokes the grant, a later toggle is never visible to the organization. + enum: + - not_granted + - available + - closed + InvitationContactAccess: + type: object + description: Contact access of the organization through this invitation, without any contact value. The values come only from GetOrganizationInvitationContacts. + additionalProperties: false + required: + - status + - fields + properties: + status: + $ref: '#/components/schemas/InvitationContactAccessState' + fields: + type: array + maxItems: 4 + uniqueItems: true + description: Kinds of contact that the read returns while `status` is `available`; empty otherwise. + items: + $ref: '#/components/schemas/ContactFieldKind' + InvitationOrganization: + type: object + description: Organization that sent the invitation, as the candidate sees it before deciding. The card that a candidate sees is `CandidateOrganizationCard` of the organization contract; returning it with the invitation is planned as an additive field, and this object only names the organization. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Public name of the organization. Plain text; clients show it as text, never as HTML. + InvitationDeclineReason: + type: string + description: |- + Structured reason of a decline. Every reason is neutral and none requires a comment. + + - salary: the salary range does not fit. + - tasks: the role or the tasks do not fit. + - stack: the technologies do not fit. + - work_format: the work format or the place of work does not fit. + - package: the package does not fit. + - company: the company or its domain does not fit. + - not_looking: the candidate is not looking for a job now. + - other_offer: the candidate accepted another offer. + - other: another reason ("Другое"); a comment stays optional. + + The organization never sees the reason of an individual decline: a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only the aggregates of FR12 with a minimum group size (planned). Adding a value is a contract change. + enum: + - salary + - tasks + - stack + - work_format + - package + - company + - not_looking + - other_offer + - other + InvitationDeclineComment: + type: string + minLength: 1 + maxLength: 500 + pattern: \S + description: Optional comment of the candidate on the offer. It may contain line breaks and has at least one character that is not white space. It is never shown to the organization, never published, and never written to logs or notifications; only the candidate reads it back. Plain text; clients show it as text, never as HTML. + InvitationDeclineRecord: + type: object + description: The candidate's own decline, as the candidate reads it back. + additionalProperties: false + required: + - reason + - comment + - declined_at + properties: + reason: + $ref: '#/components/schemas/InvitationDeclineReason' + comment: + oneOf: + - $ref: '#/components/schemas/InvitationDeclineComment' + - type: 'null' + declined_at: + $ref: '#/components/schemas/Timestamp' + OrganizationInvitation: + type: object + description: 'Invitation as the organization reads it: the candidate handle, the current terms version, the state, the coarse salary indicator, and the contact access without contact values. It never contains the candidate''s name, email address, phone number, or other contact, the exact salary minimum, or the reason and comment of a decline.' + additionalProperties: false + required: + - id + - organization_id + - candidate_handle + - need + - state + - expiry_reason + - version + - terms_version + - terms + - response_period_days + - response_deadline_at + - salary_raise_used + - salary_fit + - contact_access + - created_at + - updated_at + - delivered_at + - viewed_at + - responded_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization_id: + type: string + format: uuid + description: Organization that owns the invitation, equal to `org_id` of the path. It never changes. + candidate_handle: + $ref: '#/components/schemas/CandidateHandle' + need: + description: Need the invitation was built from, or null for a direct invitation. + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + description: Reason of an expiry, or null unless `state` is `expired`. + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + terms: + $ref: '#/components/schemas/InvitationTerms' + response_period_days: + $ref: '#/components/schemas/InvitationResponsePeriod' + response_deadline_at: + description: Moment when the candidate's time to answer ends, set at the first delivery to `delivered_at` plus `response_period_days`, or null for a draft. A command received at this moment or later is late. After an acceptance the deadline no longer applies. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + salary_raise_used: + type: boolean + description: Whether the one raise of the upper salary bound after sending (PRD FR13) has been used. It counts the whole history of the invitation. + salary_fit: + $ref: '#/components/schemas/InvitationSalaryFit' + contact_access: + $ref: '#/components/schemas/InvitationContactAccess' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + delivered_at: + description: Moment of delivery to the candidate's inbox, or null for a draft. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + viewed_at: + description: Moment when the candidate first opened the terms, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + responded_at: + description: Moment of the candidate's acceptance or decline, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + OrganizationInvitationSummary: + type: object + description: 'Invitation in the organization''s list: its identity, state, versions, role, salary range, deadline, and contact access. Read the invitation for the full terms and the salary indicator.' + additionalProperties: false + required: + - id + - candidate_handle + - need + - state + - expiry_reason + - version + - terms_version + - role_title + - salary + - response_deadline_at + - contact_access + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + candidate_handle: + $ref: '#/components/schemas/CandidateHandle' + need: + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + role_title: + $ref: '#/components/schemas/InvitationRoleTitle' + salary: + $ref: '#/components/schemas/SalaryRange' + response_deadline_at: + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + contact_access: + $ref: '#/components/schemas/InvitationContactAccess' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + OrganizationInvitationList: + type: object + description: One page of the invitations of an organization, newest first by creation time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Invitations of the page. + items: + $ref: '#/components/schemas/OrganizationInvitationSummary' + page: + $ref: '#/components/schemas/PageInfo' + OrganizationInvitationCreate: + type: object + description: New draft for one candidate. The candidate is named only by the handle from a search result of this organization, never by an email address, a phone number, or an account identifier. The terms are complete from the start, so a draft without the tax basis or the communication method cannot exist. Unknown fields are rejected, so a request cannot set the state, a version, a deadline, the salary indicator, contact access, or a candidate's minimum or contact. + additionalProperties: false + required: + - candidate_handle + - terms + properties: + candidate_handle: + $ref: '#/components/schemas/CandidateHandle' + need: + description: Need of the organization the invitation is built from, or null or absent for a direct invitation. + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + response_period_days: + description: Days to answer; absent means 7, the default of the product policy. + allOf: + - $ref: '#/components/schemas/InvitationResponsePeriod' + terms: + $ref: '#/components/schemas/InvitationTerms' + OrganizationInvitationUpdate: + type: object + description: 'Change of a draft over the version the client read. Each field present replaces that field as a whole and an absent field stays unchanged; `terms` is always replaced completely, never merged, and a change of the terms creates the next terms version. `need` sent as null unlinks the need. The candidate cannot change: a draft for another candidate is a new draft. Unknown fields are rejected.' + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/InvitationVersion' + need: + oneOf: + - $ref: '#/components/schemas/InvitationNeedReference' + - type: 'null' + response_period_days: + $ref: '#/components/schemas/InvitationResponsePeriod' + terms: + $ref: '#/components/schemas/InvitationTerms' + InvitationCommand: + type: object + description: 'Command without parameters over the invitation version the client read: send, withdraw, or cancel. Unknown fields are rejected.' + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/InvitationVersion' + InvitationSalaryRaise: + type: object + description: The one raise of the upper salary bound of a sent invitation (PRD FR13). Only `salary_to` changes; the lower bound, the currency, the period, and the tax basis stay fixed. Unknown fields are rejected, so the request cannot lower the lower bound or change the basis. + additionalProperties: false + required: + - expected_version + - salary_to + properties: + expected_version: + $ref: '#/components/schemas/InvitationVersion' + salary_to: + description: New upper bound, above the current one, with a width of the range from 10% to 40% of its midpoint. + allOf: + - $ref: '#/components/schemas/RubAmount' + CandidateInvitation: + type: object + description: 'Invitation as the addressed candidate reads it: the organization, the current terms with their version, the state and the deadline, the text and the choice of the consent C4 while an acceptance is possible, the candidate''s own decline, and the contact grant that the acceptance created. It has no candidate handle, no need, no salary indicator, and no contact value: the candidate''s own contacts and salary minimum stay in the profile.' + additionalProperties: false + required: + - id + - organization + - state + - expiry_reason + - version + - terms_version + - terms + - response_deadline_at + - delivered_at + - viewed_at + - responded_at + - updated_at + - contact_consent + - decline + - contact_grant + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization: + $ref: '#/components/schemas/InvitationOrganization' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + terms: + $ref: '#/components/schemas/InvitationTerms' + response_deadline_at: + $ref: '#/components/schemas/Timestamp' + delivered_at: + $ref: '#/components/schemas/Timestamp' + viewed_at: + description: Moment of the first view recorded by ViewMyInvitation, or null when the candidate has not opened the terms. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + responded_at: + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + updated_at: + $ref: '#/components/schemas/Timestamp' + contact_consent: + description: 'Text and choice of the consent C4 for an acceptance, or null when an acceptance is impossible now: the state does not allow it, the deadline has passed, or the profile holds no contact to disclose. In the last case the client tells the candidate to add a contact to the profile first, because a grant must cover at least one field.' + oneOf: + - $ref: '#/components/schemas/ContactConsentOffer' + - type: 'null' + decline: + description: The candidate's decline, or null unless `state` is `declined`. + oneOf: + - $ref: '#/components/schemas/InvitationDeclineRecord' + - type: 'null' + contact_grant: + description: Contact grant that the acceptance of this invitation created, or null when the invitation was never accepted. It stays after a revocation, with its status and reason. + oneOf: + - $ref: '#/components/schemas/ContactGrant' + - type: 'null' + CandidateInvitationSummary: + type: object + description: 'Invitation in the candidate''s inbox: the organization, the state, the versions, the role, the salary range, and the deadline. Listing never records a view; GetMyInvitation returns the full terms, and ViewMyInvitation records the view.' + additionalProperties: false + required: + - id + - organization + - state + - expiry_reason + - version + - terms_version + - role_title + - salary + - work_formats + - response_deadline_at + - delivered_at + - viewed_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the invitation. + organization: + $ref: '#/components/schemas/InvitationOrganization' + state: + $ref: '#/components/schemas/InvitationState' + expiry_reason: + oneOf: + - $ref: '#/components/schemas/InvitationExpiryReason' + - type: 'null' + version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + $ref: '#/components/schemas/InvitationTermsVersion' + role_title: + $ref: '#/components/schemas/InvitationRoleTitle' + salary: + $ref: '#/components/schemas/SalaryRange' + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + response_deadline_at: + $ref: '#/components/schemas/Timestamp' + delivered_at: + $ref: '#/components/schemas/Timestamp' + viewed_at: + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + updated_at: + $ref: '#/components/schemas/Timestamp' + CandidateInvitationList: + type: object + description: One page of the candidate's invitations, newest first by delivery time. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Invitations of the page. + items: + $ref: '#/components/schemas/CandidateInvitationSummary' + page: + $ref: '#/components/schemas/PageInfo' + InvitationAcceptance: + type: object + description: Acceptance of the current terms with the consent C4. The client sends the `version` and the `terms_version` it read and the contact fields the candidate selected; nothing is preselected or defaulted. Unknown fields are rejected, so a request cannot carry contact values, a grant, or another consent. + additionalProperties: false + required: + - expected_version + - terms_version + - consent_c4 + properties: + expected_version: + $ref: '#/components/schemas/InvitationVersion' + terms_version: + description: Terms version that the candidate read and accepts. A version that is not the current one answers 412 version_conflict. + allOf: + - $ref: '#/components/schemas/InvitationTermsVersion' + consent_c4: + $ref: '#/components/schemas/ContactConsentAcceptance' + InvitationDeclineRequest: + type: object + description: 'Structured decline: a reason and an optional comment. Unknown fields are rejected.' + additionalProperties: false + required: + - expected_version + - reason + properties: + expected_version: + $ref: '#/components/schemas/InvitationVersion' + reason: + $ref: '#/components/schemas/InvitationDeclineReason' + comment: + description: Optional comment for any reason, including `other`; absent or null means none. + oneOf: + - $ref: '#/components/schemas/InvitationDeclineComment' + - type: 'null' + ContactFieldKind: + type: string + description: |- + Kind of personal data that the consent C4 can disclose to one organization (PRD FR01 and FR12). The candidate selects each kind separately; one kind never implies another. + + - full_name: the full name from the profile. + - email: the contact email address from the profile. + - phone: the contact phone number from the profile. + - telegram: the Telegram username from the profile. + + The value formats are those of ContactDisclosure: a single-line full name of up to 200 characters, an E.164 phone number, and a Telegram username with the leading @. The profile contract (FR02) must store contacts in the same formats, so a disclosure never has to convert or drop a stored value. The FSP results of FR14, which need their own explicit permission, are planned as additional kinds. Adding a value is a contract change. + enum: + - full_name + - email + - phone + - telegram + ContactConsentText: + type: object + description: Currently published text of the consent C4 for this invitation. The server stores an acceptance with `text_version` and the hash of exactly this text, together with the organization, the selected fields, the invitation, and its terms version (the consent ledger). + additionalProperties: false + required: + - text_version + - text + properties: + text_version: + $ref: '#/components/schemas/ConsentTextVersion' + text: + type: string + minLength: 1 + maxLength: 100000 + description: Full consent text in plain UTF-8 with the name of the organization; paragraphs are separated by an empty line. The client shows it as text, never as HTML, next to the field choice. + ContactConsentOffer: + type: object + description: 'What the candidate can consent to in an acceptance: the consent text and the kinds of contact that the candidate''s profile holds now. It holds kinds only, never contact values, and nothing is preselected.' + additionalProperties: false + required: + - text + - available_fields + properties: + text: + $ref: '#/components/schemas/ContactConsentText' + available_fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Kinds of contact that the profile holds and that an acceptance may select. A kind outside this list answers 400 in an acceptance. + items: + $ref: '#/components/schemas/ContactFieldKind' + ContactConsentAcceptance: + type: object + description: 'Consent C4 given in an acceptance: the text version the candidate saw, an explicit `accepted`, and the contact fields the candidate selected. At least one field is required, so a hidden default or an empty choice never creates a grant. A text version that is not the currently published one answers 400 validation_failed with the pointer `/consent_c4/text_version`, and a field that the profile does not hold answers 400 with the pointer of that item, such as `/consent_c4/fields/1`. C4 is given only here, never at registration. The permission to pass the selected data on to the organization''s ATS (PRD C4 and FR19) is planned as an additive optional flag that defaults to no transfer.' + additionalProperties: false + required: + - text_version + - accepted + - fields + properties: + text_version: + $ref: '#/components/schemas/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Explicit consent. Only true is valid. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields the organization may read after the acceptance. The grant covers exactly these fields and no other. + items: + $ref: '#/components/schemas/ContactFieldKind' + ContactGrantState: + type: string + description: |- + State of a contact grant. + + - active: the grant exists. Each read by the organization still checks the consent C4, the grant, and the current visibility of the profile. + - revoked: the grant is closed for good; the organization reads no contact through it. A later publication of the profile or a new acceptance never reopens it; only a new explicit C4 creates a new grant. + enum: + - active + - revoked + ContactAccessBlock: + type: string + description: |- + Why an active grant does not allow a read now, shown only to the candidate. + + - visibility: the profile was not published (C2) or was hidden from the organization when the candidate accepted, and it still is. The acceptance never publishes the profile or lifts the hiding by itself (PRD FR12); the grant becomes readable once the candidate publishes the profile or unhides it for the organization. + enum: + - visibility + ContactRevocationReason: + type: string + description: |- + Why a contact grant was revoked, shown only to the candidate. + + - consent_revoked: the candidate revoked the consent C4 for the organization; every grant under it is closed. + - participation_cancelled: the candidate cancelled the participation in this invitation; only the grant of this invitation is closed. + - visibility_closed: the candidate revoked the publication C2 or hid the profile from the organization after the grant existed. A grant created while the visibility already did not allow a read stays active with `blocked_by` `visibility` instead. + + The withdrawal of an invitation by the organization, a no deal, and a negotiation timeout never revoke a grant. + enum: + - consent_revoked + - participation_cancelled + - visibility_closed + ContactGrant: + type: object + description: 'Contact grant as the candidate reads it: which fields one organization may read, from which invitation and terms version, and whether it is still active. It holds kinds only, never contact values. A grant is stored apart from the invitation state, so a later change of the state does not change it unless the state is a cancellation by the candidate.' + additionalProperties: false + required: + - id + - fields + - status + - readable + - blocked_by + - terms_version + - consent_text_version + - granted_at + - revoked_at + - revocation_reason + properties: + id: + type: string + format: uuid + description: Identifier of the grant. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that the grant covers. + items: + $ref: '#/components/schemas/ContactFieldKind' + status: + $ref: '#/components/schemas/ContactGrantState' + readable: + type: boolean + description: 'Whether the organization can read the covered fields now: true only for an active grant whose current consent and visibility allow the read. The organization sees the same fact as `contact_access.status` `available`, without the reason.' + blocked_by: + description: Why an active grant is not readable now, or null when it is readable or revoked; a revoked grant has `revocation_reason` instead. + oneOf: + - $ref: '#/components/schemas/ContactAccessBlock' + - type: 'null' + terms_version: + description: Terms version of the invitation that the acceptance accepted. + allOf: + - $ref: '#/components/schemas/InvitationTermsVersion' + consent_text_version: + description: Version of the consent C4 text that the candidate accepted. + allOf: + - $ref: '#/components/schemas/ConsentTextVersion' + granted_at: + $ref: '#/components/schemas/Timestamp' + revoked_at: + description: Moment of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + revocation_reason: + description: Reason of the revocation, or null while the grant is active. + oneOf: + - $ref: '#/components/schemas/ContactRevocationReason' + - type: 'null' + ContactPhoneNumber: + type: string + minLength: 8 + maxLength: 16 + pattern: ^\+[1-9][0-9]{6,14}$ + description: Phone number in the E.164 format, for example +70000000000. + ContactTelegramUsername: + type: string + minLength: 6 + maxLength: 33 + pattern: ^@[A-Za-z0-9_]{5,32}$ + description: Telegram username with the leading @. + ContactFullName: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:.*\S)?$ + description: Full name as the candidate wrote it in the profile. Plain text without line breaks; clients show it as text, never as HTML. + ContactDisclosure: + type: object + description: Contacts of the candidate that the organization may read through an active grant of this invitation. This is the only response that carries contact values, and it is separate from the terms and from the invitation. Each field the grant does not cover is null, and so is a covered field that the profile no longer holds. The response is never cached or stored by the server for later reads, so a revocation closes the next read at once. The value formats depend on the profile contract (FR02), which must store the same formats; see ContactFieldKind. + additionalProperties: false + required: + - invitation_id + - grant_id + - fields + - granted_at + - full_name + - email + - phone + - telegram + properties: + invitation_id: + type: string + format: uuid + description: Invitation whose acceptance created the grant. + grant_id: + type: string + format: uuid + description: Grant that allows the read. + fields: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that the grant covers. + items: + $ref: '#/components/schemas/ContactFieldKind' + granted_at: + $ref: '#/components/schemas/Timestamp' + full_name: + oneOf: + - $ref: '#/components/schemas/ContactFullName' + - type: 'null' + email: + oneOf: + - $ref: '#/components/schemas/EmailAddress' + - type: 'null' + phone: + oneOf: + - $ref: '#/components/schemas/ContactPhoneNumber' + - type: 'null' + telegram: + oneOf: + - $ref: '#/components/schemas/ContactTelegramUsername' + - type: 'null' + ConsentPurposeCode: + type: string + description: |- + One of the independent consents of PRD FR01. A grant or a revocation of one purpose never changes another. + + - c1: processing of personal data, given at registration. + - c2: publication of the candidate card. The record proves the consent to the published text; which fields were published and when is evidence of the publication history, not of this record. Adding a field scope to c2 records later is an additive change. + - c3: automatic categorization. Without it the candidate can request a manual assessment by the same rubric. + - c4: transfer of the selected contact data to one organization, currently given only in an invitation acceptance. + - c5: import of FSP results. + + ConsentPurpose lists the subset whose text the client may read before an account exists. + enum: + - c1 + - c2 + - c3 + - c4 + - c5 + ConsentState: + type: string + description: |- + State of a consent record, computed from the ledger. + + - active: the consent holds. For c1, c2, c3, and c5 it is the newest unrevoked record of its purpose; every unrevoked c4 record is active, one per accepted invitation. + - superseded: the subject later accepted another text version of the same purpose and has not revoked either. The record stays as evidence for its own time; it never applies to c4. + - revoked: the consent was revoked. The record keeps its grant and its one revocation time; a later grant is a new record and never reopens it. + enum: + - active + - superseded + - revoked + ConsentSource: + type: string + description: |- + Where the subject gave the consent. + + - registration: the c1 acceptance of RegisterAccount. + - consent_settings: the consent settings of the account, for c1, c2, c3, and c5 (planned). + - invitation_acceptance: the c4 acceptance of AcceptMyInvitation. + + A c4 given when sending an application (PRD Q9) is planned as an additional value. + enum: + - registration + - consent_settings + - invitation_acceptance + ConsentRevocationSource: + type: string + description: |- + Who recorded a revocation. + + - consent_settings: the subject revoked the consent in the product. + - support_request: an operator recorded a revocation that the subject requested through support. + enum: + - consent_settings + - support_request + ConsentOrganization: + type: object + description: Organization of a c4 consent as the consent recorded it. `name` is a snapshot of the name that the shown consent text carried at the time of the consent, and the stored text hash proves that text with this name; a later rename of the organization does not change it, so it can differ from the current name. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Name of the organization in the consent text at the time of the consent. Plain text; clients show it as text, never as HTML. + ConsentRecord: + type: object + description: 'One record of the consent ledger as its subject reads it: the purpose, the text version the subject accepted, where and when the consent was given, its state, and the revocation. A c4 record also names the organization, the contact fields, and the invitation with its terms version; these fields are null for every other purpose. The server also stores the SHA-256 hash of exactly the text the subject saw, which a client never sends or receives.' + additionalProperties: false + required: + - id + - purpose + - state + - text_version + - source + - granted_at + - revoked_at + - revocation_source + - organization + - fields + - invitation_id + - invitation_terms_version + properties: + id: + type: string + format: uuid + description: Identifier of the record. + purpose: + $ref: '#/components/schemas/ConsentPurposeCode' + state: + $ref: '#/components/schemas/ConsentState' + text_version: + description: Version of the consent text that the subject accepted. + allOf: + - $ref: '#/components/schemas/ConsentTextVersion' + source: + $ref: '#/components/schemas/ConsentSource' + granted_at: + $ref: '#/components/schemas/Timestamp' + revoked_at: + description: Moment of the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + revocation_source: + description: Who recorded the revocation, or null unless `state` is `revoked`. + oneOf: + - $ref: '#/components/schemas/ConsentRevocationSource' + - type: 'null' + organization: + description: Organization that a c4 consent allows to read the fields, with the name the consent text showed, or null for every other purpose. + oneOf: + - $ref: '#/components/schemas/ConsentOrganization' + - type: 'null' + fields: + type: + - array + - 'null' + minItems: 1 + maxItems: 4 + uniqueItems: true + description: Contact fields that a c4 consent covers, or null for every other purpose. One kind never implies another. + items: + $ref: '#/components/schemas/ContactFieldKind' + invitation_id: + type: + - string + - 'null' + format: uuid + description: Invitation whose acceptance gave a c4 consent, or null for every other purpose. + invitation_terms_version: + description: Terms version that the acceptance accepted, or null for every other purpose. + oneOf: + - $ref: '#/components/schemas/InvitationTermsVersion' + - type: 'null' + ConsentRecordList: + type: object + description: One page of the consent ledger of the current account, newest grant first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Records of the page. + items: + $ref: '#/components/schemas/ConsentRecord' + page: + $ref: '#/components/schemas/PageInfo' + ConsentSettingsGrantRequest: + type: object + description: Accept the current published text shown by GetMyConsentText. The server checks its version again before recording the grant. + additionalProperties: false + required: + - text_version + - accepted + properties: + text_version: + $ref: '#/components/schemas/ConsentTextVersion' + accepted: + type: boolean + enum: + - true + description: Must be true to record an explicit acceptance. + ConsentDeletionRequest: + type: object + description: Durable request to delete the account and its personal data. The request is recorded before asynchronous processing starts; it does not mean deletion has completed. + additionalProperties: false + required: + - id + - status + - requested_at + properties: + id: + type: string + format: uuid + description: Identifier of the durable deletion request. + status: + type: string + enum: + - requested + - processing + description: Current state of the deletion request. + requested_at: + $ref: '#/components/schemas/Timestamp' + OrganizationVersion: + type: integer + format: int64 + minimum: 1 + description: 'Version of the profile of an organization. Creation makes version 1, and every committed change of the profile advances it by exactly one. A change carries the version the client read as `expected_version`. Only the profile has a version: the memberships and the verification level of the organization do not advance it.' + examples: + - 2 + OrganizationName: + type: string + minLength: 1 + maxLength: 200 + pattern: ^\S(?:[^\n\r]*\S)?$ + description: Public name of the organization, for example the legal name that a candidate knows. It has no leading or trailing whitespace and no line breaks, and it is at most 200 characters because consent records keep a copy of it. Plain text; clients show it as text, never as HTML. A later rename never changes the copy that a consent record holds. + examples: + - ООО Пример Платежи + OrganizationDescription: + type: string + minLength: 1 + maxLength: 2000 + description: What the organization does, written for candidates. It may contain line breaks; the server stores CRLF as LF, and it refuses leading and trailing whitespace and any other control character. Plain text; clients show it as text, never as HTML. + examples: + - Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + OrganizationSphere: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Field of business of the organization as free text, for example "Платежи и финансовые сервисы". It has no leading or trailing whitespace and no line breaks. The product has no sphere taxonomy yet; a taxonomy code would be an additive field. Plain text; clients show it as text, never as HTML. + examples: + - Платежи и финансовые сервисы + OrganizationWebsite: + type: string + minLength: 9 + maxLength: 300 + pattern: ^https://[^\s/?#@]+(?:[/?#][^\s]*)?$ + description: 'Public website of the organization: an https URL with a host name, without credentials. The server also refuses a port, an IP address, a host name without a dot, and `localhost`. It never fetches the address.' + examples: + - https://payments.example.com + OrganizationContactChannels: + type: object + description: Public contacts of the organization, the ones a candidate sees on its card. They are company channels, such as a careers mailbox, the website, a company phone, or a company Telegram account, and never the personal email address, phone, or messenger of an employee; personal contacts of the people of the organization stay out of this object. The server cannot tell a company address from a personal one, so the owner answers for the content, and a candidate can complain about an organization through a support case. The object is the request field and the stored value alike, so a response can be sent back unchanged; every field is required and null means not set. A change replaces the whole object, never a single field of it. + additionalProperties: false + required: + - website + - email + - phone + - telegram + properties: + website: + oneOf: + - $ref: '#/components/schemas/OrganizationWebsite' + - type: 'null' + email: + description: Public mailbox of the organization, such as a careers address, or null. It is stored in the form it was given. + oneOf: + - $ref: '#/components/schemas/EmailAddress' + - type: 'null' + phone: + description: Public phone number of the organization, or null. + oneOf: + - $ref: '#/components/schemas/ContactPhoneNumber' + - type: 'null' + telegram: + description: Public Telegram account of the organization, or null. + oneOf: + - $ref: '#/components/schemas/ContactTelegramUsername' + - type: 'null' + OrganizationRepresentative: + type: object + description: 'A person that speaks for the organization to candidates, as the owner presents them on the card. It is presentation only: a representative is not a member of the organization, has no account link, and gains no right from being listed, and a member does not become a representative by joining. It holds no contact of the person; reaching the organization goes through its public contacts. The name is personal data of an employee that the owner publishes, so the owner must have the right to do it; see the open questions in the organization section of the API guide.' + additionalProperties: false + required: + - name + - job_title + properties: + name: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Name of the person as the card shows it. It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + job_title: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Position of the person in the organization, for example "Руководитель по подбору". It has no leading or trailing whitespace and no line breaks. Plain text; clients show it as text, never as HTML. + OrganizationVerificationLevel: + type: string + description: |- + Trust level of an organization (PRD FR07). It limits the quotas of the organization and, in a planned mode, the access of candidates under 18; it never replaces the consent of a candidate. + + - e0: the confirmed email of the account that created the organization. Every new organization starts here. + - e1: a corporate email, a verified domain, and a link with the organization. + - e2: a check of the requisites and of the authority of the person. + - e3: a manual check or a partner status. + + The server reports e1, e2, or e3 only after a verification process has recorded it for the organization. No request of this contract sets or raises a level, and neither does an edit of the profile, the size of the profile, the number of members, or the domain of an email address. The first slice of the product uses e0 and e1; the processes for e1, e2, and e3 do not exist yet, so a client treats every level other than e0 as unavailable until they do. Adding a level is a contract change. + enum: + - e0 + - e1 + - e2 + - e3 + OrganizationVerificationBasis: + type: string + description: |- + Ground of the current verification level, the reason a cabinet can show next to it. + + - confirmed_email: the confirmed email of the creating account (e0). + - corporate_domain: a corporate email and a verified domain (e1). + - requisites_and_authority: a check of the requisites and of the authority (e2). + - manual_review: a manual check by the platform (e3). + - partner_status: a partner status (e3). + + Each level has its own bases, so a level and a basis that do not belong together never occur. Adding a value is a contract change. + enum: + - confirmed_email + - corporate_domain + - requisites_and_authority + - manual_review + - partner_status + OrganizationVerification: + type: object + description: 'Verification level of an organization with its ground and the time it was set. It is read-only everywhere in this contract: the server sets it, and no request carries it. The scope of the check and the history of changes (PRD FR07) are planned as additive fields and a separate history with the first verification process.' + additionalProperties: false + required: + - level + - basis + - changed_at + properties: + level: + $ref: '#/components/schemas/OrganizationVerificationLevel' + basis: + $ref: '#/components/schemas/OrganizationVerificationBasis' + changed_at: + description: Moment the level was set to its current value; for a new organization, the creation time. + allOf: + - $ref: '#/components/schemas/Timestamp' + CandidateOrganizationCard: + type: object + description: 'The card of an organization as a candidate sees it: what an invitation shows before the candidate decides. The server builds it from the profile and the verification level and returns it to the owner as the preview of PRD FR07 ("through the eyes of the candidate"); a client never sends it. It holds no membership, no role, no account, no version, and no ground of the verification: a member''s email address, the number of members, and the history of the organization stay out of it. The card is the same object that the candidate side will return (planned in the invitation contract). Only a candidate who received an invitation from the organization sees it; it is not a public page, and no operation shows it to anyone else until the open question about publishing the names of representatives is decided (152-FZ). The server may leave `representatives` out, and a card without them means that the representatives are not published, not that the organization has none.' + additionalProperties: false + required: + - id + - name + - description + - sphere + - contacts + - verification_level + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + $ref: '#/components/schemas/OrganizationName' + description: + description: Description of the organization, or null. + oneOf: + - $ref: '#/components/schemas/OrganizationDescription' + - type: 'null' + sphere: + description: Field of business of the organization, or null. + oneOf: + - $ref: '#/components/schemas/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/components/schemas/OrganizationContactChannels' + representatives: + type: + - array + - 'null' + maxItems: 10 + description: Representatives in the order the owner gave them. Absent or null means that they are not published on this card, which says nothing about whether the organization has any. + items: + $ref: '#/components/schemas/OrganizationRepresentative' + verification_level: + $ref: '#/components/schemas/OrganizationVerificationLevel' + Organization: + type: object + description: 'Organization as its members read it: the profile that the owner edits, the verification level that only the server sets, and the card that a candidate sees. It never contains a role, a membership, the members of the organization, or an account identifier, so no field of it can raise a right: the role of the caller is in `OrganizationMembership` and comes only from the membership held by the server. The profile fields repeat in `candidate_card`, which is the candidate''s view of them; the client reads the profile fields for the form and `candidate_card` for the preview.' + additionalProperties: false + required: + - id + - version + - name + - description + - sphere + - contacts + - representatives + - verification + - candidate_card + - created_at + - updated_at + properties: + id: + type: string + format: uuid + description: Identifier of the organization, the `org_id` of every organization-scoped path. It never changes. + version: + $ref: '#/components/schemas/OrganizationVersion' + name: + $ref: '#/components/schemas/OrganizationName' + description: + description: Description of the organization, or null. + oneOf: + - $ref: '#/components/schemas/OrganizationDescription' + - type: 'null' + sphere: + description: Field of business of the organization, or null. + oneOf: + - $ref: '#/components/schemas/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/components/schemas/OrganizationContactChannels' + representatives: + type: array + maxItems: 10 + description: Representatives in the order the owner gave them. + items: + $ref: '#/components/schemas/OrganizationRepresentative' + verification: + $ref: '#/components/schemas/OrganizationVerification' + candidate_card: + $ref: '#/components/schemas/CandidateOrganizationCard' + created_at: + $ref: '#/components/schemas/Timestamp' + updated_at: + $ref: '#/components/schemas/Timestamp' + OrganizationCreate: + type: object + description: New organization. Only `name` is required, so a company can start with its name and complete the card later. The creating account becomes the owner of the organization; the body has no field for a role, a membership, an owner, a verification level, or a version, and unknown fields are rejected, so a request cannot set any of them. An absent `description` or `sphere`, and one sent as null, stay unset; an absent `contacts` has every contact unset; an absent `representatives` is an empty list. + additionalProperties: false + required: + - name + properties: + name: + $ref: '#/components/schemas/OrganizationName' + description: + oneOf: + - $ref: '#/components/schemas/OrganizationDescription' + - type: 'null' + sphere: + oneOf: + - $ref: '#/components/schemas/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/components/schemas/OrganizationContactChannels' + representatives: + type: array + maxItems: 10 + items: + $ref: '#/components/schemas/OrganizationRepresentative' + OrganizationUpdate: + type: object + description: Change of the profile of an organization over the version the client read. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged, and a representative left out of a sent list is removed. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. The body can change the profile only. It has no field for a role, a membership, an owner, a verification level, a basis, or a card, and unknown fields are rejected, so editing the profile can neither raise a right nor raise the trust level of the organization; both change only through processes of the server. + additionalProperties: false + required: + - expected_version + properties: + expected_version: + $ref: '#/components/schemas/OrganizationVersion' + name: + $ref: '#/components/schemas/OrganizationName' + description: + oneOf: + - $ref: '#/components/schemas/OrganizationDescription' + - type: 'null' + sphere: + oneOf: + - $ref: '#/components/schemas/OrganizationSphere' + - type: 'null' + contacts: + $ref: '#/components/schemas/OrganizationContactChannels' + representatives: + type: array + maxItems: 10 + items: + $ref: '#/components/schemas/OrganizationRepresentative' + OrganizationRole: + type: string + description: |- + Role of a member in an organization (PRD 2.2 and the FR07 matrix). The role belongs to the membership, never to the organization or to any editable profile. + + - owner: manages the organization and its members, and acts on behalf of the company. + - recruiter: leads the selection of candidates for all needs. + - hiring_manager: acts on the needs assigned to the member. + - technical_expert: refines the requirements of the assigned needs; reads no contacts and sends no invitations. + + In the MVP only the owner acts, so the other roles grant nothing yet: an operation that is not open to a role answers 403 `forbidden`. The full matrix is planned, and applying it changes no field of this contract. Adding a role is a contract change. + enum: + - owner + - recruiter + - hiring_manager + - technical_expert + MembershipState: + type: string + description: |- + State of a membership. Only `active` gives access: every other state answers as if the account were no member. + + - active: the member works in the organization with the role. + - suspended: access is stopped, and the owner or the platform may restore it. + - removed: the owner or the platform ended the membership. A removal by the platform is not undone by the owner or by an invitation: the acceptance of an employee invitation and the member management must not reactivate it on their own. Who removed the member and why become additive fields of the member management. + - left: the member ended the membership. + + One account has at most one membership per organization, so a former member who returns gets the same membership back in `active`, and the history of the pair is the history of its audit events (planned). The listing of this contract returns only `active` memberships; the other states are listed now so that generated clients accept them when the member management reads them. Adding a state is a contract change. + enum: + - active + - suspended + - removed + - left + OrganizationMembership: + type: object + description: The membership of the caller in one organization. The caller is the account of the session, so the object holds no account identifier. Only the server sets the role and the state, through the operations that manage members, which are planned; no operation of this contract changes them. + additionalProperties: false + required: + - organization_id + - role + - state + - joined_at + properties: + organization_id: + type: string + format: uuid + description: Identifier of the organization. + role: + $ref: '#/components/schemas/OrganizationRole' + state: + $ref: '#/components/schemas/MembershipState' + joined_at: + description: Moment the membership was first created. A member who left and returns keeps the same value, because the pair has one membership; the moment of the latest activation is a planned additive field (`activated_at`). + allOf: + - $ref: '#/components/schemas/Timestamp' + OrganizationSummary: + type: object + description: 'An organization in the list of the caller''s organizations: what a switcher needs to name it. The profile, the contacts, and the representatives are in `Organization`.' + additionalProperties: false + required: + - id + - name + - verification_level + properties: + id: + type: string + format: uuid + description: Identifier of the organization, the `org_id` of its paths. + name: + $ref: '#/components/schemas/OrganizationName' + verification_level: + $ref: '#/components/schemas/OrganizationVerificationLevel' + MyOrganization: + type: object + description: An organization available to the caller together with the caller's membership in it. + additionalProperties: false + required: + - organization + - membership + properties: + organization: + $ref: '#/components/schemas/OrganizationSummary' + membership: + $ref: '#/components/schemas/OrganizationMembership' + MyOrganizationList: + type: object + description: One page of the organizations available to the caller, newest membership first. It holds only organizations where the caller has an `active` membership, so it is also the list of contexts the caller can work in; it never names an organization the caller cannot enter. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Organizations of the page. + items: + $ref: '#/components/schemas/MyOrganization' + page: + $ref: '#/components/schemas/PageInfo' + PublicationVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the publication setting of the candidate. A candidate who has never published has version 0 and the profile is closed; every change that alters the setting advances it by one. The client sends the version it read as `expected_version`. It is independent of the versions of the profile and of the search status, so a change of one never makes another stale. + examples: + - 2 + SearchStatusVersion: + type: integer + format: int64 + minimum: 0 + description: Version of the search status of the candidate. A candidate who never set the status has version 0 and the status `not_looking`; every confirmation or change advances it by one. The client sends the version it read as `expected_version`. + examples: + - 3 + CardField: + type: string + description: |- + A group of values of the anonymous candidate card that the candidate chooses to publish. The set is closed and has no value for the full name, a contact, or the lowest salary: the card never carries them, so no choice and no later contract change in this list can publish them by accident. Contacts leave only through the contact grant of an accepted invitation (C4), and the lowest salary never leaves. + + - categories: specialization and grade confirmed by an authoritative assessment result. With it an organization receives the confirmed category and, with each category of the card, one supporting assessment fact: its skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration that mark a synthetic, uncalibrated demonstration (`GetOrganizationCandidateEvidence`). The candidate sees the same on `GetMyCardPreview`. + - self_assessment: the candidate's declared specialization and grade, separate from confirmed categories. + - stack: only recognized technology codes from the server's closed taxonomy. + - experience: a coarse total-experience band, without employers, periods, or descriptions. + - work_formats: explicitly selected work formats from the private questionnaire. + - salary_compatibility: a nullable compatibility outcome with no salary amounts or bounds. + - projects: the projects of the profile with their title, description, stack tags, and whether a linked repository is a public GitHub repository. The titles and descriptions are text that the candidate writes and may identify them; the repository address and its owner never reach an organization through the card. Published projects are also the text that semantic ranking reads and that match explanations name. + - soft_skills, location, and relocation: retained only for compatibility in existing saved sets; they are not returned by the anonymous card. + + Only values that the candidate confirmed ever reach the card: an unconfirmed suggestion (status `extracted`) and an unknown value never do, whatever the field set says. + + Adding a value is a contract change that lets a candidate publish more, and it is also a migration (the function `candidate_card_fields_are_canonical` and the CHECK constraints of the publication and event tables list the codes). A client treats an unknown value as a reason to ask for an update, and the server never adds a new value to a published set on its own. + enum: + - categories + - salary_compatibility + - self_assessment + - stack + - experience + - soft_skills + - location + - relocation + - work_formats + - projects + CardFieldSet: + type: array + minItems: 0 + maxItems: 10 + uniqueItems: true + description: Distinct card fields. The server stores them in ascending order of the codes and answers them in that order, whatever order the client sent, so equal sets are equal arrays. + items: + $ref: '#/components/schemas/CardField' + PublicationState: + type: string + description: |- + Whether the candidate card can be read by organizations at all. It is computed from the stored publication and the consent ledger: a profile is closed unless the candidate published it and the C2 consent that backs the publication is still unrevoked. + + - closed: no organization reads the card. This is the state of every new profile and of a profile whose publication was closed or whose C2 was revoked. + - published: organizations may read exactly the fields in `fields`, except for the organizations the candidate hid. + enum: + - closed + - published + PublicationClosedReason: + type: string + description: |- + Why a closed profile is closed, shown only to the candidate. + + - never_published: the candidate has never published the profile. + - closed_by_candidate: the candidate closed the publication. + - consent_revoked: the C2 consent that backed the publication was revoked. A later C2 grant never reopens the publication; the candidate publishes again explicitly and the new publication refers to the new consent record. + enum: + - never_published + - closed_by_candidate + - consent_revoked + Publication: + type: object + description: 'Publication setting of the candidate card. It is separate from the consent: the C2 consent in the ledger proves that the candidate accepted the publication text, and this setting records whether and which fields are published. `state` is `published` only while the referenced C2 record is unrevoked, whatever the stored setting says, so a revocation closes the card at once. The state, the fields, and the times belong to the history that the C2 consent record does not carry.' + additionalProperties: false + required: + - state + - closed_reason + - fields + - consent_id + - published_at + - version + properties: + state: + $ref: '#/components/schemas/PublicationState' + closed_reason: + description: Why the profile is closed, or null while it is published. + oneOf: + - $ref: '#/components/schemas/PublicationClosedReason' + - type: 'null' + fields: + description: Card fields that organizations may read. Empty exactly when `state` is `closed`. + allOf: + - $ref: '#/components/schemas/CardFieldSet' + consent_id: + description: Identifier of the C2 record of the consent ledger that backs the current or the last publication, the `id` of a `ConsentRecord` of this account, or null when the profile was never published. + oneOf: + - type: string + format: uuid + - type: 'null' + published_at: + description: Moment of the latest change that published or republished the card, or null while the profile was never published. It stays after a closing, as the time of the last publication. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + version: + $ref: '#/components/schemas/PublicationVersion' + PublicationUpdate: + type: object + description: 'The complete new publication setting. `published` needs a non-empty set of fields and an active C2 consent of the account; `closed` needs an empty set and never fails for a missing consent. The body names no consent: the server binds the publication to the account''s current unrevoked C2 record, and a client can neither supply nor forge one.' + additionalProperties: false + required: + - expected_version + - state + - fields + properties: + expected_version: + $ref: '#/components/schemas/PublicationVersion' + state: + $ref: '#/components/schemas/PublicationState' + fields: + $ref: '#/components/schemas/CardFieldSet' + SearchStatusValue: + type: string + description: |- + Whether the candidate says they are searching for work. The status is a statement, never a consent: it publishes nothing, hides nothing, and grants nothing, and no value of it changes the C2 consent, the publication, or the hidden organizations. + + - looking: the candidate is searching ("Ищу"). It holds only while it is confirmed in time; see `SearchStatus.lapsed`. + - not_looking: the candidate is not announcing a search. It is the state of every new account and the state to which a lapsed status falls. + enum: + - looking + - not_looking + SearchStatus: + type: object + description: 'Search status of the candidate as it holds now. The status `looking` stores the moment of its confirmation and lapses when the confirmation interval of the product policy passes without a new confirmation. A lapse only ever narrows: the status falls to `not_looking`, which is the non-public state, and a lapse never changes the publication or the hidden organizations. It needs no stored change, so no process can make a candidate more visible by expiry, and a lapsed candidate confirms again explicitly.' + additionalProperties: false + required: + - value + - lapsed + - confirmed_at + - lapses_at + - version + properties: + value: + description: 'The status that holds now: `looking` only while the confirmation has not lapsed.' + allOf: + - $ref: '#/components/schemas/SearchStatusValue' + lapsed: + type: boolean + description: True when the candidate set `looking`, did not confirm it again, and the interval ended, so `value` is `not_looking`. False otherwise, including a status the candidate cleared. + confirmed_at: + description: Moment of the latest confirmation of `looking`, or null when the candidate never set it or cleared it. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + lapses_at: + description: Moment at which the confirmed status lapses, fixed when it was confirmed from the `search_status` section of the product policy version in force then, or null when `confirmed_at` is null. A later policy change does not move it; it stays in the past for a lapsed status. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + version: + $ref: '#/components/schemas/SearchStatusVersion' + SearchStatusUpdate: + type: object + description: 'The complete new search status. `looking` is also the confirmation of a status that still holds or has lapsed: it sets the confirmation time to now. The body carries no time, interval, or policy version; the server takes them from the effective product policy.' + additionalProperties: false + required: + - expected_version + - value + properties: + expected_version: + $ref: '#/components/schemas/SearchStatusVersion' + value: + $ref: '#/components/schemas/SearchStatusValue' + PrivacyOrganization: + type: object + description: Organization as the candidate who hid it reads it. The name is the current name of the organization. The candidate must already have been able to see the organization to hide it, so the reference tells them nothing that they could not read before. + additionalProperties: false + required: + - id + - name + properties: + id: + type: string + format: uuid + description: Identifier of the organization. + name: + type: string + minLength: 1 + maxLength: 200 + description: Current name of the organization. Plain text; clients show it as text, never as HTML. + HiddenOrganization: + type: object + description: 'One organization that the candidate hides the profile from. The record belongs to the candidate: no organization reads it, learns that it was hidden, or can tell a hidden candidate from one who is not published.' + additionalProperties: false + required: + - organization + - hidden_at + properties: + organization: + $ref: '#/components/schemas/PrivacyOrganization' + hidden_at: + $ref: '#/components/schemas/Timestamp' + HiddenOrganizationList: + type: object + description: One page of the organizations that the candidate hides the profile from, newest first with the organization identifier as the tie-breaker. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Hidden organizations of the page. + items: + $ref: '#/components/schemas/HiddenOrganization' + page: + $ref: '#/components/schemas/PageInfo' + PrivacySettings: + type: object + description: 'The visibility settings of the current candidate in one read: the publication, the search status, and the number of hidden organizations. The three are independent: each has its own version and its own operation, and a change of one leaves the others as they were. A new account reads a closed profile, `not_looking`, and no hidden organization.' + additionalProperties: false + required: + - publication + - search_status + - hidden_organizations_total + properties: + publication: + $ref: '#/components/schemas/Publication' + search_status: + $ref: '#/components/schemas/SearchStatus' + hidden_organizations_total: + type: integer + minimum: 0 + maximum: 1000 + description: Number of organizations that the candidate hides the profile from. The list is read with `ListMyHiddenOrganizations`. + CardCategory: + type: object + description: A category confirmed by assessment results, as the card shows it. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which is never a standard confirmation. + additionalProperties: false + required: + - specialization + - grade + - strength + - basis + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + strength: + type: string + enum: + - standard + - strong + description: Coarse strength of the authoritative confirmation. + basis: + $ref: '#/components/schemas/EvidenceBasis' + AnonymousCardContent: + type: object + description: 'The anonymous candidate card as an organization reads it. Only explicitly published values reach it; unconfirmed stack suggestions and unknown values never do. Stack output uses a closed taxonomy. It carries no name, contact, resume text, employer, salary figure, account or profile identifier, and no schema of the private profile or of a contact disclosure is reachable from it; a contact reaches an organization only through the contact grant of an accepted invitation. Each property is null when its field is not published or the candidate has no value for it, so the card does not tell the two apart. The set of properties is closed, and an organization-visible card must never gain a property that identifies the candidate. The one free-text exception is `projects`: the candidate writes it and publishes it by a separate explicit choice, the card never adds the repository address or owner to it, and the client warns that a project title can identify its author. The search ranking and the full card of an organization''s search result are defined by the search contract, which reuses this content.' + additionalProperties: false + required: + - pseudonym + - categories + - stack + - self_assessment + - experience_band + - work_formats + - salary_compatibility + - projects + properties: + pseudonym: + type: string + minLength: 47 + maxLength: 47 + pattern: ^cv1_[A-Za-z0-9_-]{43}$ + description: Stable opaque alias scoped to the reading organization. It is not an account or profile identifier and changes across organizations. + categories: + type: + - array + - 'null' + maxItems: 9 + description: Categories confirmed by assessment results, or null. + items: + $ref: '#/components/schemas/CardCategory' + stack: + type: + - array + - 'null' + maxItems: 4 + description: Recognized confirmed technology codes only, or null. + items: + type: string + enum: + - go + - postgresql + - kafka + - docker + self_assessment: + type: + - array + - 'null' + maxItems: 9 + description: Candidate-declared specialization and grade, separate from categories. + items: + $ref: '#/components/schemas/CardSelfAssessment' + experience_band: + oneOf: + - $ref: '#/components/schemas/CandidateExperienceBand' + - type: 'null' + description: Coarse total work-experience bucket, or null. + work_formats: + type: + - array + - 'null' + maxItems: 3 + description: Explicitly opted-in work formats, or null. + items: + $ref: '#/components/schemas/CandidateWorkFormat' + salary_compatibility: + oneOf: + - $ref: '#/components/schemas/CandidateSalaryCompatibility' + - type: 'null' + description: Nullable compatibility result with no salary values. + projects: + type: + - array + - 'null' + maxItems: 10 + description: 'Published projects in the candidate''s order, or null. Cohort generalization never changes them: they are text the candidate chose to publish, so publishing them can make the card unique.' + items: + $ref: '#/components/schemas/CardProject' + CardPreview: + type: object + description: A private candidate preview computed from the current profile, publication, and consent ledger. Its pseudonym uses a separate preview context and is not an organization's alias. Organization-specific visibility filters and cohort checks can further generalize or suppress the organization-facing card. This read creates no view or history record and never reaches an organization. `card` is null while the profile is closed. `evidence` is what an organization would read in the evidence section of the card, one supporting assessment fact for each category of the card, and is null exactly when `card` is null; the organization-facing section can still be generalized or suppressed. + additionalProperties: false + required: + - state + - fields + - card + - evidence + - generated_at + properties: + state: + $ref: '#/components/schemas/PublicationState' + fields: + $ref: '#/components/schemas/CardFieldSet' + card: + oneOf: + - $ref: '#/components/schemas/AnonymousCardContent' + - type: 'null' + evidence: + oneOf: + - $ref: '#/components/schemas/OrganizationEvidence' + - type: 'null' + generated_at: + $ref: '#/components/schemas/Timestamp' + PrivacyEventKind: + type: string + description: |- + Kind of a change of the visibility settings that the history records. + + - publication_opened: the candidate published a closed profile. + - publication_changed: the candidate changed the published fields of a published profile, or published it again under a new C2 record. + - publication_closed: the candidate closed the publication. A revocation of C2 closes the card by the ledger and is read from the consent history, not recorded here. + - search_status_confirmed: the candidate set or confirmed `looking`. + - search_status_cleared: the candidate set `not_looking`. A lapse is not an event: it is computed. + - organization_hidden: the candidate hid the profile from an organization. + - organization_unhidden: the candidate lifted the hiding for an organization. + enum: + - publication_opened + - publication_changed + - publication_closed + - search_status_confirmed + - search_status_cleared + - organization_hidden + - organization_unhidden + PrivacyEvent: + type: object + description: One recorded change of the visibility settings of the current candidate, as evidence of what was published, hidden, or announced and when. The history is append-only and returns only the caller's own records. A publication event carries the published fields and the C2 record behind them; an organization event names the organization; the other properties are null. + additionalProperties: false + required: + - id + - kind + - occurred_at + - fields + - consent_id + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the event. + kind: + $ref: '#/components/schemas/PrivacyEventKind' + occurred_at: + $ref: '#/components/schemas/Timestamp' + fields: + description: Published fields after the change for `publication_opened` and `publication_changed`, an empty set for `publication_closed`, and null for every other kind. + oneOf: + - $ref: '#/components/schemas/CardFieldSet' + - type: 'null' + consent_id: + description: C2 record that backs the publication, for `publication_opened` and `publication_changed`, or null. + oneOf: + - type: string + format: uuid + - type: 'null' + organization: + description: Organization of `organization_hidden` and `organization_unhidden` with its current name, resolved when the history is read (the event stores only the identifier), or null. + oneOf: + - $ref: '#/components/schemas/PrivacyOrganization' + - type: 'null' + PrivacyEventList: + type: object + description: One page of the settings history of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Events of the page. + items: + $ref: '#/components/schemas/PrivacyEvent' + page: + $ref: '#/components/schemas/PageInfo' + CardAccessKind: + type: string + description: |- + How an organization reached the candidate. + + - card_viewed: an organization read the permitted anonymous card. + - contact_read: an organization read the contacts through the contact grant of an accepted invitation. + enum: + - card_viewed + - contact_read + CardAccess: + type: object + description: One access of an organization to the card or the contacts of the current candidate. A retained access permits the candidate to see the organization's identifier and current name and to hide their profile from it. `organization` is null when the organization cannot be presented. Earlier permitted accesses remain after hiding. The record carries no employee identity, query, ranking, or search filter of the organization. + additionalProperties: false + required: + - id + - kind + - occurred_at + - organization + properties: + id: + type: string + format: uuid + description: Identifier of the access record. + kind: + $ref: '#/components/schemas/CardAccessKind' + occurred_at: + $ref: '#/components/schemas/Timestamp' + organization: + oneOf: + - $ref: '#/components/schemas/PrivacyOrganization' + - type: 'null' + CardAccessList: + type: object + description: One page of the accesses to the card of the current candidate, newest first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Accesses of the page. + items: + $ref: '#/components/schemas/CardAccess' + page: + $ref: '#/components/schemas/PageInfo' + EvidenceKind: + type: string + description: |- + Whether a fact is a statement or an observation. + + - claim: something the candidate stated that nothing confirmed separately. Its trust is 0. + - measurement: a result that a system observed, such as a confirmed assessment. Its trust is 1 to 3. + + Assessments produce measurements only. A claim never becomes a measurement by repetition, and the two kinds are stored apart. + enum: + - claim + - measurement + EvidenceSourceType: + type: string + description: |- + Where the fact comes from. + + - assessment_result: a real (root or corrective) assessment result of this platform that confirmed a grade. An express training run (`demo_express`), a failed attempt, and a result without a reviewed category source are never a source. + + Adding a value is a contract change. + enum: + - assessment_result + EvidenceAttribution: + type: string + description: |- + Whose contribution the fact is. + + - personal: the candidate's own result. Every assessment fact is personal. + - team_role: a team result with a confirmed role of the candidate. + - team_unattributed: a team result without a confirmed role; it is not a personal skill. + + Only `personal` is produced today. + enum: + - personal + - team_role + - team_unattributed + EvidenceTrustLevel: + type: integer + format: int32 + minimum: 0 + maximum: 3 + description: |- + Strength of the confirmation. + + - 0: stated by the person, not confirmed separately. + - 1: an observable online result without a reliable confirmation of the identity or the authorship. Every assessment fact has this level today, because the assessment is unproctored and the identity is not confirmed. + - 2: a result tied to a confirmed identity or confirmed by an independent party. + - 3: an in-person check with a matching confirmation. + + A repeated statement, a sign-in, or a repeated tag of the same event never raises the level. + examples: + - 1 + EvidenceVisibility: + type: string + description: |- + Whether the fact may take part in what an organization reads. + + - visible: the fact is eligible for the organization projection. It does not publish the fact: the projection also needs the published card with the `categories` field and an active C2. + - hidden: the candidate hid the fact. No organization reads it. Hiding never edits or deletes the confirmed result. + enum: + - visible + - hidden + EvidenceSkillCode: + type: string + description: A skill tag from a closed set - the specialization codes of the catalog and the technology codes of the anonymous card. An assessment tags its fact with the specialization of the category. + enum: + - backend + - frontend + - mobile + - network_engineer + - devops_sre + - data_analyst + - ds_ml + - information_security + - qa + - go + - postgresql + - kafka + - docker + EvidenceBasis: + type: string + description: |- + What the measurement rests on. + + - synthetic_demo: a demonstration category from a synthetic reviewed bank. It shows the mechanics and is not a validated measurement. + enum: + - synthetic_demo + EvidenceCalibrationStatus: + type: string + description: |- + Calibration of the method behind the result. + + - uncalibrated: the thresholds are initial values that no measurement has validated. + enum: + - uncalibrated + EvidenceResult: + type: object + description: 'What the fact says: the grade that was passed and how reliable the method is. It carries no score, answer, item, failure, or anti-cheat data.' + additionalProperties: false + required: + - grade + - basis + - calibration_status + properties: + grade: + $ref: '#/components/schemas/GradeCode' + basis: + $ref: '#/components/schemas/EvidenceBasis' + calibration_status: + $ref: '#/components/schemas/EvidenceCalibrationStatus' + EvidenceSource: + type: object + description: Where the fact comes from. For an assessment the event is the attempt and the result is the immutable result of that attempt, which the candidate reads at `GetMyAssessmentResult`; the two identifiers are equal because a result is keyed by its attempt. + additionalProperties: false + required: + - type + - event_id + - result_id + properties: + type: + $ref: '#/components/schemas/EvidenceSourceType' + event_id: + type: string + format: uuid + description: Identifier of the source event. One event is one fact, however many skills it is tagged with. + result_id: + type: string + format: uuid + description: Identifier of the immutable result that produced the fact. + EvidenceFact: + type: object + description: One independent fact of the current candidate. `occurred_at` is when the source event ended; for an assessment it is the time of the decision. A fact is one source event; the skills of that event are tags of the fact, so a second tag never makes a second fact. Hidden facts are listed here with their visibility, because the candidate owns them. + additionalProperties: false + required: + - id + - kind + - source + - skills + - result + - attribution + - trust + - occurred_at + - visibility + properties: + id: + type: string + format: uuid + description: Identifier of the fact. + kind: + $ref: '#/components/schemas/EvidenceKind' + source: + $ref: '#/components/schemas/EvidenceSource' + skills: + type: array + minItems: 1 + maxItems: 13 + uniqueItems: true + description: Skill tags of the event in ascending order. + items: + $ref: '#/components/schemas/EvidenceSkillCode' + result: + $ref: '#/components/schemas/EvidenceResult' + attribution: + $ref: '#/components/schemas/EvidenceAttribution' + trust: + $ref: '#/components/schemas/EvidenceTrustLevel' + occurred_at: + $ref: '#/components/schemas/Timestamp' + visibility: + $ref: '#/components/schemas/EvidenceVisibility' + EvidenceFactList: + type: object + description: One page of the facts of the current candidate, newest event first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Facts of the page. + items: + $ref: '#/components/schemas/EvidenceFact' + page: + $ref: '#/components/schemas/PageInfo' + OrganizationEvidenceFact: + type: object + description: 'The one assessment fact that supports a category of the card as an organization reads it: the earliest visible measurement that passed exactly the confirmed grade of that category. A lower grade, a retake, the other tags of the event, the source, the basis, the exact time, and every identifier stay with the candidate. The fact carries no identifier of the fact, the event, the result, or the candidate, so it cannot be joined to a person by a key. It is not unlinkable: the skill, the grade, the trust level, and the year, together with the other values of the card, can narrow a small pool of candidates, and the minimum cohort of the card does not cover the year. `basis` and `calibration_status` are the same for every candidate: they say that the fact comes from a synthetic demonstration and is not calibrated, so a demonstration is never read as a validated measurement. The fact never carries an answer, score, item, failure, signal, or review band.' + additionalProperties: false + required: + - skill + - grade + - trust + - basis + - calibration_status + - observed_year + properties: + skill: + $ref: '#/components/schemas/EvidenceSkillCode' + grade: + $ref: '#/components/schemas/GradeCode' + trust: + $ref: '#/components/schemas/EvidenceTrustLevel' + basis: + $ref: '#/components/schemas/EvidenceBasis' + calibration_status: + $ref: '#/components/schemas/EvidenceCalibrationStatus' + observed_year: + type: integer + format: int32 + minimum: 2000 + maximum: 9999 + description: Year (UTC) when the assessment ended. The month, day, and time stay with the candidate. + examples: + - 2026 + OrganizationEvidence: + type: object + description: 'The permitted evidence of one candidate card, ordered by skill: at most one fact for each category of the card (at most nine). The list is empty when no visible fact supports a category of the card.' + additionalProperties: false + required: + - items + properties: + items: + type: array + maxItems: 9 + description: Permitted facts, one for each supported category. + items: + $ref: '#/components/schemas/OrganizationEvidenceFact' + NotificationKind: + type: string + description: |- + Which event put the notification into the inbox. The inbox stores a reference to the event, never its text. + + - invitation_delivered: an invitation reached the candidate's inbox. It does not depend on any email, and a failed or missing email never blocks it. The send of an invitation produces it through the outbox, so the notice appears shortly after the commit of the send, while the invitation itself is in ListMyInvitations from that commit. + - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility check, the list, and the read state). It has no product meaning, needs no action, and is never produced by a user action. + + Adding a value is a contract change; a client shows an unknown kind with the generic text of an item without content. + enum: + - invitation_delivered + - synthetic + NotificationContent: + type: object + description: The text of a notification as the current source shows it to the recipient now. It is computed on every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it from the next read. It holds no contact, no score, and no result of an assessment. + additionalProperties: false + required: + - title + - summary + - link_path + properties: + title: + type: string + minLength: 1 + maxLength: 120 + description: Short heading in Russian. + summary: + type: string + minLength: 1 + maxLength: 500 + description: One or two sentences in Russian. Plain text, never markup. + link_path: + type: + - string + - 'null' + maxLength: 256 + pattern: ^/[A-Za-z0-9/_-]{0,255}$ + description: Same-origin absolute path of the screen that the notification opens, or null when there is none. It has no origin, query, fragment, or escape; a client opens it only as a path of its own router. + examples: + - /candidate/invitations + Notification: + type: object + description: One item of the inbox of the current account. Its identity, kind, organization, delivery time, and read state are stored; its content is resolved from the current source on every read. + additionalProperties: false + required: + - id + - kind + - organization_id + - delivered_at + - read_at + - content + properties: + id: + type: string + format: uuid + description: Identifier of the item. It equals the identifier of the event that produced it, so a repeated delivery of the same event is the same item. + kind: + $ref: '#/components/schemas/NotificationKind' + organization_id: + type: string + format: uuid + description: 'The organization context of the item: the organization that sent it to a candidate, or the organization whose cabinet holds it for an employer. The identifier is not a right to read the organization.' + delivered_at: + $ref: '#/components/schemas/Timestamp' + read_at: + description: When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the first time. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + content: + description: The current content, or null when the source is gone or the recipient may not see it now. A client then shows a generic line such as "The content is no longer available" and never an old copy. The item stays in the list and can be marked read. + oneOf: + - $ref: '#/components/schemas/NotificationContent' + - type: 'null' + NotificationList: + type: object + description: One page of the inbox, newest delivery first. + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + description: Items of the page. + items: + $ref: '#/components/schemas/Notification' + page: + $ref: '#/components/schemas/PageInfo' + NotificationReadReceipt: + type: object + description: The read state of one item after a mark. It carries no content, so marking never reads the source. + additionalProperties: false + required: + - id + - read_at + properties: + id: + type: string + format: uuid + description: Identifier of the marked item. + read_at: + $ref: '#/components/schemas/Timestamp' + AssessmentLabNodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a lab node as the task statement uses it, such as `r1` or `srv`. It is a label of the task, not a host name or an address. + AssessmentLabNodeKind: + type: string + description: |- + What the console of a node shows. + + - mikrotik: a MikroTik router with the RouterOS console. + - ubuntu: a small Ubuntu server with a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + AssessmentLabNode: + type: object + description: A node of a lab by its task name and kind. It never carries an address, a MAC address, a port, a password, a key, or an infrastructure name. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/components/schemas/AssessmentLabNodeName' + kind: + $ref: '#/components/schemas/AssessmentLabNodeKind' + LabItemContent: + type: object + description: 'Practical lab: configure or repair a small network of virtual nodes through their consoles. The candidate starts the lab of the item with CreateMyAssessmentLab, works in the node consoles, and submits with SubmitMyAssessmentLab; the server then checks the state of the nodes. The content lists only the nodes the statement names and the lifetime of the lab, never the checker, its criteria, the seed, or an address. SubmitMyAssessmentAnswer takes no answer to a lab item; its result is submitted only with SubmitMyAssessmentLab.' + additionalProperties: false + required: + - format + - nodes + - time_limit_seconds + properties: + format: + type: string + enum: + - lab + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the lab in the order of the statement. + items: + $ref: '#/components/schemas/AssessmentLabNode' + time_limit_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of a lab of this item from its creation. The lab also ends no later than the attempt deadline. + LabAnswer: + type: object + description: 'Answer of a lab item: the state of the nodes of the named lab at the moment of submission. The server reads that state with the checker of the task; the body carries no configuration text, score, or correctness flag. Two answers are equal when they name the same lab. It is the answer of SubmitMyAssessmentLab only and is not a member of AssessmentAnswer.' + additionalProperties: false + required: + - format + - lab_id + properties: + format: + type: string + enum: + - lab + lab_id: + type: string + format: uuid + description: The lab of this item that the candidate worked in. + AssessmentLabState: + type: string + description: |- + State of a lab of an attempt item. + + - provisioning: the nodes are being prepared; poll GetMyAssessmentLab. + - ready: the consoles can be opened until `expires_at`. + - checking: the answer was accepted; the consoles are closed and the server checks the nodes. + - submitted: the check finished and the answer is recorded; the lab is deleted. The state never says whether the answer was correct. + - expired: the lifetime or the attempt deadline ended before a submission; the lab is deleted and the item cannot start another lab. + - failed: the lab infrastructure failed, independently of the candidate; `failure_reason` is `lab_error`. Nothing was recorded or consumed, and the candidate may start a new lab of the same item while the item is current. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - checking + - submitted + - expired + - failed + AssessmentLabFailureReason: + type: string + description: 'Why a lab failed: `lab_error` for an infrastructure failure, such as a node that did not boot or a check that could not reach a node. It never depends on the candidate and is never a failed check.' + enum: + - lab_error + AssessmentLab: + type: object + description: Candidate view of the lab of one attempt item. It contains no node address, MAC address, port, password, key, token, seed, checker state, criteria, score, or infrastructure name. + additionalProperties: false + required: + - id + - item_id + - state + - nodes + - created_at + - ready_at + - expires_at + - finished_at + - failure_reason + properties: + id: + type: string + format: uuid + description: Identifier of the lab. + item_id: + $ref: '#/components/schemas/AssessmentItemId' + state: + $ref: '#/components/schemas/AssessmentLabState' + nodes: + type: array + minItems: 1 + maxItems: 8 + items: + $ref: '#/components/schemas/AssessmentLabNode' + created_at: + $ref: '#/components/schemas/Timestamp' + ready_at: + description: Time the lab became `ready`, or null before. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + expires_at: + description: 'Time the lab ends unless it was submitted before: the earlier of the lifetime of the item and the attempt deadline. It never moves.' + $ref: '#/components/schemas/Timestamp' + finished_at: + description: Time the lab reached `submitted`, `expired`, or `failed`, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + failure_reason: + description: '`lab_error` when `state` is `failed`, otherwise null.' + oneOf: + - $ref: '#/components/schemas/AssessmentLabFailureReason' + - type: 'null' + AssessmentLabCreate: + type: object + description: Start the lab of the current lab item. Unknown fields are rejected. + additionalProperties: false + required: + - item_id + properties: + item_id: + $ref: '#/components/schemas/AssessmentItemId' + AssessmentLabConsoleSessionCreate: + type: object + description: Open a console of one node of a ready lab. Unknown fields are rejected. + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/components/schemas/AssessmentLabNodeName' + AssessmentLabConsoleSession: + type: object + description: A console session of one node. The client opens a WebSocket to `websocket_path` on the same origin before `expires_at`; the session cookie and the Origin check authorize the upgrade, so no secret travels in the path, the body, or a query string. A session can be attached once and ends with the lab. + additionalProperties: false + required: + - id + - node + - websocket_path + - expires_at + properties: + id: + type: string + format: uuid + description: Identifier of the console session; it is not a secret. + node: + $ref: '#/components/schemas/AssessmentLabNodeName' + websocket_path: + type: string + maxLength: 128 + pattern: ^/api/v1/me/assessment-lab-consoles/[0-9a-f-]{36}$ + description: Same-origin path of the console WebSocket. + expires_at: + description: Time by which the WebSocket must be opened. + $ref: '#/components/schemas/Timestamp' + AssessmentLabSubmission: + type: object + description: Submit the lab of the current lab item as its answer. Unknown fields are rejected, so a request cannot send a score or a correctness flag. + additionalProperties: false + required: + - expected_version + - answer + properties: + expected_version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + answer: + $ref: '#/components/schemas/LabAnswer' HealthResponse: type: object additionalProperties: false @@ -31,3 +11048,7180 @@ components: type: string enum: - ok + VerificationCode: + type: string + minLength: 6 + maxLength: 6 + pattern: ^[0-9]{6}$ + description: Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code. + EmailVerificationCodeRequest: + type: object + description: Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest. + additionalProperties: false + required: + - email + - code + - password + properties: + email: + $ref: '#/components/schemas/EmailAddress' + code: + $ref: '#/components/schemas/VerificationCode' + password: + type: string + minLength: 1 + maxLength: 128 + description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. + ProfileProjectTitle: + type: string + minLength: 1 + maxLength: 100 + pattern: ^\S(?:.*\S)?$ + description: Name of a project as the candidate wants an organization to read it. It has no leading or trailing whitespace and no line breaks. When the candidate publishes the `projects` card field, the title reaches the anonymous card and match explanations, so it must not contain a name, a contact, or a repository address. Plain text; clients show it as text, never as HTML. + ProfileProjectDescription: + type: string + minLength: 1 + maxLength: 500 + description: What the project does and what the candidate did in it. It may contain line breaks. When the `projects` card field is published it reaches the anonymous card. Plain text; clients show it as text, never as HTML. + ProfileProjectStack: + type: array + maxItems: 10 + description: Technology tags of the project, each tag at most once without regard to letter case. + items: + $ref: '#/components/schemas/StackTag' + ProfileRepositoryUrl: + type: string + minLength: 22 + maxLength: 160 + pattern: ^https://github\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$ + description: Address of a public GitHub repository of the project in the form https://github.com//. The server accepts only this host and form, removes a trailing slash and a `.git` suffix, and stores the canonical address. Organizations never receive the address before an accepted invitation, because the owner name can identify the candidate. + examples: + - https://github.com/example-org/payments-ledger + ProfileRepositoryCheckState: + type: string + description: |- + Result of the latest server check of a project repository on the public GitHub API. The server only reads public metadata; a check never proves that the candidate wrote the code. + + - pending: the check is scheduled and has not finished yet. + - verified: the repository exists and is public. Match explanations may then say that the project is backed by a public repository. + - not_found: GitHub reports no such public repository; it may be private, renamed to another owner, or deleted. + - unavailable: GitHub could not be asked, for example because of its rate limit; the server retries later. + enum: + - pending + - verified + - not_found + - unavailable + ProfileRepositoryCheck: + type: object + description: State of the server check of a project repository. Read-only; no request writes it. The fetched metadata itself (description, topics, languages, and a plain-text README excerpt) is used only for ranking and is never returned or shown. + additionalProperties: false + required: + - state + - checked_at + properties: + state: + $ref: '#/components/schemas/ProfileRepositoryCheckState' + checked_at: + description: Time of the last finished check, or null before the first one. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + ProfileProjectItem: + type: object + description: One project of the candidate with its confirmation state and provenance. A project is a claim of trust level 0 that the candidate types; a linked repository adds a separate server check (`repository_check`), never a higher trust level. The project reaches organizations only when the candidate publishes the `projects` card field, and then without the repository address. + additionalProperties: false + required: + - title + - description + - stack + - repository_url + - repository_check + - status + - source + properties: + title: + $ref: '#/components/schemas/ProfileProjectTitle' + description: + description: What the project is about, or null when the candidate gives nothing. + oneOf: + - $ref: '#/components/schemas/ProfileProjectDescription' + - type: 'null' + stack: + $ref: '#/components/schemas/ProfileProjectStack' + repository_url: + description: Canonical repository address, or null when the project links none. + oneOf: + - $ref: '#/components/schemas/ProfileRepositoryUrl' + - type: 'null' + repository_check: + description: The server check of the linked repository, or null when the project links none. + oneOf: + - $ref: '#/components/schemas/ProfileRepositoryCheck' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + source: + $ref: '#/components/schemas/ProfileClaimSource' + ProfileProjectItemInput: + type: object + description: Decision about one project in a request; see CandidateProfileUpdate for the rules of `status`. The server answers 400 with the pointer of the field for a repository address that is not a GitHub repository address, a repeated repository, or a repeated stack tag. + additionalProperties: false + required: + - title + - description + - stack + - repository_url + - status + properties: + title: + $ref: '#/components/schemas/ProfileProjectTitle' + description: + oneOf: + - $ref: '#/components/schemas/ProfileProjectDescription' + - type: 'null' + stack: + $ref: '#/components/schemas/ProfileProjectStack' + repository_url: + oneOf: + - $ref: '#/components/schemas/ProfileRepositoryUrl' + - type: 'null' + status: + $ref: '#/components/schemas/ProfileItemStatus' + ProfileRepositoryCheckRequest: + type: object + description: Result of a request to check the linked repositories again. + additionalProperties: false + required: + - scheduled + properties: + scheduled: + type: integer + format: int32 + minimum: 0 + maximum: 10 + description: Number of repository checks that the request scheduled. + AssessmentRealMode: + type: string + description: Server-selected mode available to a real category assessment. + enum: + - demo_basic + - adaptive + AssessmentRealResultCommon: + type: object + description: Immutable result of a real assessment, visible only to its candidate. It records the method, versions, decision, uncertainty, and limitations. A corrective result also carries root_attempt_id and chain_deadline from the same chain. Later policy, bank, or algorithm versions never change it. It never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. Fields the method does not compute are null, never zero. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + description: Root attempt of a corrective check, or null when this is not a corrective result. The corrective attempt keeps this link. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Immutable deadline shared by a corrective chain, or null when this result is not from a corrective check. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + readOnly: true + task_language: + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + kind: + type: string + enum: + - root + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + versions: + $ref: '#/components/schemas/AssessmentVersions' + outcome: + $ref: '#/components/schemas/AssessmentOutcome' + not_determined_reason: + description: The reason when `outcome` is `not_determined`, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentNotDeterminedReason' + - type: 'null' + confirmed_grade: + description: Grade that this attempt confirmed, the target grade, or null when it confirmed none. Together with the specialization it forms the category. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + previous_confirmed_grade: + description: Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed nothing, this grade stays in force. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + category_decision: + $ref: '#/components/schemas/AssessmentCategoryDecisionView' + strength: + description: Strength of an adaptive confirmation, otherwise null. + oneOf: + - $ref: '#/components/schemas/AssessmentStrength' + - type: 'null' + calibration_status: + $ref: '#/components/schemas/CalibrationStatus' + limitations: + type: array + maxItems: 10 + uniqueItems: true + items: + $ref: '#/components/schemas/AssessmentLimitation' + uncertainty: + description: Ability estimate and uncertainty of an adaptive attempt with a decision; null for demo_basic, which computes none, and for an attempt without a decision. + oneOf: + - $ref: '#/components/schemas/AssessmentUncertainty' + - type: 'null' + basic_score: + description: Raw score of a demo_basic attempt with a decision, otherwise null. + oneOf: + - $ref: '#/components/schemas/BasicScore' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Verdicts of the practices that have one, main first. + items: + $ref: '#/components/schemas/AssessmentPracticeResult' + gaps: + type: array + maxItems: 20 + description: Domains with weak evidence; empty when none were found or the method finds none. + items: + $ref: '#/components/schemas/AssessmentGap' + durations: + $ref: '#/components/schemas/AssessmentDurations' + next_steps: + type: array + maxItems: 5 + items: + $ref: '#/components/schemas/AssessmentNextStep' + decided_at: + $ref: '#/components/schemas/Timestamp' + AssessmentQualifiedResult: + description: Result of a real assessment that is not a corrective attempt. The correction-chain fields are explicitly null. + allOf: + - $ref: '#/components/schemas/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - root + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentCorrectiveResult: + description: Result of a corrective real assessment. Both chain fields are present and identify the same immutable correction chain. + allOf: + - $ref: '#/components/schemas/AssessmentRealResultCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/components/schemas/Timestamp' + readOnly: true + required: + - kind + - root_attempt_id + - chain_deadline + AssessmentSignalNoticeVersion: + type: integer + format: int32 + minimum: 1 + maximum: 2147483647 + description: Version of the notice text about the collected signals. The client shows the text of the version it knows and sends that version back when the candidate confirms; a changed text gets a new version and needs a new confirmation. + AssessmentSignalNotice: + type: object + description: State of the notice about the signals that are collected during a real assessment attempt. The acknowledgement is a record that the candidate was informed. It is not a consent, grants no purpose, and neither enables nor blocks signal storage; C3 remains the only consent that the signal operation checks. + additionalProperties: false + required: + - notice_version + - acknowledged + - acknowledged_at + properties: + notice_version: + allOf: + - $ref: '#/components/schemas/AssessmentSignalNoticeVersion' + description: The version the server currently requires the candidate to acknowledge. + acknowledged: + type: boolean + description: True when the candidate acknowledged `notice_version`. + acknowledged_at: + description: Server time of the first acknowledgement of this version, or null. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + AssessmentSignalNoticeAcknowledgement: + type: object + description: The notice version the candidate was shown and acknowledged. + additionalProperties: false + required: + - notice_version + properties: + notice_version: + $ref: '#/components/schemas/AssessmentSignalNoticeVersion' + AssessmentQualifiedAttemptCreate: + type: object + description: Start a real assessment for a specialization and target grade, with the task language. The candidate comes from the session. The server chooses demo_basic or adaptive and fixes the policy, bank, and algorithm versions. Unknown fields such as `mode`, `seed`, or `score` are rejected. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + properties: + kind: + type: string + enum: + - root + description: Start a real-assessment chain and reserve one root quota slot. + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + description: Task language of the attempt, one of the `task_languages` of the published bank, or null when the bank offers no choice of language. The questionnaire choice is the value the client offers first. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + AssessmentCorrectiveAttemptCreate: + type: object + description: Start a corrective real assessment at a lower target grade in the chain rooted at root_attempt_id. The server validates that this grade is strictly below the preceding grade and that the chain remains within its existing deadline and quota. chain_deadline is derived from the root attempt and is never supplied by the client. + additionalProperties: false + required: + - kind + - specialization + - target_grade + - task_language + - root_attempt_id + properties: + kind: + type: string + enum: + - corrective + description: Continue the existing real-assessment chain without reserving another root slot. + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + task_language: + description: Task language of the attempt, or null when the bank offers no choice. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + root_attempt_id: + type: string + format: uuid + description: Root real-assessment attempt whose quota and deadline this attempt shares. + AssessmentExpressAttemptCreate: + type: object + description: Explicitly start the short training run. It has no specialization or target grade, uses its separate demo policy, and does not consume a real-assessment attempt. + additionalProperties: false + required: + - kind + properties: + kind: + type: string + enum: + - demo_express + description: Explicitly request the training run; real modes cannot be selected by the client. + AssessmentAttemptKind: + type: string + description: Assessment track that distinguishes root, corrective, and training attempts. + enum: + - root + - corrective + - demo_express + AssessmentWatermark: + type: object + description: 'Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.' + additionalProperties: false + required: + - code + properties: + code: + type: string + minLength: 10 + maxLength: 11 + pattern: ^[0-9A-HJKMNP-TV-Z]{5}-?[0-9A-HJKMNP-TV-Z]{5}$ + description: Two groups of five symbols of Crockford base32, such as `7K3QD-9XM2T`. + AssessmentAttemptCommon: + type: object + description: Common state of an assessment attempt. Real assessments have a specialization and target grade; demo_express has neither. The attempt shows its fixed versions, server deadlines, session limit, progress, current item, and practices. It never contains answer keys, answer correctness, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + additionalProperties: false + required: + - id + - version + - specialization + - target_grade + - task_language + - kind + - mode + - state + - versions + - started_at + - expires_at + - sessions + - finished_at + - progress + - current_item + - practices + properties: + id: + type: string + format: uuid + description: Attempt identifier. + version: + $ref: '#/components/schemas/AssessmentAttemptVersion' + specialization: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/components/schemas/SpecializationCode' + - type: 'null' + target_grade: + description: Null only for demo_express, which has no qualification category. + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + task_language: + description: Task language of the attempt, or null when none is selected. + oneOf: + - $ref: '#/components/schemas/TaskLanguage' + - type: 'null' + kind: + $ref: '#/components/schemas/AssessmentAttemptKind' + root_attempt_id: + description: Present only for a corrective real assessment. It identifies the root attempt whose quota and chain deadline this attempt shares. + oneOf: + - type: string + format: uuid + - type: 'null' + readOnly: true + chain_deadline: + description: Present only for a corrective real assessment. It is the immutable deadline derived from the root attempt and is not extended by a lower target grade. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + readOnly: true + mode: + $ref: '#/components/schemas/AssessmentMode' + state: + $ref: '#/components/schemas/AssessmentAttemptState' + versions: + $ref: '#/components/schemas/AssessmentVersions' + started_at: + $ref: '#/components/schemas/Timestamp' + expires_at: + description: Server deadline. For demo_express it is 180 to 300 seconds after started_at; for a corrective assessment it does not exceed chain_deadline. + $ref: '#/components/schemas/Timestamp' + sessions: + description: Session limit of the attempt, or null when its policy defines none. + oneOf: + - $ref: '#/components/schemas/AssessmentSessions' + - type: 'null' + finished_at: + description: Time the attempt reached a terminal state, or null while it is active. + oneOf: + - $ref: '#/components/schemas/Timestamp' + - type: 'null' + progress: + $ref: '#/components/schemas/AssessmentProgress' + current_item: + description: 'Item to answer now: a test item in `in_progress`, the practice item to submit in `practice_pending` or `additional_practice_pending` while that practice is `not_started` or `failed`, and null otherwise.' + oneOf: + - $ref: '#/components/schemas/AssessmentItem' + - type: 'null' + practices: + type: array + maxItems: 5 + description: Practices in the order assigned by the mode policy. The list exposes verdicts only after submission. + items: + $ref: '#/components/schemas/AssessmentPractice' + watermark: + $ref: '#/components/schemas/AssessmentWatermark' + AssessmentQualifiedAttempt: + allOf: + - $ref: '#/components/schemas/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - root + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + type: 'null' + description: Root attempts have no parent attempt. + chain_deadline: + type: 'null' + description: A root attempt has no correction-chain deadline. + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentCorrectiveAttempt: + allOf: + - $ref: '#/components/schemas/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - corrective + mode: + type: string + enum: + - demo_basic + - adaptive + specialization: + $ref: '#/components/schemas/SpecializationCode' + target_grade: + $ref: '#/components/schemas/GradeCode' + root_attempt_id: + type: string + format: uuid + readOnly: true + chain_deadline: + $ref: '#/components/schemas/Timestamp' + readOnly: true + required: + - kind + - mode + - specialization + - target_grade + - root_attempt_id + - chain_deadline + AssessmentExpressAttempt: + allOf: + - $ref: '#/components/schemas/AssessmentAttemptCommon' + - type: object + properties: + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + specialization: + type: 'null' + target_grade: + type: 'null' + task_language: + type: 'null' + root_attempt_id: + type: 'null' + chain_deadline: + type: 'null' + required: + - kind + - mode + - specialization + - target_grade + - task_language + - root_attempt_id + - chain_deadline + AssessmentCaptureSignal: + type: object + description: 'A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.' + additionalProperties: false + required: + - kind + - item_instance_id + - occurred_at + properties: + kind: + type: string + enum: + - screenshot_key + - devtools_open + item_instance_id: + $ref: '#/components/schemas/AssessmentItemId' + occurred_at: + $ref: '#/components/schemas/Timestamp' + AssessmentWorkSession: + type: object + description: The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for the attempt, not a score or a signal, and it changes no result. + additionalProperties: false + required: + - held_until + - renew_after_seconds + properties: + held_until: + $ref: '#/components/schemas/Timestamp' + renew_after_seconds: + type: integer + format: int32 + minimum: 1 + maximum: 3600 + description: How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed down in the background still renews before its hold expires. + AssessmentFinalizeConflictProblem: + type: object + description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + title: + type: string + minLength: 1 + maxLength: 200 + status: + type: integer + format: int32 + const: 409 + code: + type: string + enum: + - state_conflict + - idempotency_in_progress + detail: + type: string + maxLength: 1000 + instance: + type: string + format: uri-reference + maxLength: 2048 + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + errors: + type: array + maxItems: 100 + items: + $ref: '#/components/schemas/ProblemFieldError' + pending_item_ids: + type: array + maxItems: 220 + uniqueItems: true + items: + type: string + format: uuid + description: Frozen item IDs still unanswered when finalize is rejected for an incomplete attempt. Omitted when the conflict is unrelated to unanswered items. + AssessmentExpressResult: + type: object + description: Immutable educational result of a demo_express run. It includes a short summary but cannot report a category, percentile, uncertainty, grade, strength, or qualification evidence. The result belongs only to the training mode and does not consume a real-assessment quota. + additionalProperties: false + required: + - attempt_id + - specialization + - target_grade + - task_language + - kind + - mode + - versions + - outcome + - not_determined_reason + - confirmed_grade + - previous_confirmed_grade + - strength + - calibration_status + - limitations + - uncertainty + - basic_score + - practices + - gaps + - durations + - next_steps + - summary + - decided_at + properties: + attempt_id: + type: string + format: uuid + specialization: + type: 'null' + description: Express training does not assess a specialization. + target_grade: + type: 'null' + description: Express training does not assess a target grade. + task_language: + type: 'null' + kind: + type: string + enum: + - demo_express + mode: + type: string + enum: + - demo_express + versions: + $ref: '#/components/schemas/AssessmentVersions' + outcome: + type: string + enum: + - demonstration + not_determined_reason: + type: 'null' + confirmed_grade: + type: 'null' + description: Express training never confirms a grade. + previous_confirmed_grade: + type: 'null' + strength: + type: 'null' + calibration_status: + type: string + enum: + - uncalibrated + limitations: + type: array + minItems: 1 + maxItems: 1 + items: + type: string + enum: + - demonstration_only + uncertainty: + type: 'null' + description: Express training computes no ability estimate or percentile. + basic_score: + type: 'null' + practices: + type: array + maxItems: 0 + items: + $ref: '#/components/schemas/AssessmentPracticeResult' + gaps: + type: array + maxItems: 0 + items: + $ref: '#/components/schemas/AssessmentGap' + durations: + $ref: '#/components/schemas/AssessmentDurations' + next_steps: + type: array + maxItems: 0 + items: + $ref: '#/components/schemas/AssessmentNextStep' + summary: + type: string + minLength: 1 + maxLength: 2000 + description: Short educational feedback about this training run. + decided_at: + $ref: '#/components/schemas/Timestamp' + MatchGradeFilter: + type: object + description: A confirmed category filter, never a candidate declaration. + additionalProperties: false + required: + - specialization + - grade + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + MatchConfirmationStatus: + type: string + description: Confirmation state for this specialization only. A result for one specialization never changes the state of another specialization. + enum: + - confirmed + - unconfirmed + MatchSearchStackTag: + type: string + description: A stack code that the anonymous card may expose. Search filters do not accept arbitrary profile text or candidate-provided evidence. + enum: + - go + - postgresql + - kafka + - docker + CandidateSalaryCompatibility: + type: string + description: A coarse compatibility result only. No salary amount, minimum, range, or threshold is part of the anonymous card. + enum: + - compatible + - not_compatible + MatchSearchConditions: + type: object + description: Filters against safe, coarse card conditions. No candidate location, salary amount, salary minimum, or salary range is accepted. + additionalProperties: false + properties: + work_formats: + type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + salary_compatibility: + $ref: '#/components/schemas/CandidateSalaryCompatibility' + MatchSearchFilters: + type: object + description: Optional filters over the current organization-visible bank. An empty object means no additional filter. Confirmed and declared grades are separate fields; a declaration never satisfies a confirmed-grade or category filter. Conditions use only the safe, coarse card fields. + additionalProperties: false + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmed_grade: + description: Match only candidates with this currently confirmed grade in the selected specialization. It never matches a declared grade. + $ref: '#/components/schemas/GradeCode' + confirmed_category: + $ref: '#/components/schemas/MatchGradeFilter' + confirmation_status: + $ref: '#/components/schemas/MatchConfirmationStatus' + declared_grade: + description: Candidate-declared grade filter. This is a separate claim and cannot satisfy `confirmed_grade` or `confirmed_category`. + $ref: '#/components/schemas/GradeCode' + stack: + type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + items: + $ref: '#/components/schemas/MatchSearchStackTag' + conditions: + $ref: '#/components/schemas/MatchSearchConditions' + MatchSearchByNeed: + type: object + description: Search one immutable set of confirmed requirements. `requirements_version` is the Need.requirements_version, not the general Need.version; text-only or suggestion-only edits do not change this search basis. + additionalProperties: false + required: + - need_id + - requirements_version + properties: + need_id: + type: string + format: uuid + description: Need owned by the organization in the path. + requirements_version: + $ref: '#/components/schemas/NeedVersion' + filters: + $ref: '#/components/schemas/MatchSearchFilters' + MatchSearchByBank: + type: object + description: Search the current organization-visible bank. An empty `filters` object includes all otherwise eligible specializations as separate entries. + additionalProperties: false + required: + - filters + properties: + filters: + $ref: '#/components/schemas/MatchSearchFilters' + MatchSearchRequest: + oneOf: + - $ref: '#/components/schemas/MatchSearchByNeed' + - $ref: '#/components/schemas/MatchSearchByBank' + description: Search either a Need.requirements_version snapshot or the whole organization-visible bank with explicit filters. Unknown fields are rejected by both closed request variants. + MatchSearchNeedSource: + type: object + description: The immutable need requirements snapshot used by this result. + additionalProperties: false + required: + - kind + - need_id + - requirements_version + properties: + kind: + type: string + enum: + - need + need_id: + type: string + format: uuid + requirements_version: + $ref: '#/components/schemas/NeedVersion' + MatchAppliedConditions: + type: object + description: Conditions echoed as a complete snapshot; null means no filter. + additionalProperties: false + required: + - work_formats + - salary_compatibility + properties: + work_formats: + oneOf: + - type: array + minItems: 1 + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + - type: 'null' + salary_compatibility: + oneOf: + - $ref: '#/components/schemas/CandidateSalaryCompatibility' + - type: 'null' + MatchAppliedFilters: + type: object + description: A normalized response snapshot of the bank filters. Each key is present; null means the corresponding request filter was omitted. This keeps a search result tied to its exact filter basis. + additionalProperties: false + required: + - specialization + - confirmed_grade + - confirmed_category + - confirmation_status + - declared_grade + - stack + - conditions + properties: + specialization: + oneOf: + - $ref: '#/components/schemas/SpecializationCode' + - type: 'null' + confirmed_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + confirmed_category: + oneOf: + - $ref: '#/components/schemas/MatchGradeFilter' + - type: 'null' + confirmation_status: + oneOf: + - $ref: '#/components/schemas/MatchConfirmationStatus' + - type: 'null' + declared_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + stack: + oneOf: + - type: array + minItems: 1 + maxItems: 4 + uniqueItems: true + items: + $ref: '#/components/schemas/MatchSearchStackTag' + - type: 'null' + conditions: + oneOf: + - $ref: '#/components/schemas/MatchAppliedConditions' + - type: 'null' + MatchSearchBankSource: + type: object + description: The normalized filters used for a bank search. + additionalProperties: false + required: + - kind + - filters + properties: + kind: + type: string + enum: + - bank + filters: + $ref: '#/components/schemas/MatchAppliedFilters' + MatchSearchSource: + oneOf: + - $ref: '#/components/schemas/MatchSearchNeedSource' + - $ref: '#/components/schemas/MatchSearchBankSource' + description: Search basis echoed with the response so the displayed result remains tied to its need requirements version or bank filters. + MatchCategory: + type: object + description: A confirmed category. Its specialization must equal the enclosing match entry's specialization. `basis` says what the grade rests on; `synthetic_demo` marks a demonstration category, which an organization must read as one and never as a standard confirmation. + additionalProperties: false + required: + - specialization + - grade + - basis + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + grade: + $ref: '#/components/schemas/GradeCode' + basis: + $ref: '#/components/schemas/EvidenceBasis' + MatchStrength: + type: string + description: Coarse strength of a confirmed assessment for this specialization. + enum: + - standard + - strong + MatchPublicStack: + type: array + maxItems: 4 + uniqueItems: true + items: + $ref: '#/components/schemas/MatchSearchStackTag' + CandidateExperienceBand: + type: string + description: Coarse total experience bucket. Rare combinations may be generalized to 0_3 or 3_plus before they are returned. + enum: + - '0_1' + - '1_3' + - '3_6' + - 6_plus + - '0_3' + - 3_plus + MatchPublicContext: + type: object + description: Safe anonymous-card context only. A null value means that the value is not in the public card or is not present; the response does not reveal which. It contains no contact, candidate location, or salary amount. + additionalProperties: false + required: + - stack + - experience_band + - work_formats + - salary_compatibility + properties: + stack: + oneOf: + - $ref: '#/components/schemas/MatchPublicStack' + - type: 'null' + experience_band: + oneOf: + - $ref: '#/components/schemas/CandidateExperienceBand' + - type: 'null' + work_formats: + oneOf: + - type: array + maxItems: 3 + uniqueItems: true + items: + $ref: '#/components/schemas/WorkFormat' + - type: 'null' + salary_compatibility: + oneOf: + - $ref: '#/components/schemas/CandidateSalaryCompatibility' + - type: 'null' + MatchEvidenceCode: + type: string + description: Template code for an explanation derived from allowed evidence. It carries no free text, raw answer, or reason for withheld FSP data. + enum: + - confirmed_category + - required_skill_evidence + - desired_skill_evidence + - domain_alignment + - task_alignment + - work_conditions_match + - salary_compatibility + - declared_grade + MatchEvidenceState: + type: string + enum: + - supports + - partial + - gap + - declared_only + MatchEvidenceSummaryItem: + type: object + description: A templated, non-text evidence explanation. + additionalProperties: false + required: + - code + - state + properties: + code: + $ref: '#/components/schemas/MatchEvidenceCode' + state: + $ref: '#/components/schemas/MatchEvidenceState' + MatchEvidenceSummary: + type: array + maxItems: 12 + items: + $ref: '#/components/schemas/MatchEvidenceSummaryItem' + MatchRequirementKind: + type: string + description: Kind of the need requirement that an explanation item answers. + enum: + - required_skill + - desired_skill + - task + MatchSemanticItemKind: + type: string + description: |- + Kind of the published card item that matched a requirement. + + - project: one published project; `project_title` names it. + - stack: the recognized technology codes of the card. + - roles: the specializations and grades that the card shows. + enum: + - project + - stack + - roles + MatchSimilarityBand: + type: string + description: Coarse band of the cosine similarity between the requirement and the matched item under the versioned policy thresholds. `high` and `medium` are the only values; a weaker similarity produces no item. The band is a computed similarity of two texts, not a judgement of the candidate. + enum: + - high + - medium + MatchSemanticEvidence: + type: object + description: 'Why the entry is in the result: one confirmed requirement of the need and the published card item with the highest semantic similarity to it. The server computes it from stored vectors and the versioned thresholds; no model writes text into it. `requirement_text` is the confirmed text of the organization''s own need. `project_title` is the title the candidate published with the `projects` card field and is null for other kinds. No repository address, owner, or fetched repository text is ever part of it.' + additionalProperties: false + required: + - requirement_kind + - requirement_text + - item_kind + - project_title + - repository_verified + - similarity + properties: + requirement_kind: + $ref: '#/components/schemas/MatchRequirementKind' + requirement_text: + type: string + minLength: 1 + maxLength: 300 + description: Confirmed skill name or task text of the need. Plain text; show it as text, never as HTML. + item_kind: + $ref: '#/components/schemas/MatchSemanticItemKind' + project_title: + description: Published project title for `project`, otherwise null. Plain text; show it as text, never as HTML. + oneOf: + - type: string + minLength: 1 + maxLength: 100 + - type: 'null' + repository_verified: + type: boolean + description: True only for a project whose linked repository the latest server check found public on GitHub ("backed by a public repository"). It does not prove authorship. + similarity: + $ref: '#/components/schemas/MatchSimilarityBand' + MatchSemanticEvidenceList: + type: array + description: 'Semantic explanation items in a stable order: `high` before `medium`, then by similarity, then by the order of the requirements in the need. At most the versioned per-entry limit is returned. It is empty for a bank search, while vectors are not ready, when ML is unavailable, and when no requirement reaches a band; `unknown_flags` names `ml_unavailable` when the semantic component itself is unknown.' + maxItems: 12 + items: + $ref: '#/components/schemas/MatchSemanticEvidence' + MatchScore: + type: number + format: double + minimum: 0 + maximum: 1 + description: A normalized FR09 ranking component from 0 to 1. + MatchNullableScore: + description: A score from a versioned ranking component, or null when it is not available. Any null component has a matching bounded entry in `unknown_flags`. + oneOf: + - type: number + format: double + minimum: 0 + maximum: 1 + - type: 'null' + MatchConfirmedComponents: + type: object + description: Components from the FR09 ranking model for a confirmed category. `percentile` is null when fewer than 30 comparable real candidates are available; the ranking uses neutral T = 0.5 and does not publish a percentile. If ML is unavailable, `semantics` uses neutral 0.5 and the reason appears in `unknown_flags`. + additionalProperties: false + required: + - fit + - coverage + - domain + - semantics + - percentile + - competition + - freshness + - responsiveness + - rank_score + properties: + fit: + $ref: '#/components/schemas/MatchScore' + coverage: + $ref: '#/components/schemas/MatchScore' + domain: + $ref: '#/components/schemas/MatchScore' + semantics: + $ref: '#/components/schemas/MatchScore' + percentile: + $ref: '#/components/schemas/MatchNullableScore' + competition: + $ref: '#/components/schemas/MatchScore' + freshness: + $ref: '#/components/schemas/MatchScore' + responsiveness: + $ref: '#/components/schemas/MatchScore' + rank_score: + $ref: '#/components/schemas/MatchScore' + MatchUnknownComponent: + type: string + description: Ranking or public-card component whose value is unknown. + enum: + - semantics + - percentile + - assessment + - freshness + - responsiveness + - experience_band + - work_formats + - salary_compatibility + - domain + MatchUnknownReason: + type: string + description: Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported only while the comparable real cohort of the category is smaller than the versioned minimum; once the cohort reaches the minimum but the percentile is still not computed, the reason is `percentile_not_computed`. In both cases T is the neutral 0.5. + enum: + - ml_unavailable + - cohort_below_30 + - no_confirmation_for_specialization + - not_in_public_card + - need_field_unconfirmed + - no_freshness_history + - no_response_history + - percentile_not_computed + MatchUnknownFlag: + type: object + description: A safe, bounded explanation for one unavailable component. + additionalProperties: false + required: + - component + - reason + properties: + component: + $ref: '#/components/schemas/MatchUnknownComponent' + reason: + $ref: '#/components/schemas/MatchUnknownReason' + MatchUnknownFlags: + type: array + maxItems: 9 + items: + $ref: '#/components/schemas/MatchUnknownFlag' + MatchConfirmedCandidate: + type: object + description: One confirmed specialization entry in the `main` or `near` group. The group containing it supplies the group label. A candidate may have a separate entry for another specialization. + additionalProperties: false + required: + - candidate_handle + - specialization + - confirmation_status + - declared_grade + - category + - strength + - public_context + - evidence_summary + - semantic_evidence + - components + - unknown_flags + properties: + candidate_handle: + $ref: '#/components/schemas/CandidateHandle' + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmation_status: + type: string + enum: + - confirmed + declared_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + description: Candidate-declared grade for this specialization, never a confirmation. + category: + $ref: '#/components/schemas/MatchCategory' + strength: + $ref: '#/components/schemas/MatchStrength' + public_context: + $ref: '#/components/schemas/MatchPublicContext' + evidence_summary: + $ref: '#/components/schemas/MatchEvidenceSummary' + semantic_evidence: + $ref: '#/components/schemas/MatchSemanticEvidenceList' + components: + $ref: '#/components/schemas/MatchConfirmedComponents' + unknown_flags: + $ref: '#/components/schemas/MatchUnknownFlags' + MatchUnconfirmedComponents: + type: object + description: Unconfirmed entries are ordered only by Fit and coverage. This strict component object has no theta, T, P, test percentile, or confirmed assessment score. + additionalProperties: false + required: + - fit + - coverage + properties: + fit: + type: number + format: double + minimum: 0 + maximum: 1 + description: Job fit for this specialization, never an assessment score. + coverage: + type: number + format: double + minimum: 0 + maximum: 1 + description: Coverage of confirmed need skills by allowed public evidence. + MatchUnconfirmedCandidate: + type: object + description: One specialization with no confirmed category. `category` and `strength` remain present and null. A confirmation in another specialization never changes this entry. The schema intentionally has no assessment measurement fields. + additionalProperties: false + required: + - candidate_handle + - specialization + - confirmation_status + - declared_grade + - category + - strength + - public_context + - evidence_summary + - semantic_evidence + - components + - unknown_flags + properties: + candidate_handle: + $ref: '#/components/schemas/CandidateHandle' + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmation_status: + type: string + enum: + - unconfirmed + declared_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + description: Candidate-declared grade, separate from assessment confirmation. + category: + type: 'null' + description: There is no confirmed category for this specialization. + strength: + type: 'null' + description: Assessment strength is not measured for this specialization. + public_context: + $ref: '#/components/schemas/MatchPublicContext' + evidence_summary: + $ref: '#/components/schemas/MatchEvidenceSummary' + semantic_evidence: + $ref: '#/components/schemas/MatchSemanticEvidenceList' + components: + $ref: '#/components/schemas/MatchUnconfirmedComponents' + unknown_flags: + $ref: '#/components/schemas/MatchUnknownFlags' + MatchSearchGroups: + type: object + description: Separate ranking groups. Confirmed categories appear in main and near; unconfirmed specializations appear only in the lower unconfirmed group. + additionalProperties: false + required: + - main + - near + - unconfirmed + properties: + main: + type: array + items: + $ref: '#/components/schemas/MatchConfirmedCandidate' + near: + type: array + items: + $ref: '#/components/schemas/MatchConfirmedCandidate' + unconfirmed: + type: array + items: + $ref: '#/components/schemas/MatchUnconfirmedCandidate' + MatchSearchResponse: + type: object + description: Anonymous search result grouped by specialization state. Repeated organization-scoped handles are allowed when the same candidate has different specialization entries; entries never transfer confirmation between specializations. + additionalProperties: false + required: + - source + - groups + - truncated + properties: + source: + $ref: '#/components/schemas/MatchSearchSource' + groups: + $ref: '#/components/schemas/MatchSearchGroups' + truncated: + type: boolean + description: 'True when the groups are not the whole ranked result: a group exceeded the versioned per-group limit, or the organization''s card-view allowance ended while the entries were being revealed. The entries returned are in rank order and already counted as card views. It carries no total, so it does not reveal how many candidates match.' + CardSelfAssessment: + type: object + description: Candidate-declared specialization and optional grade. This is never an assessment result. + additionalProperties: false + required: + - specialization + - confirmation_status + properties: + specialization: + $ref: '#/components/schemas/SpecializationCode' + confirmation_status: + type: string + enum: + - confirmed + - unconfirmed + declared_grade: + oneOf: + - $ref: '#/components/schemas/GradeCode' + - type: 'null' + CandidateWorkFormat: + type: string + enum: + - remote + - office + - hybrid + CardProject: + type: object + description: One published project as the card shows it. It never carries the repository address, the repository owner, or any text fetched from the repository. + additionalProperties: false + required: + - title + - description + - stack + - repository_verified + properties: + title: + type: string + minLength: 1 + maxLength: 100 + description: Project title as the candidate published it. Plain text; show it as text, never as HTML. + description: + description: Published project description, or null. Plain text; show it as text, never as HTML. + oneOf: + - type: string + minLength: 1 + maxLength: 500 + - type: 'null' + stack: + type: array + maxItems: 10 + description: Published technology tags of the project. + items: + $ref: '#/components/schemas/StackTag' + repository_verified: + type: boolean + description: True when the latest server check found the linked repository on GitHub and it is public. It does not prove that the candidate wrote the code. + parameters: + IdempotencyKey: + name: Idempotency-Key + in: header + required: true + description: |- + Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + + Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect. + + Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx. + + Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new. + schema: + type: string + minLength: 1 + maxLength: 255 + pattern: ^[A-Za-z0-9._:-]+$ + example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11 + IfMatch: + name: If-Match + in: header + required: false + description: |- + Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match. + + On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428. + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + PageLimit: + name: limit + in: query + required: false + description: Maximum number of items in the page. The server may return fewer items even when more remain; use `page.has_more` to detect the end. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 100 + default: 20 + PageCursor: + name: cursor + in: query + required: false + description: Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the first page. A malformed or foreign cursor returns 400 with code validation_failed. + schema: + type: string + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + AssessmentAttemptId: + name: attempt_id + in: path + required: true + description: Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + OrganizationId: + name: org_id + in: path + required: true + description: Identifier of an organization. Access comes only from an active membership of the session account in this organization, checked by the server on every request; the identifier itself grants nothing. An organization without such a membership and an unknown identifier both answer 404 not_found, so organizations cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + NeedId: + name: need_id + in: path + required: true + description: Identifier of a need of the organization in the path. A need of another organization and an unknown identifier both answer 404 not_found. + schema: + type: string + format: uuid + example: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + SupportCaseId: + name: case_id + in: path + required: true + description: Identifier of a case of the current account. A case of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + InvitationId: + name: invitation_id + in: path + required: true + description: Identifier of an invitation of the organization in the path. An invitation of another organization and an unknown identifier both answer 404 not_found. + schema: + type: string + format: uuid + example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + MyInvitationId: + name: invitation_id + in: path + required: true + description: Identifier of an invitation addressed to the current candidate. A draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + HiddenOrganizationId: + name: org_id + in: path + required: true + description: Identifier of the organization that the current candidate hides or stops hiding the profile from. It names the target of a candidate's own setting and grants the candidate nothing about the organization. Hiding answers the same 404 not_found for an organization that does not exist and for one that the candidate cannot see, so organizations cannot be enumerated; lifting the hiding answers 204 for any well-formed identifier. + schema: + type: string + format: uuid + example: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + NotificationId: + name: notification_id + in: path + required: true + description: Identifier of an item of the inbox of the current account in the cabinet that the path names. An item of another account, an item of another organization context, and an unknown identifier all answer 404 not_found, so identifiers cannot be enumerated. + schema: + type: string + format: uuid + example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + AttemptClient: + name: X-Attempt-Client + in: header + required: false + description: |- + Random identifier that one open page of the assessment attempt generates when it loads and keeps until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a one-way keyed digest bound to the attempt, never the value. + + A request that omits the header counts as one anonymous client. It is refused with 409 `state_conflict` while another page holds the work session, and it is accepted while nobody does, so a client that predates the header keeps working until a page holds the session. + schema: + type: string + minLength: 16 + maxLength: 64 + pattern: ^[A-Za-z0-9_-]+$ + example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG + AttemptClientRequired: + name: X-Attempt-Client + in: header + required: true + description: The page identifier described at AttemptClient. It is required here because the operation exists to hold or release the work session of one page. + schema: + type: string + minLength: 16 + maxLength: 64 + pattern: ^[A-Za-z0-9_-]+$ + example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG + CandidateHandle: + name: candidate_handle + in: path + required: true + description: Organization-scoped opaque candidate alias issued by the current visible card projection. The server resolves it only for the organization in the path and rechecks current membership, publication consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all answer the same 404. + schema: + $ref: '#/components/schemas/CandidateHandle' + example: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + headers: + ETag: + description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. + required: true + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + RetryAfter: + description: Number of seconds to wait before retrying the request. + schema: + type: integer + format: int32 + minimum: 0 + maximum: 86400 + example: 30 + 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. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + $ref: '#/components/examples/ValidationFailed' + domain_rule: + $ref: '#/components/examples/DomainValidationFailed' + Unauthenticated: + description: No valid session or credentials; code unauthenticated. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + unauthenticated: + $ref: '#/components/examples/Unauthenticated' + Forbidden: + description: The caller is authenticated but may not perform the operation; code forbidden. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + forbidden: + $ref: '#/components/examples/Forbidden' + NotFound: + description: The object does not exist or is not visible to the caller; code not_found. Missing and inaccessible objects are not distinguished. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + not_found: + $ref: '#/components/examples/NotFound' + IdempotencyInProgress: + description: A request with the same Idempotency-Key and the same fingerprint is still being processed; code idempotency_in_progress. Retry after the original request completes. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + StateConflict: + description: The operation conflicts with the current state of the resource, for example a transition that is not allowed from its current status; code state_conflict. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/StateConflict' + PreconditionFailed: + description: If-Match does not match the current resource version; code version_conflict. Nothing was changed. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/VersionConflict' + PayloadTooLarge: + description: The request body exceeds the operation limit; code payload_too_large. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + payload_too_large: + $ref: '#/components/examples/PayloadTooLarge' + UnprocessableContent: + description: The Idempotency-Key was already used with a different request within 24 hours; code idempotency_key_reused. Nothing was changed. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + idempotency_key_reused: + $ref: '#/components/examples/IdempotencyKeyReused' + PreconditionRequired: + description: The operation requires If-Match; code precondition_required. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + precondition_required: + $ref: '#/components/examples/PreconditionRequired' + TooManyRequests: + description: Too many requests; code rate_limited. + headers: + Retry-After: + $ref: '#/components/headers/RetryAfter' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + rate_limited: + $ref: '#/components/examples/RateLimited' + Internal: + description: Unexpected server error; code internal. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + internal: + $ref: '#/components/examples/Internal' + NotImplemented: + description: The operation is declared in the contract but not implemented yet; code not_implemented. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + not_implemented: + $ref: '#/components/examples/NotImplemented' + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + $ref: '#/components/examples/ValidationFailed' + not_found: + $ref: '#/components/examples/NotFound' + internal: + $ref: '#/components/examples/Internal' + not_implemented: + $ref: '#/components/examples/NotImplemented' + 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' + CsrfCheckFailedOrForbidden: + description: 'The request failed cross-site request protection, code csrf_check_failed: the X-CSRF-Token header is missing or does not belong to the session, or the Origin is not allowed. Or the account may not perform the operation, code forbidden. Nothing was changed in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + csrf_check_failed: + $ref: '#/components/examples/CsrfCheckFailed' + forbidden: + $ref: '#/components/examples/Forbidden' + QuestionnaireValidationFailed: + description: 'The body does not match the contract or violates a questionnaire rule: more than two specializations, an unknown specialization, grade, or task language, an unknown field such as confirmed_grade, a repeated specialization, or a task language that the specialization''s published bank does not offer; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + too_many_specializations: + $ref: '#/components/examples/QuestionnaireTooManySpecializations' + unknown_grade: + $ref: '#/components/examples/QuestionnaireUnknownGrade' + repeated_specialization: + $ref: '#/components/examples/QuestionnaireRepeatedSpecialization' + QuestionnaireVersionConflict: + description: '`expected_version` is not the current questionnaire version; code version_conflict. Nothing was changed; read the questionnaire again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/VersionConflict' + ProfileValidationFailed: + description: 'The body does not match the contract or violates a profile rule: an unknown field such as confirmed_grade, category, trust_level, or source, a phone number outside E.164, a Telegram username without the leading @, an email that is not an address, a month outside the YYYY-MM format, a salary that is not a positive multiple of 1000, more items than a list allows, a repeated tag, skill, or role specialization, a period that ends before it starts or lies in the future, a decision extracted for a value that is not a stored suggestion, an overlapping experience period without an explicit date-pair acknowledgement, or a missing or invalid expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed. The problem never repeats a submitted value, because the body is personal data.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + phone_not_e164: + $ref: '#/components/examples/ProfilePhoneNotE164' + extracted_value_changed: + $ref: '#/components/examples/ProfileExtractedValueChanged' + repeated_role: + $ref: '#/components/examples/ProfileRepeatedRole' + ProfileVersionConflict: + description: '`expected_version` is not the current profile version; code version_conflict. Nothing was changed; read the profile again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/ProfileStaleVersion' + AssessmentAttemptCreateValidationFailed: + description: 'The body does not match the contract or violates an assessment rule: an unknown specialization, grade, or task language, an unknown field such as mode or seed, a specialization that is not in the questionnaire, or a task language that the published bank does not offer; code validation_failed with body pointers. Nothing was created, and the outcome is not stored under the Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + specialization_not_in_questionnaire: + $ref: '#/components/examples/AssessmentSpecializationNotInQuestionnaire' + AssessmentAnswerValidationFailed: + description: 'The body does not match the contract or the answer does not fit the item: a format other than the item format, an option, element, or line that the item does not have, an order that is not a permutation of every element, more selections than the item allows, a text longer than the item allows, a language that the practice does not offer, or an unknown field such as score or duration; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was stored, and the outcome is not stored under the Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + unknown_option: + $ref: '#/components/examples/AssessmentAnswerUnknownOption' + score_sent_by_client: + $ref: '#/components/examples/AssessmentAnswerUnknownField' + AssessmentCommandConflict: + description: 'The attempt state does not allow the answer at the current version, code state_conflict: the attempt is terminal or past its limits, the item is not the current item, the item already has a different answer, or the practice has a pending or finished verdict and the submission differs. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case; read the attempt to see its state.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentItemNotCurrent' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + AssessmentFinalizeConflict: + description: 'The attempt state does not allow finalize at the current version, code state_conflict: items or the main practice are unfinished, a practice verdict is pending, or the attempt ended as expired or insufficient_bank. If required questions are unfinished, the response includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/AssessmentFinalizeConflictProblem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentFinalizeNotReady' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + AssessmentCreateConflict: + description: 'No attempt can start for the category now, code state_conflict: the specialization already has an active attempt, a retry or promotion interval or the attempt limit blocks the grade, or the bank is insufficient. GetMyAssessmentAvailability tells which, with the date when a blocked attempt opens. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was created in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentAttemptNotAvailable' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + AssessmentResultNotReady: + description: The attempt is still active, so it has no result yet; code state_conflict. The attempt state tells what remains to be done. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/AssessmentResultNotReady' + AssessmentVersionConflict: + description: '`expected_version` is not the current attempt version; code version_conflict. Nothing was changed, and the outcome is not stored under the Idempotency-Key; read the attempt again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/AssessmentStaleVersion' + NeedValidationFailed: + description: 'The body does not match the contract or violates a need rule: an unknown field such as rec_score, members, or candidate_minimum, a field sent as a bare value instead of `{value, status}`, a list sent as null, an unknown specialization, grade, work format, currency, period, or tax basis, a salary bound that is not a positive multiple of 1000, a lower bound that is not below the upper one, a range width outside 10-40% of its midpoint, a repeated skill or task, status `extracted` with a value that is not the stored suggestion, a vacancy that is not a vacancy of the organization, or a missing or invalid expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the outcome is not stored under an Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + reversed_salary_range: + $ref: '#/components/examples/NeedSalaryRangeReversed' + equal_salary_bounds: + $ref: '#/components/examples/NeedSalaryEqualBounds' + salary_range_too_wide: + $ref: '#/components/examples/NeedSalaryRangeTooWide' + salary_without_tax_basis: + $ref: '#/components/examples/NeedSalaryWithoutTaxBasis' + extracted_value_mismatch: + $ref: '#/components/examples/NeedExtractedValueMismatch' + recommendation_score_sent_by_client: + $ref: '#/components/examples/NeedUnknownField' + missing_expected_version: + $ref: '#/components/examples/NeedMissingExpectedVersion' + NeedVersionConflict: + description: '`expected_version` is not the current need version; code version_conflict. Nothing was changed; read the need again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/NeedStaleVersion' + SupportCaseValidationFailed: + description: 'The body does not match the contract or violates a case rule: an empty or blank description, including one made only of Unicode spaces, an unknown case type, an object identifier that is not a UUID, an object type that the case type does not accept, a missing required field of the type, an unknown field such as status, decision, moderator, or priority, or a complaint reason that requires an invitation reference; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was created, and the outcome is not stored under the Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + blank_description: + $ref: '#/components/examples/SupportCaseBlankDescription' + unknown_type: + $ref: '#/components/examples/SupportCaseUnknownType' + decision_sent_by_client: + $ref: '#/components/examples/SupportCaseUnknownField' + malformed_object_id: + $ref: '#/components/examples/SupportCaseMalformedReference' + complaint_reason_needs_invitation: + $ref: '#/components/examples/SupportCaseComplaintNeedsInvitation' + SupportCaseCreateConflict: + description: 'The referenced object does not allow this case now, code state_conflict: the attempt of a grade appeal has no result yet, the case referenced by a grade appeal is not a manual assessment resolved with the outcome assessed, the attempt of an anti-cheat appeal has no anti-cheat review decision, the attempt or the manual assessment already has an appeal of the same type, or an open case of the same type already exists for the category or the object. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was created in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/SupportCaseAppealExists' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + InvitationValidationFailed: + description: 'The body does not match the contract or violates an invitation rule: a missing term or package condition, a package condition left out instead of `not_provided`, a salary range without its tax basis, a salary bound that is not a positive multiple of 1000, a lower bound that is not below the upper one, a range width outside 10-40% of its midpoint, the `office` or `hybrid` format without a place of work, a repeated technology, a candidate handle that the organization cannot use, a need or requirements version that the organization does not have, a response period other than 3, 7, or 14 days, an unknown field such as a candidate''s email address or salary minimum, or a missing or invalid expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the outcome is not stored under an Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + without_tax_basis: + $ref: '#/components/examples/InvitationWithoutTaxBasis' + without_communication_method: + $ref: '#/components/examples/InvitationWithoutCommunicationMethod' + package_condition_left_out: + $ref: '#/components/examples/InvitationPackageItemMissing' + salary_range_too_wide: + $ref: '#/components/examples/InvitationSalaryRangeTooWide' + location_required: + $ref: '#/components/examples/InvitationLocationRequired' + unknown_candidate: + $ref: '#/components/examples/InvitationUnknownCandidate' + candidate_data_in_body: + $ref: '#/components/examples/InvitationCandidateDataInBody' + InvitationAcceptValidationFailed: + description: 'The body does not match the contract or violates a rule of the consent C4: a missing `terms_version` or `expected_version`, `accepted` other than true, an empty or repeated choice of contact fields, an unknown field kind, a field that the candidate''s profile does not hold, a consent text version that is not the published one, or an unknown field such as a contact value; code validation_failed with body pointers. Nothing was changed, no consent or grant was recorded, and the outcome is not stored under the Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + empty_field_choice: + $ref: '#/components/examples/InvitationConsentWithoutFields' + outdated_consent_text: + $ref: '#/components/examples/InvitationConsentTextOutdated' + missing_terms_version: + $ref: '#/components/examples/InvitationMissingTermsVersion' + InvitationVersionConflict: + description: '`expected_version` is not the current invitation version, or, for an acceptance, `terms_version` is not the current terms version; code version_conflict. Nothing was changed, no consent or grant was recorded, and the outcome is not stored under an Idempotency-Key; read the invitation again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + stale_terms: + $ref: '#/components/examples/InvitationStaleTerms' + stale_version: + $ref: '#/components/examples/InvitationStaleVersion' + InvitationCommandConflict: + description: 'The state of the invitation does not allow the command, code state_conflict: for example an acceptance of a withdrawn or expired invitation or one past its deadline, a send of an invitation that is no longer a draft, a send blocked by the pending limit of the need or by the pause after a decline, or a second raise of the upper salary bound. The invitation tells the client its state. Or a request with the same Idempotency-Key is still running, code idempotency_in_progress. Nothing was changed in either case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + not_answerable: + $ref: '#/components/examples/InvitationNotAnswerable' + salary_raise_used: + $ref: '#/components/examples/InvitationSalaryRaiseUsed' + send_blocked: + $ref: '#/components/examples/InvitationSendBlocked' + idempotency_in_progress: + $ref: '#/components/examples/IdempotencyInProgress' + OrganizationValidationFailed: + description: 'The body does not match the contract or violates an organization rule: a missing name, an unknown field such as role, verification_level, verification, members, owner, or version, a name or sphere with surrounding whitespace or a line break, a website that is not an https URL of a host name, a phone number outside E.164, a Telegram username without the leading @, a contact that has no valid form, more than ten representatives, or a missing or invalid expected_version; code validation_failed with body pointers. A missing nested field has its own pointer with the code required; an unknown field points at the object that contains it, a failure inside an array element points at the array, and only a malformed document, an unknown top-level field, or an unknown top-level variant points at the whole body. Nothing was changed, and the outcome is not stored under an Idempotency-Key.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + role_sent_by_client: + $ref: '#/components/examples/OrganizationUnknownField' + website_not_https: + $ref: '#/components/examples/OrganizationWebsiteNotHttps' + name_with_surrounding_whitespace: + $ref: '#/components/examples/OrganizationNameWithWhitespace' + missing_expected_version: + $ref: '#/components/examples/OrganizationMissingExpectedVersion' + OrganizationVersionConflict: + description: '`expected_version` is not the current version of the organization; code version_conflict. Nothing was changed; read the organization again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/OrganizationStaleVersion' + PrivacyValidationFailed: + description: 'The body does not match the contract or breaks a visibility rule: an unknown field, a repeated or unknown card field, a published state with no field, a closed state with a field, a search status other than looking and not_looking, or a missing or invalid expected_version; code validation_failed with body pointers. Nothing was changed. The problem never repeats a submitted value.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + published_without_fields: + $ref: '#/components/examples/PrivacyPublishedWithoutFields' + PrivacyVersionConflict: + description: '`expected_version` is not the current version of the setting; code version_conflict. Nothing was changed; read the settings again before retrying.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + version_conflict: + $ref: '#/components/examples/PrivacyStaleVersion' + PublicationConsentRequired: + description: 'The profile cannot be published because the account has no active, unrevoked C2 consent; code state_conflict. Nothing was changed. The candidate gives C2 in the consent settings first. `errors` holds the entry `{in: body, pointer: /state, code: consent_required}`.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + state_conflict: + $ref: '#/components/examples/PublicationConsentRequiredConflict' + HiddenOrganizationLimit: + description: 'The candidate already hides the maximum number of organizations (1000); code state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`. Nothing was changed.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + limit_reached: + $ref: '#/components/examples/HiddenOrganizationLimitReached' + EmailVerificationCodeFailed: + description: 'The code does not verify the email. Code verification_token_invalid covers every refusal in the same shape: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, and a code that was burned after five failed attempts. Code validation_failed means the body does not match the contract, such as a code that is not six digits, and carries the pointer `/code`, `/email`, or `/password`. Nothing was changed in any case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + verification_code_invalid: + $ref: '#/components/examples/VerificationCodeInvalid' + validation_failed: + $ref: '#/components/examples/VerificationCodeMalformed' + ServiceUnavailable: + description: The service cannot serve the request now; code service_unavailable. Retry-After is sent when a retry after that wait can succeed, for example when a queue is full, and omitted when a retry cannot help soon, for example when the feature is not enabled on this server. + headers: + Retry-After: + $ref: '#/components/headers/RetryAfter' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + service_unavailable: + summary: A queue is full. + value: + type: urn:lincodex:problem:service_unavailable + title: Service unavailable + status: 503 + code: service_unavailable + 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 + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 0b6f6f0e-7c55-4c8f-a8d1-6f3f3b8f2a10 + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + - in: header + pointer: /Idempotency-Key + code: required + message: The value is required. + NotFound: + summary: Unknown route or invisible object + value: + type: urn:lincodex:problem:not_found + title: Resource not found + status: 404 + code: not_found + detail: The requested resource does not exist. + trace_id: 1c2d3e4f-5a6b-4c7d-8e9f-0a1b2c3d4e5f + Internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. + trace_id: 9c0d1e2f-3a4b-4c5d-8e6f-7a8b9c0d1e2f + NotImplemented: + summary: Operation declared in the contract without an implementation + value: + type: urn:lincodex:problem:not_implemented + title: Operation not implemented + status: 501 + code: not_implemented + detail: This operation is not available yet. + trace_id: 0d1e2f3a-4b5c-4d6e-9f7a-8b9c0d1e2f3a + DomainValidationFailed: + summary: The body violates a domain rule + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6c + errors: + - in: body + pointer: /salary_from + code: invalid + message: The value does not match the contract. + Unauthenticated: + summary: No valid session + value: + type: urn:lincodex:problem:unauthenticated + title: Authentication required + status: 401 + code: unauthenticated + detail: Sign in and repeat the request. + trace_id: 4f2d1c3b-6a5e-4d7f-8b9a-0c1d2e3f4a5b + 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. + 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 + IdempotencyInProgress: + summary: The first request with this key is still running + value: + type: urn:lincodex:problem:idempotency_in_progress + title: Request with this idempotency key is in progress + status: 409 + code: idempotency_in_progress + detail: Retry after the original request completes. + trace_id: 2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a + 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. + VerificationCodeInvalid: + summary: The code does not verify the email + value: + type: urn:lincodex:problem:verification_token_invalid + title: Verification code is not valid + status: 400 + code: verification_token_invalid + detail: Check the code and the password, or request a new message. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b + VerificationCodeMalformed: + summary: The code is not six digits + 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: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c + errors: + - in: body + pointer: /code + 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 + 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' + SpecializationCatalog: + summary: Illustrative MVP catalog with the Backend and Network Engineer banks published + description: Illustrative values. The directions, specializations, and grades follow the MVP scale; `test_availability` comes from the published task banks, so the grades and languages shown here are not a statement about any deployed bank. + value: + directions: + - code: development + title: Разработка + specializations: + - code: backend + title: Backend + test_availability: + status: available + grades: + - intern + - junior + - middle + - senior + task_languages: + - python + - go + note: null + - code: frontend + title: Frontend + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: mobile + title: Mobile + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: infrastructure + title: Инфраструктура + specializations: + - code: network_engineer + title: Сетевой инженер + test_availability: + status: available + grades: + - junior + - middle + task_languages: [] + note: null + - code: devops_sre + title: DevOps/SRE + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: data + title: Данные + specializations: + - code: data_analyst + title: Аналитик данных + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: ds_ml + title: DS/ML + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: security + title: Безопасность + specializations: + - code: information_security + title: Информационная безопасность + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + - code: quality + title: Качество + specializations: + - code: qa + title: QA + test_availability: + status: in_development + grades: [] + task_languages: [] + note: Тест в разработке. + grades: + - code: intern + title: Стажер + - code: junior + title: Junior + - code: middle + title: Middle + - code: senior + title: Senior + NewCandidateQuestionnaire: + summary: A candidate who has not saved the questionnaire yet + value: + version: 0 + specializations: [] + work_context: null + updated_at: null + BackendGoAndNetworkEngineerQuestionnaire: + summary: Backend with Go and Network Engineer, two independent specializations + description: Go is a task language of the `backend` specialization and PostgreSQL and gRPC are stack tags; none of them is a category. The candidate has two specializations, `backend` and `network_engineer`, each assessed independently. The self-assessed grades are claims; no confirmed grade appears. + value: + version: 3 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: + - go + stack: + - PostgreSQL + - gRPC + - Kafka + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: + - Cisco IOS + - BGP + experience: null + work_context: + work_formats: + - remote + - hybrid + updated_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 + BackendGoAndNetworkEngineerQuestionnaireUpdate: + summary: Save Backend with Go and Network Engineer over version 2 + value: + expected_version: 2 + specializations: + - specialization: backend + self_assessed_grade: middle + task_languages: + - go + stack: + - PostgreSQL + - gRPC + - Kafka + experience: + commercial_months: 30 + academic_months: 12 + - specialization: network_engineer + self_assessed_grade: junior + task_languages: [] + stack: + - Cisco IOS + - BGP + experience: null + work_context: + work_formats: + - remote + - hybrid + QuestionnaireTooManySpecializations: + summary: Three specializations were sent; at most two are allowed + 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: 6c7d8e9f-0a1b-4c2d-8e3f-4a5b6c7d8e9f + errors: + - in: body + pointer: /specializations + code: invalid + message: The value does not match the contract. + QuestionnaireUnknownGrade: + summary: A self-assessed grade outside the grade scale, such as lead + 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: 7d8e9f0a-1b2c-4d3e-9f4a-5b6c7d8e9f0a + errors: + - in: body + pointer: /specializations/0/self_assessed_grade + code: invalid + message: The value does not match the contract. + QuestionnaireRepeatedSpecialization: + summary: The same specialization was chosen twice + 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: 8e9f0a1b-2c3d-4e4f-8a5b-6c7d8e9f0a1b + errors: + - in: body + pointer: /specializations/1/specialization + code: invalid + message: The value does not match the contract. + VersionConflict: + summary: If-Match does not match the current version + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 3e4f5a6b-7c8d-4e9f-8a0b-2c3d4e5f6a7b + NewCandidateProfile: + summary: A candidate who has not saved the profile yet + value: + version: 0 + full_name: + status: unknown + value: null + source: null + contacts: + email: + status: unknown + value: null + source: null + phone: + status: unknown + value: null + source: null + telegram: + status: unknown + value: null + source: null + stack: [] + roles: [] + experience: [] + experience_overlaps: [] + soft_skills: [] + projects: [] + terms: + location: + status: unknown + value: null + source: null + relocation: + status: unknown + value: null + source: null + salary_minimum: + status: unknown + value: null + source: null + confirmed_categories: [] + updated_at: null + BackendCandidateProfile: + summary: A manual Backend profile with one unconfirmed suggestion + description: 'The candidate typed most values, so they are `manual`. The phone number and the Kafka tag are suggestions that an imported document produced (planned): they are `extracted`, unconfirmed, and, like every claim, trust level 0. The candidate claims Middle in `roles`, while the only confirmed category is Backend Junior from an assessment result; the two are separate fields and the profile never merges them. The example values are fictional.' + value: + version: 3 + full_name: + status: confirmed + value: Anna Sokolova + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + contacts: + email: + status: confirmed + value: anna.sokolova@example.com + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + phone: + status: extracted + value: '+79000000000' + source: + origin: extracted_from_resume + trust_level: 0 + quote: 'Tel.: +7 900 000-00-00' + extraction_version: resume-rules.2026-10.1 + confirmed_at: null + telegram: + status: unknown + value: null + source: null + stack: + - tag: PostgreSQL + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + - tag: Kafka + status: extracted + source: + origin: extracted_from_resume + trust_level: 0 + quote: Event streaming with Kafka + extraction_version: resume-rules.2026-10.1 + confirmed_at: null + roles: + - specialization: backend + self_assessed_grade: middle + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + experience: + - employer_name: Example Payments + specialization: backend + started_on: 2022-03 + ended_on: null + summary: Moved the payout service to an event model and owned its on-call rotation. + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + experience_overlaps: [] + soft_skills: + - skill: Mentoring + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + projects: + - title: Payment webhook deduplication service + description: Idempotent receiver for acquirer callbacks with a unique operation key and an outbox for retries. + stack: + - Go + - PostgreSQL + repository_url: https://github.com/example-org/payments-ledger + repository_check: + state: verified + checked_at: '2026-10-05T09:31:00Z' + status: confirmed + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + terms: + location: + status: confirmed + value: Kazan + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + relocation: + status: confirmed + value: false + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + salary_minimum: + status: confirmed + value: + amount: 180000 + currency: RUB + period: month + tax_basis: net + source: + origin: manual + trust_level: 0 + quote: null + extraction_version: null + confirmed_at: '2026-10-05T09:30:00Z' + confirmed_categories: + - specialization: backend + grade: junior + basis: synthetic_demo + confirmed_at: '2026-10-04T18:10:00Z' + attempt_id: 0192b3c4-d5e6-7f80-9a1b-2c3d4e5f6a7b + updated_at: '2026-10-05T09:30:00Z' + BackendCandidateProfileUpdate: + summary: Save the Backend profile over version 2 + description: The candidate keeps the phone number and the Kafka tag as unconfirmed suggestions by sending `extracted` with exactly their stored values, and confirms or sets everything else. The values are fictional. + value: + expected_version: 2 + full_name: + value: Anna Sokolova + status: confirmed + contacts: + email: + value: anna.sokolova@example.com + status: confirmed + phone: + value: '+79000000000' + status: extracted + telegram: null + stack: + - tag: PostgreSQL + status: confirmed + - tag: Kafka + status: extracted + roles: + - specialization: backend + self_assessed_grade: middle + status: confirmed + experience: + - employer_name: Example Payments + specialization: backend + started_on: 2022-03 + ended_on: null + summary: Moved the payout service to an event model and owned its on-call rotation. + status: confirmed + soft_skills: + - skill: Mentoring + status: confirmed + terms: + location: + value: Kazan + status: confirmed + relocation: + value: false + status: confirmed + salary_minimum: + value: + amount: 180000 + currency: RUB + period: month + tax_basis: net + status: confirmed + ProfilePhoneNotE164: + summary: The phone number is not in the E.164 format + description: A rule of the schema. The pointer names the value inside the decision, and the body never repeats the submitted number. + 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: 6d7e8f9a-0b1c-4d2e-8f4a-5b6c7d8e9f01 + errors: + - in: body + pointer: /contacts/phone/value + code: invalid + message: The value does not match the contract. + ProfileExtractedValueChanged: + summary: A decision extracted for a tag that is not a stored suggestion + description: A domain rule of the server, checked after the schema. A suggestion can stay unconfirmed only with exactly its stored value; send confirmed to set a manual value. + 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: 7e8f9a0b-1c2d-4e3f-9a5b-6c7d8e9f0a12 + errors: + - in: body + pointer: /stack/1/status + code: invalid + message: The value does not match the contract. + ProfileRepeatedRole: + summary: The same specialization appears in two roles + 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: 8f9a0b1c-2d3e-4f4a-8b6c-7d8e9f0a1b23 + errors: + - in: body + pointer: /roles/1/specialization + code: invalid + message: The value does not match the contract. + ProfileStaleVersion: + summary: The save carried a stale expected_version + description: The profile changed, for example in another tab, after the client read it. Nothing was changed; the client reads the profile again and reapplies its edits. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 9a0b1c2d-3e4f-4a5b-9c7d-8e9f0a1b2c34 + AssessmentAvailability: + summary: Backend open in demo_basic, Network Engineer blocked + description: Illustrative values. Backend junior and middle can start in the demo_basic mode, with their limits shown before the start; intern and senior have no sufficient bank. Network Engineer junior waits for its same-grade retry interval after an unconfirmed attempt. + value: + specializations: + - specialization: backend + confirmed_grade: null + confirmed_basis: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 12 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - specialization: network_engineer + confirmed_grade: null + confirmed_basis: null + active_attempt_id: null + grades: + - grade: intern + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + - grade: junior + status: cooldown + mode: demo_basic + available_at: '2026-11-12T00:00:00Z' + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: middle + status: available + mode: demo_basic + available_at: null + time_limit_seconds: 259200 + max_sessions: 2 + max_items: 10 + practice_required: false + - grade: senior + status: insufficient_bank + mode: null + available_at: null + time_limit_seconds: null + max_sessions: null + max_items: null + practice_required: null + StateConflict: + summary: The resource state does not allow the operation + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5b + AssessmentAttemptCreateBackendJunior: + summary: Start Backend junior with Go tasks + value: + kind: root + specialization: backend + target_grade: junior + task_language: go + AssessmentAttemptCreated: + summary: New demo_basic attempt with its first item + description: The server chose demo_basic from the published bank and fixed the policy, bank, and algorithm versions; creation started session 1. A retry of this create with the same Idempotency-Key and body within 24 hours replays exactly this 201 response and creates nothing; read the attempt for its current state. The attempt has no practice, because code practice stays disabled until the sandbox isolation is verified. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 1 + kind: root + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: null + chain_deadline: null + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + sequence: 1 + prompt: Какой HTTP-статус вернуть, если запрос валиден, но ресурс находится в состоянии, не допускающем операцию? + content: + format: choice + multiple: false + options: + - id: k7 + text: '400' + - id: p2 + text: '404' + - id: x9 + text: '409' + - id: c4 + text: '500' + practices: [] + AssessmentCorrectiveAttemptCreated: + summary: Corrective attempt shares the root chain deadline + value: + id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + version: 1 + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: '2026-11-23T09:00:00Z' + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-22T10:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 0 + max_items: 25 + current_item: + id: 01928f7e-9999-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: What does an HTTP 412 response indicate for expected_version? + content: + format: choice + multiple: false + options: + - id: a1 + text: The version is stale. + - id: b2 + text: The request is malformed. + practices: [] + AssessmentExpressAttemptCreated: + summary: Short training attempt without a qualification category + value: + id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c01 + version: 1 + kind: demo_express + specialization: null + target_grade: null + task_language: null + root_attempt_id: null + chain_deadline: null + mode: demo_express + state: in_progress + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-08T10:05:00Z' + sessions: + used: 1 + max: 1 + idle_timeout_seconds: 300 + finished_at: null + progress: + answered_items: 0 + max_items: 5 + current_item: + id: 01928f7f-aaaa-7a2b-8c3d-4e5f6a7b8c01 + sequence: 1 + prompt: Choose the status code that signals a version conflict. + content: + format: choice + multiple: false + options: + - id: c3 + text: '412' + - id: d4 + text: '200' + practices: [] + AssessmentSpecializationNotInQuestionnaire: + summary: The specialization is not in the questionnaire + 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: 9f0a1b2c-3d4e-4f5a-8b6c-7d8e9f0a1b2c + errors: + - in: body + pointer: /specialization + code: invalid + message: The value does not match the contract. + AssessmentAttemptNotAvailable: + summary: No attempt can start for the category now + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3d4e5f6a-7b8c-4d9e-8f0a-1b2c3d4e5f6a + AssessmentAttemptResumed: + summary: Adaptive attempt resumed on its sixth item in session 2 + description: A reload or a new session returns the same item instance with the same lines; nothing tells whether the five earlier answers were correct, and seed items look like scored ones. The retest started from the previous ability estimate of the specialization. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 7 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: in_progress + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 5 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + sequence: 6 + prompt: Найдите строку, из-за которой соединения с базой данных не возвращаются в пул. + content: + format: find_error + syntax: python + max_selections: 1 + lines: + - number: 1 + text: 'def load_user(pool, user_id):' + - number: 2 + text: ' conn = pool.acquire()' + - number: 3 + text: ' row = conn.fetchrow(QUERY, user_id)' + - number: 4 + text: ' if row is None:' + - number: 5 + text: ' raise NotFound(user_id)' + - number: 6 + text: ' pool.release(conn)' + - number: 7 + text: ' return row' + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentAttemptPracticePending: + summary: Item part finished, main practice not submitted + description: The adaptive stop rule ended the item part after 14 items, but no grade is decided until the main practice has a finished verdict. The current item is the practice; hidden checks and seeds are not part of it. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 16 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: 'Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу.' + content: + format: practice + languages: + - python + max_source_length: 20000 + public_examples: + - input: '[[1,3],[2,6],[8,10]]' + expected_output: '[[1,6],[8,10]]' + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentAttemptPracticeVerdictPending: + summary: Practice submitted, verdict pending in the sandbox + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 17 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: pending + submitted_at: '2026-11-20T10:05:00Z' + verdict: null + failure_reason: null + AssessmentAttemptSandboxFailed: + summary: Sandbox queue was full; the practice can be submitted again + description: The failure does not depend on the solution and consumes nothing. The practice item is current again; a resubmission, with the same or a different solution, queues it again and advances the version. + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 18 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + sequence: 15 + prompt: 'Реализуйте функцию merge_intervals: на вход список пар [start, end], на выход объединенные пересекающиеся интервалы, отсортированные по началу.' + content: + format: practice + languages: + - python + max_source_length: 20000 + public_examples: + - input: '[[1,3],[2,6],[8,10]]' + expected_output: '[[1,6],[8,10]]' + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: failed + submitted_at: '2026-11-20T10:05:00Z' + verdict: null + failure_reason: sandbox_busy + AssessmentAttemptReadyToFinalize: + summary: Main practice verdict finished, ready to finalize + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 20 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: ready_to_finalize + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: '2026-11-20T10:09:00Z' + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null + AssessmentAttemptAdditionalPracticePending: + summary: Finalize offered an additional practice in the same attempt + description: 'The probability of reaching middle was in the band below confirmation, so finalize decided nothing yet: it appended an additional practice and returned the attempt instead of a result. The attempt keeps its time and session limits and spends no new attempt. Submitting the additional practice leads back to ready_to_finalize; finalizing now declines it and gives not_confirmed. A retry of that finalize with a new key and the old expected_version 20 answers 412 and cannot decline by accident.' + value: + id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + version: 21 + kind: root + specialization: backend + target_grade: middle + task_language: python + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: additional_practice_pending + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-20T09:00:00Z' + expires_at: '2026-11-23T09:00:00Z' + sessions: + used: 2 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 14 + max_items: 25 + current_item: + id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + sequence: 16 + prompt: Реализуйте LRU-кеш с операциями get и put за O(1). + content: + format: practice + languages: + - python + max_source_length: 20000 + public_examples: + - input: put(1,1); put(2,2); get(1); put(3,3); get(2) + expected_output: 1, -1 + practices: + - kind: main + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + status: finished + submitted_at: '2026-11-20T10:09:00Z' + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + failure_reason: null + - kind: additional + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8ca0 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentAttemptCompleted: + summary: demo_basic attempt finalized; read the result next + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 14 + kind: root + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: null + chain_deadline: null + mode: demo_basic + state: completed + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: '2026-10-08T10:24:00Z' + progress: + answered_items: 12 + max_items: 12 + current_item: null + practices: [] + AssessmentAttemptInsufficientBank: + summary: Attempt ended because the bank could not cover the blueprint + description: The bank ran out of unseen families for a required domain within the item limit. The attempt ended without a confirmed grade instead of repeating a family; its result has outcome not_determined, and it does not count against the retry rules. + value: + id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + version: 10 + kind: root + specialization: network_engineer + target_grade: middle + task_language: null + root_attempt_id: null + chain_deadline: null + mode: adaptive + state: insufficient_bank + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + started_at: '2026-11-21T12:00:00Z' + expires_at: '2026-11-24T12:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: '2026-11-21T12:31:00Z' + progress: + answered_items: 8 + max_items: 25 + current_item: null + practices: + - kind: main + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c99 + status: not_started + submitted_at: null + verdict: null + failure_reason: null + AssessmentItemNotCurrent: + summary: The answered item is not the current item, or it already has another answer + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 2c3d4e5f-6a7b-4c8d-9e9f-0a1b2c3d4e5f + AssessmentStaleVersion: + summary: The command carried a stale expected_version + description: Another tab or device changed the attempt after the client read version 1. Nothing was stored; the client reads the attempt again and continues from its current item. The repository answers a stale version with 412, not 409. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c + PayloadTooLarge: + summary: The request body exceeds the limit + value: + type: urn:lincodex:problem:payload_too_large + title: Request body too large + status: 413 + code: payload_too_large + detail: Reduce the request body size and retry. + trace_id: 8b9c0d1e-2f3a-4b4c-9d5e-6f7a8b9c0d1e + AssessmentChoiceAnswer: + summary: Answer item 1 of version 1 + value: + expected_version: 1 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d01 + answer: + format: choice + option_ids: + - x9 + AssessmentOrderAnswer: + summary: Answer item 2 with every element once + value: + expected_version: 2 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + answer: + format: order + element_ids: + - a7 + - b1 + - c2 + - d3 + AssessmentNumberAnswer: + summary: Number answer + value: + expected_version: 3 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d03 + answer: + format: number + number: 254 + AssessmentStringAnswer: + summary: String answer + value: + expected_version: 4 + item_id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d04 + answer: + format: string + text: Retry-After + AssessmentFindErrorAnswer: + summary: Find-error answer for the resumed item + value: + expected_version: 7 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c06 + answer: + format: find_error + line_numbers: + - 5 + AssessmentConfigurationAnswer: + summary: Configuration answer + value: + expected_version: 7 + item_id: 01928f7c-6666-7a2b-8c3d-4e5f6a7b8c07 + answer: + format: configuration + config: |- + interface GigabitEthernet0/1 + ip access-group BLOCK_TELNET in + AssessmentPracticeAnswer: + summary: Main practice solution + description: Sent with expected_version 16 for the first submission. After a failed verdict the client sends it again with the current version, such as 18 in AssessmentAttemptSandboxFailed; the same source then queues again. + value: + expected_version: 16 + item_id: 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c99 + answer: + format: practice + language: python + source_code: |- + def merge_intervals(intervals): + result = [] + for start, end in sorted(intervals): + if result and start <= result[-1][1]: + result[-1][1] = max(result[-1][1], end) + else: + result.append([start, end]) + return result + AssessmentAnswerAccepted: + summary: Answer to item 1 stored; item 2 follows + description: The answer of AssessmentChoiceAnswer was stored and the version advanced from 1 to 2. The response does not say whether the answer was correct. A retry with the same Idempotency-Key replays exactly this response. Sending the same answer to item 1 again, even with a new key or the older expected_version 1, stores nothing and returns 200 with the current attempt. AssessmentOrderAnswer answers item 2 next. + value: + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + version: 2 + kind: root + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: null + chain_deadline: null + mode: demo_basic + state: in_progress + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + started_at: '2026-10-08T10:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + sessions: + used: 1 + max: 2 + idle_timeout_seconds: 1800 + finished_at: null + progress: + answered_items: 1 + max_items: 12 + current_item: + id: 01928f7a-4a10-7b2c-9d3e-5f6a7b8c9d02 + sequence: 2 + prompt: Упорядочите шаги обработки запроса в обработчике HTTP. + content: + format: order + elements: + - id: d3 + text: Записать ответ + - id: a7 + text: Проверить сессию + - id: c2 + text: Выполнить операцию + - id: b1 + text: Разобрать и проверить тело + practices: [] + AssessmentAnswerUnknownOption: + summary: The selected option does not belong to the item + 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: 0a1b2c3d-4e5f-4a6b-9c7d-8e9f0a1b2c3d + errors: + - in: body + pointer: /answer/option_ids/0 + code: invalid + message: The value does not match the contract. + AssessmentAnswerUnknownField: + summary: The client sent its own score + 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: 1b2c3d4e-5f6a-4b7c-8d8e-9f0a1b2c3d4e + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + AssessmentFinalization: + summary: Finalize version 20 + value: + expected_version: 20 + AssessmentFinalizeNotReady: + summary: Premature finalize; the problem lists unanswered frozen items + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6a7b8c9d-0e1f-4a2b-8c3d-4e5f6a7b8c9e + pending_item_ids: + - 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + - 01928f7b-2222-7a2b-8c3d-4e5f6a7b8c9d + AssessmentDemoBasicResult: + summary: demo_basic result with a confirmed grade and no uncertainty + description: demo_basic computes no ability estimate, so `uncertainty` and `strength` are null rather than zero, and no percentile is shown. The pass mark comes from basic grading policy version 1, and the limitations name the uncalibrated thresholds, the demo bank, and the missing practice. A first confirmation is not a promotion, so the higher grade can be tested at once. The result never changes; a repeated finalize returns the completed attempt, and this read returns the same result. + value: + attempt_id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + specialization: backend + target_grade: junior + kind: root + root_attempt_id: null + chain_deadline: null + task_language: go + mode: demo_basic + versions: + policy_version: 1 + bank_version: backend-demo.2026-10.1 + algorithm_version: basic-raw-score.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: junior + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - demo_bank + - practice_not_included + - unproctored + uncertainty: null + basic_score: + points: 9 + max_points: 12 + pass_points: 8 + practices: [] + gaps: [] + durations: + items_seconds: 1260 + practice_seconds: null + next_steps: + - action: take_higher_grade + grade: middle + available_at: null + decided_at: '2026-10-08T10:24:00Z' + AssessmentAdaptiveResult: + summary: Adaptive promotion confirmed with medium strength + description: Illustrative values, continuing AssessmentAttemptAdditionalPracticePending. The additional practice raised P_G to 0.84, in the medium band of the policy version, so the grade is confirmed with medium strength. The candidate already had junior, so this is a promotion, and the next one waits for the promotion interval. The thresholds are uncalibrated until the pilot. + value: + attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null + task_language: python + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: confirmed + not_determined_reason: null + confirmed_grade: middle + previous_confirmed_grade: junior + strength: medium + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: + theta: 0.62 + standard_error: 0.24 + interval_95: + low: 0.15 + high: 1.09 + p_grade: 0.84 + basic_score: null + practices: + - kind: main + verdict: + score: 2 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: false + - kind: additional + verdict: + score: 3 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: true + - group: 3 + passed: true + gaps: + - domain: concurrency + title: Конкурентность + durations: + items_seconds: 1980 + practice_seconds: 1500 + next_steps: + - action: take_higher_grade + grade: senior + available_at: '2027-02-18T10:30:00Z' + decided_at: '2026-11-20T10:30:00Z' + AssessmentNotConfirmedResult: + summary: Adaptive attempt not confirmed after the additional practice + description: P_G stayed below 0.80 after the additional practice, so middle is not confirmed, and the candidate keeps no confirmed grade. After a failure, including the first test, junior can be tested at once; accepting junior on the evidence of this attempt is offered; middle opens again after the same-grade retry interval. + value: + attempt_id: 01928f7d-7777-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.7 + p_grade: 0.62 + basic_score: null + practices: + - kind: main + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + - kind: additional + verdict: + score: 1 + max_score: 3 + groups: + - group: 1 + passed: true + - group: 2 + passed: false + - group: 3 + passed: false + gaps: + - domain: databases + title: Базы данных + durations: + items_seconds: 2100 + practice_seconds: 1800 + next_steps: + - action: take_lower_grade + grade: junior + available_at: null + - action: accept_lower_grade + grade: junior + available_at: null + - action: retake_same_grade + grade: middle + available_at: '2026-12-22T11:00:00Z' + decided_at: '2026-11-22T11:00:00Z' + AssessmentInsufficientBankResult: + summary: Attempt without a decision because the bank was insufficient + value: + attempt_id: 01928f7c-5555-7a2b-8c3d-4e5f6a7b8c9d + specialization: network_engineer + target_grade: middle + kind: root + root_attempt_id: null + chain_deadline: null + task_language: null + mode: adaptive + versions: + policy_version: 2 + bank_version: network.2026-11.1 + algorithm_version: irt-1pl-eap.1 + outcome: not_determined + not_determined_reason: insufficient_bank + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1860 + practice_seconds: null + next_steps: [] + decided_at: '2026-11-21T12:31:00Z' + AssessmentCorrectiveResult: + summary: Corrective result retains its root and fixed deadline + value: + attempt_id: 01928f7e-8888-7a2b-8c3d-4e5f6a7b8c9d + specialization: backend + target_grade: middle + kind: corrective + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + chain_deadline: '2026-11-23T09:00:00Z' + task_language: go + mode: adaptive + versions: + policy_version: 2 + bank_version: backend.2026-11.3 + algorithm_version: irt-1pl-eap.1 + outcome: not_confirmed + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: junior + strength: null + calibration_status: uncalibrated + limitations: + - uncalibrated_thresholds + - unproctored + uncertainty: + theta: 0.21 + standard_error: 0.25 + interval_95: + low: -0.28 + high: 0.7 + p_grade: 0.62 + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 1500 + practice_seconds: 900 + next_steps: [] + decided_at: '2026-11-22T11:00:00Z' + AssessmentExpressResult: + summary: Short training result with no qualification evidence + value: + attempt_id: 01928f7f-9999-7a2b-8c3d-4e5f6a7b8c9d + specialization: null + target_grade: null + task_language: null + kind: demo_express + mode: demo_express + versions: + policy_version: 1 + bank_version: express-demo.2026-10.1 + algorithm_version: express-interactive.1 + outcome: demonstration + not_determined_reason: null + confirmed_grade: null + previous_confirmed_grade: null + strength: null + calibration_status: uncalibrated + limitations: + - demonstration_only + uncertainty: null + basic_score: null + practices: [] + gaps: [] + durations: + items_seconds: 260 + practice_seconds: null + next_steps: [] + summary: The run demonstrates the task flow and creates no qualification evidence. + decided_at: '2026-11-22T11:00:00Z' + AssessmentResultNotReady: + summary: The attempt has no result yet + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4e5f6a7b-8c9d-4e0f-9a1b-2c3d4e5f6a7b + MyOrganizationListPage: + summary: The organizations of an owner who works in two companies + description: The caller has an active membership in both organizations, newest first. A third organization, where the caller left, is not listed. + value: + items: + - organization: + id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c + name: ИП Тестов Логистика + verification_level: e0 + membership: + organization_id: 01928f7a-4d5e-7f6a-8b7c-9d0e1f2a3b4c + role: owner + state: active + joined_at: '2026-10-06T11:30:00Z' + - organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + verification_level: e0 + membership: + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + role: owner + state: active + joined_at: '2026-10-06T09:00:00Z' + page: + has_more: false + next_cursor: null + OrganizationCreateNameOnly: + summary: A company that starts with its name only + description: Only the name is required; the card is completed later with UpdateOrganization. + value: + name: ООО Пример Платежи + OrganizationCreateCompleteCard: + summary: A company that gives its whole card at creation + description: Every contact is a company channel, and the representative is presentation only. There is no field for a role or a verification level. + value: + name: ООО Пример Платежи + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: '+74950000000' + telegram: '@payments_careers' + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору + OrganizationNameOnly: + summary: A new organization that has only a name + description: The creator is the owner of the organization, which starts at the verification level e0 on the ground of the confirmed email. The card repeats the profile as a candidate sees it. + value: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + version: 1 + name: ООО Пример Платежи + description: null + sphere: null + contacts: + website: null + email: null + phone: null + telegram: null + representatives: [] + verification: + level: e0 + basis: confirmed_email + changed_at: '2026-10-06T09:00:00Z' + candidate_card: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + description: null + sphere: null + contacts: + website: null + email: null + phone: null + telegram: null + representatives: [] + verification_level: e0 + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + OrganizationCompleteCard: + summary: An organization with a complete card, still at the level e0 + description: Completing the card, adding contacts, and listing representatives did not raise the verification level, which stays e0 and changes only through a verification process of the server. + value: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + version: 2 + name: ООО Пример Платежи + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: '+74950000000' + telegram: '@payments_careers' + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору + verification: + level: e0 + basis: confirmed_email + changed_at: '2026-10-06T09:00:00Z' + candidate_card: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: '+74950000000' + telegram: '@payments_careers' + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору + verification_level: e0 + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:40:00Z' + OrganizationUnknownField: + summary: The client sent a role together with the profile + description: A role, an owner, a verification level, and a list of members are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. + 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: 1e2f3a4b-5c6d-4e7f-8a9b-0c1d2e3f4a5c + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + OrganizationWebsiteNotHttps: + summary: The website is not an https URL of a host name + description: A domain rule of the server, checked after the schema. The schema already refuses a value that is not an https URL; the server also refuses a port, an IP address, and a host name without a dot. + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 2f3a4b5c-6d7e-4f8a-9b0c-1d2e3f4a5b6d + errors: + - in: body + pointer: /contacts/website + code: invalid + message: The value does not match the contract. + OrganizationNameWithWhitespace: + summary: The name has leading whitespace + 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: 3a4b5c6d-7e8f-4a9b-8c1d-2e3f4a5b6c7e + errors: + - in: body + pointer: /name + code: invalid + message: The value does not match the contract. + OrganizationMissingExpectedVersion: + summary: A change without expected_version + 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: 4b5c6d7e-8f9a-4b0c-9d2e-3f4a5b6c7d8f + errors: + - in: body + pointer: /expected_version + code: required + message: The value is required. + OrganizationUpdateCompleteCard: + summary: The owner completes the card of the organization + description: The change carries the version that the client read and the fields to replace; contacts and representatives are replaced as a whole. The body has no role or verification field. + value: + expected_version: 1 + description: Платежный сервис для малого бизнеса. Разрабатываем собственное ядро проведения платежей и интеграции с банками. + sphere: Платежи и финансовые сервисы + contacts: + website: https://payments.example.com + email: careers@payments.example.com + phone: '+74950000000' + telegram: '@payments_careers' + representatives: + - name: Анна Тестова + job_title: Руководитель по подбору + OrganizationStaleVersion: + summary: The change carried a stale expected_version + description: Another member changed the organization after the client read it. Nothing was changed; the client reads the organization again and reapplies its edits. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 5c6d7e8f-9a0b-4c1d-8e3f-4a5b6c7d8e90 + NeedListPage: + summary: The last page of the needs of an organization + value: + items: + - id: 01928f7a-3c4d-7e5f-8a6b-7c8d9e0f1a23 + vacancy_id: null + title: Backend в команду платежей + version: 2 + specialization: + status: confirmed + value: backend + source: + origin: extracted_from_text + quote: Ищем бэкенд-разработчика + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + grade: + status: confirmed + value: middle + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:20:00Z' + - id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + vacancy_id: null + title: Junior Go-разработчик для сервиса уведомлений + version: 1 + specialization: + status: confirmed + value: backend + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + grade: + status: confirmed + value: junior + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + created_at: '2026-10-06T08:15:00Z' + updated_at: '2026-10-06T08:15:00Z' + page: + has_more: false + next_cursor: null + NeedCreateManual: + summary: A manual need without a vacancy and without a text + description: Every field comes from the form as a decision with status confirmed, so every value is a confirmed manual value. There is no vacancy_id and no source_text; the domain is not given and stays unknown. + value: + title: Junior Go-разработчик для сервиса уведомлений + specialization: + value: backend + status: confirmed + grade: + value: junior + status: confirmed + required_skills: + - name: Go + status: confirmed + - name: PostgreSQL + status: confirmed + desired_skills: + - name: Docker + status: confirmed + tasks: + - text: Поддерживать и развивать сервис уведомлений + status: confirmed + work_formats: + value: + - hybrid + status: confirmed + location: + value: Москва + status: confirmed + salary: + value: + salary_from: 120000 + salary_to: 160000 + currency: RUB + period: month + tax_basis: net + status: confirmed + NeedCreateFromText: + summary: A need created from a pasted description + description: Only the title and the text are given. The server extracts suggestions from the text; nothing is confirmed until a member confirms it. + value: + title: Backend в команду платежей + source_text: 'Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно.' + NeedManualWithoutVacancy: + summary: A complete manual need without a vacancy, with computed recommendations + description: The need created by NeedCreateManual. Every value is confirmed and manual, so the quote, extracted_in_version, and extraction_version are null; the domain was not given and stays unknown with null value and source rather than a guessed one. The hybrid format makes the location critical, and it is confirmed. The range of 120000-160000 has a width of about 29%. The first category scores 0.75 with Overlap 1, a money share rounded down to 0.5, and Supply 0.5 for 15 available candidates. The other two have fewer than five candidates, so their score is null and Supply enters their ranking as 0. The recommendation values are illustrative and say nothing about a deployed policy or real candidates. + value: + id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + vacancy_id: null + title: Junior Go-разработчик для сервиса уведомлений + source_text: null + version: 1 + requirements_version: 1 + requirements: + specialization: + status: confirmed + value: backend + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + grade: + status: confirmed + value: junior + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + required_skills: + - name: Go + taxonomy_code: go + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + - name: PostgreSQL + taxonomy_code: postgresql + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + desired_skills: + - name: Docker + taxonomy_code: docker + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + tasks: + - text: Поддерживать и развивать сервис уведомлений + status: confirmed + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + domain: + status: unknown + value: null + source: null + work_formats: + status: confirmed + value: + - hybrid + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + location: + status: confirmed + value: Москва + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + salary: + status: confirmed + value: + salary_from: 120000 + salary_to: 160000 + currency: RUB + period: month + tax_basis: net + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + recommendations: + status: computed + requirements_version: 1 + policy_version: 1 + algorithm_version: need-rec.2026-10.1 + computed_at: '2026-10-06T08:15:02Z' + categories: + - specialization: backend + grade: junior + score: 0.75 + skill_overlap: + share: 1 + covered_skills: + - Go + - PostgreSQL + - Docker + uncovered_skills: [] + money: + status: computed + share: 0.5 + supply: from_5_to_29 + - specialization: backend + grade: intern + score: null + skill_overlap: + share: 0.8 + covered_skills: + - Go + - PostgreSQL + uncovered_skills: + - Docker + money: + status: insufficient_data + share: null + supply: fewer_than_5 + - specialization: devops_sre + grade: junior + score: null + skill_overlap: + share: 0.2 + covered_skills: + - Docker + uncovered_skills: + - Go + - PostgreSQL + money: + status: insufficient_data + share: null + supply: fewer_than_5 + created_at: '2026-10-06T08:15:00Z' + updated_at: '2026-10-06T08:15:00Z' + NeedExtractedWithUnknownSkill: + summary: A need from text with suggestions, an unknown skill, and missing fields + description: 'The need created by NeedCreateFromText. Every value found in the text is extracted with its quote from the text of version 1 and the extractor version, and waits for confirmation. Temporal is not in the skill taxonomy, so its taxonomy_code is null instead of a guessed code. The text names no grade, place, or salary: they stay unknown with null value and source, and the critical ones are listed in missing_fields with a question. Without a confirmed skill there are no recommendations yet.' + value: + id: 01928f7a-3c4d-7e5f-8a6b-7c8d9e0f1a23 + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + vacancy_id: null + title: Backend в команду платежей + source_text: 'Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно.' + version: 1 + requirements_version: 1 + requirements: + specialization: + status: extracted + value: backend + source: + origin: extracted_from_text + quote: Ищем бэкенд-разработчика + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + grade: + status: unknown + value: null + source: null + required_skills: + - name: Go + taxonomy_code: go + status: extracted + source: + origin: extracted_from_text + quote: 'Обязательно: Go, PostgreSQL и Temporal' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: PostgreSQL + taxonomy_code: postgresql + status: extracted + source: + origin: extracted_from_text + quote: 'Обязательно: Go, PostgreSQL и Temporal' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: Temporal + taxonomy_code: null + status: extracted + source: + origin: extracted_from_text + quote: 'Обязательно: Go, PostgreSQL и Temporal' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + desired_skills: + - name: Kafka + taxonomy_code: kafka + status: extracted + source: + origin: extracted_from_text + quote: Желательно опыт с Kafka + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + tasks: + - text: Развивать сервис выплат и переводить его на событийную модель + status: extracted + source: + origin: extracted_from_text + quote: 'Задачи: развивать сервис выплат и переводить его на событийную модель' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + domain: + status: extracted + value: платежи + source: + origin: extracted_from_text + quote: в команду платежей + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + work_formats: + status: extracted + value: + - remote + source: + origin: extracted_from_text + quote: Работа удаленно + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + location: + status: unknown + value: null + source: null + salary: + status: unknown + value: null + source: null + readiness: + status: incomplete + missing_fields: + - field: specialization + reason: unconfirmed + question: Подтвердите специализацию, найденную в описании. + - field: grade + reason: unknown + question: 'Какой грейд нужен: Intern, Junior, Middle или Senior?' + - field: required_skills + reason: unconfirmed + question: Подтвердите обязательные навыки, найденные в описании. + - field: work_formats + reason: unconfirmed + question: Подтвердите формат работы, найденный в описании. + - field: salary + reason: unknown + question: 'Какую вилку в рублях вы предлагаете и в какой базе: на руки или до вычета НДФЛ?' + recommendations: + status: not_available + requirements_version: 1 + policy_version: null + algorithm_version: null + computed_at: null + categories: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + NeedSalaryRangeReversed: + summary: The lower salary bound is above the upper one + 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: 6b7c8d9e-0f1a-4b2c-8d3e-4f5a6b7c8d9f + errors: + - in: body + pointer: /salary/value/salary_to + code: invalid + message: The value does not match the contract. + NeedSalaryEqualBounds: + summary: Equal salary bounds; PRD FR13 requires salary_from < salary_to + 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: 1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d + errors: + - in: body + pointer: /salary/value/salary_to + code: invalid + message: The value does not match the contract. + NeedSalaryRangeTooWide: + summary: A salary range wider than 40% of its midpoint, such as 100000-200000 + description: The width (200000 - 100000) / 150000 is about 67%. A range narrower than 10%, such as 100000-105000, gets the same answer. + 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: 2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e + errors: + - in: body + pointer: /salary/value/salary_to + code: invalid + message: The value does not match the contract. + NeedSalaryWithoutTaxBasis: + summary: A salary range without its tax basis + description: The responder rebuilds the path of a missing nested field from the decoder, so the pointer names the missing field. + 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: 7c8d9e0f-1a2b-4c3d-9e4f-5a6b7c8d9e0a + errors: + - in: body + pointer: /salary/value/tax_basis + code: required + message: The value is required. + NeedExtractedValueMismatch: + summary: Status extracted with a value that is not the stored suggestion + description: A request may keep only the stored suggestion unconfirmed. To set another value, it sends status confirmed. + 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: 3c4d5e6f-7a8b-4c9d-8e0f-2a3b4c5d6e7f + errors: + - in: body + pointer: /grade/status + code: invalid + message: The value does not match the contract. + NeedUnknownField: + summary: The client sent its own recommendation score + description: Recommendations, membership, and candidate minimums are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. + 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: 8d9e0f1a-2b3c-4d4e-8f5a-6b7c8d9e0f1b + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + NeedMissingExpectedVersion: + summary: A change without expected_version + 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: 9e0f1a2b-3c4d-4e5f-9a6b-7c8d9e0f1a2c + errors: + - in: body + pointer: /expected_version + code: required + message: The value is required. + NeedConfirmedAfterUpdate: + summary: The need after the confirmation, as version 2 + description: Confirmed suggestions keep the origin extracted_from_text, their quotes, and extracted_in_version 1; the grade and the salary are manual. A confirmed requirement changed, so requirements_version is 2 as well. Kafka and the domain are still open suggestions; Kafka does not count in the recommendations, and Temporal stays without a taxonomy code, so no category covers it. The place is unknown but not critical, because the only format is remote. The range of 250000-320000 has a width of about 25%. Scores use the overlap 4/6, the money share rounded down to a quarter or the neutral 0.5, and the exact Supply of groups of five or more. The recommendation values are illustrative. + value: + id: 01928f7a-3c4d-7e5f-8a6b-7c8d9e0f1a23 + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + vacancy_id: null + title: Backend в команду платежей + source_text: 'Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно.' + version: 2 + requirements_version: 2 + requirements: + specialization: + status: confirmed + value: backend + source: + origin: extracted_from_text + quote: Ищем бэкенд-разработчика + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + grade: + status: confirmed + value: middle + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + required_skills: + - name: Go + taxonomy_code: go + status: confirmed + source: + origin: extracted_from_text + quote: 'Обязательно: Go, PostgreSQL и Temporal' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: PostgreSQL + taxonomy_code: postgresql + status: confirmed + source: + origin: extracted_from_text + quote: 'Обязательно: Go, PostgreSQL и Temporal' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + - name: Temporal + taxonomy_code: null + status: confirmed + source: + origin: extracted_from_text + quote: 'Обязательно: Go, PostgreSQL и Temporal' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + desired_skills: + - name: Kafka + taxonomy_code: kafka + status: extracted + source: + origin: extracted_from_text + quote: Желательно опыт с Kafka + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + tasks: + - text: Развивать сервис выплат и переводить его на событийную модель + status: extracted + source: + origin: extracted_from_text + quote: 'Задачи: развивать сервис выплат и переводить его на событийную модель' + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + domain: + status: extracted + value: платежи + source: + origin: extracted_from_text + quote: в команду платежей + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + work_formats: + status: confirmed + value: + - remote + source: + origin: extracted_from_text + quote: Работа удаленно + extracted_in_version: 1 + extraction_version: need-rules.2026-10.1 + location: + status: unknown + value: null + source: null + salary: + status: confirmed + value: + salary_from: 250000 + salary_to: 320000 + currency: RUB + period: month + tax_basis: gross + source: + origin: manual + quote: null + extracted_in_version: null + extraction_version: null + readiness: + status: complete + missing_fields: [] + recommendations: + status: computed + requirements_version: 2 + policy_version: 1 + algorithm_version: need-rec.2026-10.1 + computed_at: '2026-10-06T09:20:01Z' + categories: + - specialization: backend + grade: middle + score: 0.61 + skill_overlap: + share: 0.67 + covered_skills: + - Go + - PostgreSQL + uncovered_skills: + - Temporal + money: + status: computed + share: 0.25 + supply: 30_or_more + - specialization: devops_sre + grade: middle + score: 0.45 + skill_overlap: + share: 0.33 + covered_skills: + - PostgreSQL + uncovered_skills: + - Go + - Temporal + money: + status: insufficient_data + share: null + supply: from_5_to_29 + - specialization: backend + grade: senior + score: 0.41 + skill_overlap: + share: 0.67 + covered_skills: + - Go + - PostgreSQL + uncovered_skills: + - Temporal + money: + status: computed + share: 0 + supply: from_5_to_29 + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:20:00Z' + NeedUpdateConfirmSuggestions: + summary: Confirm suggestions, answer the missing fields, and keep two suggestions open + description: Sent over version 1 of NeedExtractedWithUnknownSkill. The specialization, the required skills, and the work format are sent with their stored values and status confirmed, so they are confirmed and keep their quotes. The grade and the salary are new manual values. Kafka and the domain are sent with status extracted and their stored values, so they stay open suggestions. The tasks are absent and stay unchanged. + value: + expected_version: 1 + specialization: + value: backend + status: confirmed + grade: + value: middle + status: confirmed + required_skills: + - name: Go + status: confirmed + - name: PostgreSQL + status: confirmed + - name: Temporal + status: confirmed + desired_skills: + - name: Kafka + status: extracted + domain: + value: платежи + status: extracted + work_formats: + value: + - remote + status: confirmed + salary: + value: + salary_from: 250000 + salary_to: 320000 + currency: RUB + period: month + tax_basis: gross + status: confirmed + NeedStaleVersion: + summary: The change carried a stale expected_version + description: Another member or a server-side extraction changed the need after the client read it. Nothing was changed; the client reads the need again and reapplies its unsaved edits. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 0f1a2b3c-4d5e-4f6a-8b7c-8d9e0f1a2b3d + SearchByNeed: + summary: Search against one confirmed requirements snapshot. + description: The reference is Need.requirements_version, not Need.version. + value: + need_id: 4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11 + requirements_version: 3 + filters: + specialization: backend + SearchByBank: + summary: Search the organization-visible bank with separate confirmed and declared filters. + value: + filters: + specialization: backend + confirmed_grade: middle + confirmed_category: + specialization: backend + grade: middle + confirmation_status: confirmed + declared_grade: junior + stack: + - go + - postgresql + conditions: + work_formats: + - remote + salary_compatibility: compatible + ThreeGroups: + summary: Synthetic example of main, near, and unconfirmed entries. + description: Illustrative contract values only; these are not measurements from real candidates. The same organization-scoped handle has independent Backend and Networks states. + value: + source: + kind: bank + filters: + specialization: null + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + specialization: backend + confirmation_status: confirmed + declared_grade: middle + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: standard + public_context: + stack: + - go + - postgresql + experience_band: '3_6' + work_formats: + - remote + salary_compatibility: compatible + evidence_summary: + - code: confirmed_category + state: supports + - code: required_skill_evidence + state: supports + - code: work_conditions_match + state: supports + semantic_evidence: [] + components: + fit: 0.78 + coverage: 0.72 + domain: 0.75 + semantics: 0.5 + percentile: 0.61 + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.65 + unknown_flags: [] + near: + - candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB + specialization: frontend + confirmation_status: confirmed + declared_grade: junior + category: + specialization: frontend + grade: junior + basis: synthetic_demo + strength: standard + public_context: + stack: + - docker + experience_band: null + work_formats: + - hybrid + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + - code: required_skill_evidence + state: gap + semantic_evidence: [] + components: + fit: 0.48 + coverage: 0.18 + domain: 0.5 + semantics: 0.5 + percentile: 0.42 + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.43 + unknown_flags: + - component: experience_band + reason: not_in_public_card + - component: salary_compatibility + reason: not_in_public_card + unconfirmed: + - candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + specialization: network_engineer + confirmation_status: unconfirmed + declared_grade: junior + category: null + strength: null + public_context: + stack: null + experience_band: '1_3' + work_formats: + - remote + salary_compatibility: compatible + evidence_summary: + - code: declared_grade + state: declared_only + - code: required_skill_evidence + state: partial + semantic_evidence: [] + components: + fit: 0.51 + coverage: 0.38 + unknown_flags: + - component: assessment + reason: no_confirmation_for_specialization + truncated: false + Empty: + summary: A valid search with no eligible visible candidates. + value: + source: + kind: bank + filters: + specialization: null + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: [] + near: [] + unconfirmed: [] + truncated: false + MLUnavailable: + summary: Semantic similarity uses the documented neutral value while ML is unavailable. + description: Synthetic example; 0.5 is the FR09 neutral value, not an inference. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC + specialization: backend + confirmation_status: confirmed + declared_grade: null + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: strong + public_context: + stack: + - go + experience_band: 3_plus + work_formats: + - remote + salary_compatibility: compatible + evidence_summary: + - code: confirmed_category + state: supports + semantic_evidence: [] + components: + fit: 0.7 + coverage: 0.6 + domain: 0.5 + semantics: 0.5 + percentile: 0.6 + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.61 + unknown_flags: + - component: semantics + reason: ml_unavailable + near: [] + unconfirmed: [] + truncated: false + CohortBelow30: + summary: A small comparison cohort has no published percentile. + description: Synthetic example; the exact cohort size is not disclosed. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD + specialization: backend + confirmation_status: confirmed + declared_grade: middle + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: standard + public_context: + stack: + - postgresql + experience_band: '3_6' + work_formats: + - office + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + semantic_evidence: [] + components: + fit: 0.62 + coverage: 0.55 + domain: 0.5 + semantics: 0.7 + percentile: null + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.56 + unknown_flags: + - component: percentile + reason: cohort_below_30 + near: [] + unconfirmed: [] + truncated: false + Truncated: + summary: The group limit or the card-view allowance cut the output. + description: Synthetic example. The entries returned are in rank order and already counted as card views; the flag carries no total. + value: + source: + kind: bank + filters: + specialization: backend + confirmed_grade: null + confirmed_category: null + confirmation_status: null + declared_grade: null + stack: null + conditions: null + groups: + main: + - candidate_handle: cv1_EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE + specialization: backend + confirmation_status: confirmed + declared_grade: null + category: + specialization: backend + grade: junior + basis: synthetic_demo + strength: standard + public_context: + stack: null + experience_band: null + work_formats: null + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + semantic_evidence: [] + components: + fit: 0.5 + coverage: 0.5 + domain: 0.5 + semantics: 0.5 + percentile: null + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.45125 + unknown_flags: + - component: semantics + reason: ml_unavailable + - component: percentile + reason: cohort_below_30 + near: [] + unconfirmed: [] + truncated: true + SemanticEvidence: + summary: A need search explains an entry with semantic evidence from published card items. + description: Synthetic example. `semantics` is the calibrated cosine of the stored vectors; each evidence item pairs one confirmed requirement of the need with the closest published card item. The project is named only by the title that the candidate published; the repository address never appears. + value: + source: + kind: need + need_id: 4d3a4a1b-4f60-44c1-9dc2-6c8e6c9d4c11 + requirements_version: 3 + groups: + main: + - candidate_handle: cv1_FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + specialization: backend + confirmation_status: confirmed + declared_grade: middle + category: + specialization: backend + grade: middle + basis: synthetic_demo + strength: standard + public_context: + stack: + - kafka + - postgresql + experience_band: '3_6' + work_formats: null + salary_compatibility: null + evidence_summary: + - code: confirmed_category + state: supports + - code: required_skill_evidence + state: declared_only + semantic_evidence: + - requirement_kind: task + requirement_text: Make payment callbacks idempotent + item_kind: project + project_title: Payment webhook deduplication service + repository_verified: true + similarity: high + - requirement_kind: required_skill + requirement_text: Kafka + item_kind: stack + project_title: null + repository_verified: false + similarity: medium + components: + fit: 0.69 + coverage: 0.25 + domain: 0.5 + semantics: 0.92 + percentile: null + competition: 0 + freshness: 0.5 + responsiveness: 0.5 + rank_score: 0.59 + unknown_flags: + - component: percentile + reason: cohort_below_30 + - component: freshness + reason: no_freshness_history + - component: responsiveness + reason: no_response_history + - component: work_formats + reason: not_in_public_card + - component: salary_compatibility + reason: not_in_public_card + - component: domain + reason: not_in_public_card + near: [] + unconfirmed: [] + truncated: false + OrganizationAnonymousCandidateCard: + summary: An anonymous card currently visible to one organization + description: The alias is scoped to the reading organization; no contact values are included. + value: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + categories: + - specialization: backend + grade: middle + strength: standard + basis: synthetic_demo + stack: + - postgresql + - kafka + self_assessment: null + experience_band: '1_3' + work_formats: null + salary_compatibility: null + projects: null + OrganizationCandidateEvidence: + summary: The one supporting assessment fact of the category on the card + value: + items: + - skill: backend + grade: junior + trust: 1 + basis: synthetic_demo + calibration_status: uncalibrated + observed_year: 2026 + OrganizationInvitationListPage: + summary: The last page of the invitations of an organization + description: The organization sees that the second invitation was declined, but not the reason or the comment. + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: '2026-10-13T09:30:00Z' + contact_access: + status: available + fields: + - email + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + candidate_handle: cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB + need: null + state: declined + expiry_reason: null + version: 4 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + response_deadline_at: '2026-10-08T10:00:00Z' + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-05T09:00:00Z' + updated_at: '2026-10-06T08:00:00Z' + page: + has_more: false + next_cursor: null + InvitationCreateFromNeed: + summary: A draft for a candidate from the search results of a need + description: 'Every term is present: net salary range, communication method, and each package condition, provided or explicitly not provided.' + value: + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + response_period_days: 7 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + OrganizationInvitationDraft: + summary: A new draft, version 1 with terms version 1 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 1 + terms_version: 1 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: not_provided + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + delivered_at: null + viewed_at: null + responded_at: null + InvitationWithoutTaxBasis: + summary: A salary range without its tax basis + description: The tax basis is a required field of SalaryRange; the pointer names the missing nested field. + 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: 1f2a3b4c-5d6e-4f7a-8b9c-0d1e2f3a4b5c + errors: + - in: body + pointer: /terms/salary/tax_basis + code: required + message: The value is required. + InvitationWithoutCommunicationMethod: + summary: Terms without the communication method + description: The communication method is a required term; the pointer names the missing nested field. + 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: 2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d + errors: + - in: body + pointer: /terms/communication_method + code: required + message: The value is required. + InvitationPackageItemMissing: + summary: A package without the training condition + description: 'Not providing a condition is the explicit item {status: not_provided}; leaving it out is a missing required field.' + 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: 3b4c5d6e-7f8a-4b9c-8d0e-2f3a4b5c6d7e + errors: + - in: body + pointer: /terms/package/training + code: required + message: The value is required. + InvitationSalaryRangeTooWide: + summary: A salary range wider than 40% of its midpoint + 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: 4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f + errors: + - in: body + pointer: /terms/salary/salary_to + code: invalid + message: The value does not match the contract. + InvitationLocationRequired: + summary: The hybrid format without a place of work + 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-4b5c6d7e8f9a + errors: + - in: body + pointer: /terms/location + code: invalid + message: The value does not match the contract. + InvitationUnknownCandidate: + summary: A candidate handle that this organization cannot use + description: An unknown handle, a handle of another organization, and a profile that is no longer visible to the organization get the same answer. + 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: 6e7f8a9b-0c1d-4e2f-9a3b-5c6d7e8f9a0b + errors: + - in: body + pointer: /candidate_handle + code: invalid + message: The value does not match the contract. + InvitationCandidateDataInBody: + summary: The request carried a candidate's email address or salary minimum + description: Contacts and minimums are never request fields; any unknown field fails validation, and an unknown top-level field such as candidate_email points at the whole body. + 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: 7f8a9b0c-1d2e-4f3a-8b4c-6d7e8f9a0b1c + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + OrganizationInvitationDelivered: + summary: The invitation in the candidate's inbox with a seven-day deadline + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: null + responded_at: null + OrganizationInvitationAccepted: + summary: 'The accepted invitation: the email address is readable through the contacts operation' + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: true + salary_fit: within_range + contact_access: + status: available + fields: + - email + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + InvitationUpdateTerms: + summary: The draft gets the training condition; the terms are sent complete + value: + expected_version: 1 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + OrganizationInvitationDraftUpdated: + summary: The draft after the terms change, version 2 with terms version 2 + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: draft + expiry_reason: null + version: 2 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: null + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:20:00Z' + delivered_at: null + viewed_at: null + responded_at: null + InvitationStaleTerms: + summary: The acceptance named a terms version that is no longer current + description: The organization raised the salary after the candidate read the terms. Nothing changed and no consent or grant was recorded; the client reads the invitation again and shows the new terms for a new decision. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 1d2e3f4a-5b6c-4d7e-8f8a-0b1c2d3e4f5a + InvitationStaleVersion: + summary: The command carried a stale expected_version + description: The invitation changed after the client read it. Nothing changed; the client reads the invitation again. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 2e3f4a5b-6c7d-4e8f-9a9b-1c2d3e4f5a6b + InvitationSendCommand: + summary: Send the draft that the client read as version 2 + value: + expected_version: 2 + InvitationNotAnswerable: + summary: The invitation no longer accepts an answer + description: For example, it was withdrawn, it expired, or the deadline has passed. + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 3f4a5b6c-7d8e-4f9a-8b0c-2d3e4f5a6b7c + InvitationSalaryRaiseUsed: + summary: The upper bound of this invitation was already raised once + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 4a5b6c7d-8e9f-4a0b-9c1d-3e4f5a6b7c8d + InvitationSendBlocked: + summary: The send is blocked by the pending limit of the need or the pause after a decline + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5b6c7d8e-9f0a-4b1c-8d2e-4f5a6b7c8d9e + InvitationSalaryRaiseCommand: + summary: The one raise of the upper bound from 260000 to 280000 net + value: + expected_version: 4 + salary_to: 280000 + OrganizationInvitationSalaryRaised: + summary: 'The viewed invitation after the one raise of the upper bound: terms version 3' + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: viewed + expiry_reason: null + version: 5 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: true + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T14:00:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: null + InvitationWithdrawCommand: + summary: Withdraw the invitation that the client read as version 3 + value: + expected_version: 3 + OrganizationInvitationWithdrawn: + summary: The invitation withdrawn by the organization before an answer + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + candidate_handle: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + need: + need_id: 01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12 + requirements_version: 3 + state: withdrawn + expiry_reason: null + version: 4 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_period_days: 7 + response_deadline_at: '2026-10-13T09:30:00Z' + salary_raise_used: false + salary_fit: within_range + contact_access: + status: not_granted + fields: [] + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T11:00:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: null + responded_at: null + InvitationContactsEmailOnly: + summary: Synthetic contacts through a grant that covers only the email address + description: Every field the grant does not cover is null. The values are synthetic. + value: + invitation_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + grant_id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + granted_at: '2026-10-06T15:00:00Z' + full_name: null + email: candidate@example.com + phone: null + telegram: null + CandidateInvitationListPage: + summary: The last page of the candidate's inbox + value: + items: + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + updated_at: '2026-10-06T12:00:00Z' + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: expired + expiry_reason: invitation_timeout + version: 3 + terms_version: 1 + role_title: Middle Go-разработчик в команду платежей + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + work_formats: + - remote + - hybrid + response_deadline_at: '2026-10-04T10:00:00Z' + delivered_at: '2026-10-01T10:00:00Z' + viewed_at: null + updated_at: '2026-10-04T10:00:00Z' + page: + has_more: false + next_cursor: null + CandidateInvitationDelivered: + summary: The delivered invitation as GetMyInvitation reads it, before a view is recorded + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: delivered + expiry_reason: null + version: 3 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: null + responded_at: null + updated_at: '2026-10-06T09:30:00Z' + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null + CandidateInvitationViewed: + summary: The terms after ViewMyInvitation, with the C4 choice and no contact + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: viewed + expiry_reason: null + version: 4 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: null + updated_at: '2026-10-06T12:00:00Z' + contact_consent: + text: + text_version: c4-2026-10-01 + text: Я разрешаю передать ООО Пример Платежи выбранные мной контактные данные для связи по этому приглашению. Согласие можно отозвать в любой момент в разделе согласий. + available_fields: + - full_name + - email + - phone + decline: null + contact_grant: null + CandidateInvitationAccepted: + summary: The accepted invitation with the grant for the email address only + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: active + readable: true + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: '2026-10-06T15:00:00Z' + revoked_at: null + revocation_reason: null + CandidateInvitationDeclined: + summary: The declined invitation with the candidate's own reason + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: declined + expiry_reason: null + version: 5 + terms_version: 2 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 260000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T16:00:00Z' + updated_at: '2026-10-06T16:00:00Z' + contact_consent: null + decline: + reason: other + comment: null + declined_at: '2026-10-06T16:00:00Z' + contact_grant: null + InvitationAcceptEmailOnly: + summary: Accept terms version 3 and disclose only the email address + value: + expected_version: 5 + terms_version: 3 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email + InvitationAcceptStaleTerms: + summary: Accept terms version 2 after the organization raised the salary + description: The candidate read version 4 with terms version 2; the raise made version 5 with terms version 3, so the server answers 412. + value: + expected_version: 4 + terms_version: 2 + consent_c4: + text_version: c4-2026-10-01 + accepted: true + fields: + - email + - phone + CandidateInvitationAcceptedVisibilityBlocked: + summary: 'Accepted while the profile is hidden from the organization: the grant is active but not readable' + description: The acceptance never lifts the hiding or publishes the profile. The organization sees contact_access closed without the reason. + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: accepted + expiry_reason: null + version: 6 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + updated_at: '2026-10-06T15:00:00Z' + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: active + readable: false + blocked_by: visibility + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: '2026-10-06T15:00:00Z' + revoked_at: null + revocation_reason: null + InvitationConsentWithoutFields: + summary: An acceptance with an empty choice of contact fields + 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: 8a9b0c1d-2e3f-4a4b-9c5d-7e8f9a0b1c2d + errors: + - in: body + pointer: /consent_c4/fields + code: invalid + message: The value does not match the contract. + InvitationConsentTextOutdated: + summary: An acceptance of a C4 text version that is no longer published + 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-8f9a0b1c2d3e + errors: + - in: body + pointer: /consent_c4/text_version + code: invalid + message: The value does not match the contract. + InvitationMissingTermsVersion: + summary: An acceptance without terms_version + 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: 0c1d2e3f-4a5b-4c6d-9e7f-9a0b1c2d3e4f + errors: + - in: body + pointer: /terms_version + code: required + message: The value is required. + InvitationDeclineOther: + summary: Decline with the neutral reason other and no comment + value: + expected_version: 4 + reason: other + InvitationDeclineWithComment: + summary: Decline with a reason and an optional comment + value: + expected_version: 4 + reason: work_format + comment: Ищу только полностью удаленную работу. + InvitationCancelCommand: + summary: Cancel the participation after the acceptance + value: + expected_version: 6 + CandidateInvitationCancelled: + summary: The participation cancelled after the acceptance; the grant of this invitation is revoked + value: + id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + state: cancelled_by_candidate + expiry_reason: null + version: 7 + terms_version: 3 + terms: + role_title: Middle Go-разработчик в команду платежей + specialization: backend + grade: middle + offer_type: full_time + tasks: + - Развивать сервис выплат на Go + - Перевести расчет комиссий на событийную модель + team: 'Команда платежей: пять бэкенд-разработчиков, QA-инженер и продакт-менеджер. Код-ревью для каждого изменения, дежурства по графику раз в шесть недель.' + tech_stack: + - Go + - PostgreSQL + - Kafka + work_formats: + - remote + - hybrid + location: Москва + communication_method: + channel: email + details: Письмо от тимлида с предложением созвона в течение трех рабочих дней + salary: + salary_from: 200000 + salary_to: 280000 + currency: RUB + period: month + tax_basis: net + package: + bonus: + status: provided + description: Годовой бонус до 15% оклада + equipment: + status: provided + description: Ноутбук и монитор на выбор + training: + status: provided + description: Конференции и курсы до 100000 рублей в год + health_insurance: + status: provided + description: ДМС со стоматологией после испытательного срока + response_deadline_at: '2026-10-13T09:30:00Z' + delivered_at: '2026-10-06T09:30:00Z' + viewed_at: '2026-10-06T12:00:00Z' + responded_at: '2026-10-06T15:00:00Z' + updated_at: '2026-10-07T10:00:00Z' + contact_consent: null + decline: null + contact_grant: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + fields: + - email + status: revoked + readable: false + blocked_by: null + terms_version: 3 + consent_text_version: c4-2026-10-01 + granted_at: '2026-10-06T15:00:00Z' + revoked_at: '2026-10-07T10:00:00Z' + revocation_reason: participation_cancelled + NotificationListPage: + summary: An unread notice and a read one whose source is no longer visible + value: + items: + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: '2026-10-09T08:30:00Z' + read_at: null + content: + title: Тестовое уведомление + summary: Организация «Север» отправила проверочное уведомление платформы. Оно создано для проверки доставки и не требует действий. + link_path: null + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f6f + kind: synthetic + organization_id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + delivered_at: '2026-10-08T17:05:00Z' + read_at: '2026-10-08T17:10:00Z' + content: null + page: + has_more: false + next_cursor: null + NotificationReadReceipt: + summary: The first read time of an item + value: + id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + read_at: '2026-10-09T08:45:00Z' + ConsentRecordListPage: + summary: The whole consent history of a candidate on one page + description: C1 was accepted at registration and again for a newer text version, so the first record is superseded; the version c1-2026-10-05 is an illustration, since the migration publishes only c1-2026-10-01 so far. C2 was granted and revoked. C4 was given in the acceptance of one invitation with the email only; the organization name is the one the consent text showed. + value: + items: + - id: 01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80 + purpose: c4 + state: active + text_version: c4-2026-10-01 + source: invitation_acceptance + granted_at: '2026-10-06T10:15:00Z' + revoked_at: null + revocation_source: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + fields: + - email + invitation_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e6f + invitation_terms_version: 3 + - id: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70 + purpose: c1 + state: active + text_version: c1-2026-10-05 + source: consent_settings + granted_at: '2026-10-05T12:00:00Z' + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + purpose: c2 + state: revoked + text_version: c2-2026-10-01 + source: consent_settings + granted_at: '2026-10-02T09:00:00Z' + revoked_at: '2026-10-04T18:30:00Z' + revocation_source: consent_settings + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + - id: 01928f7a-6f7a-7b8c-9d0e-1f2a3b4c5d50 + purpose: c1 + state: superseded + text_version: c1-2026-10-01 + source: registration + granted_at: '2026-10-01T08:00:00Z' + revoked_at: null + revocation_source: null + organization: null + fields: null + invitation_id: null + invitation_terms_version: null + page: + has_more: false + next_cursor: null + NewCandidatePrivacySettings: + summary: A new candidate with the profile closed + description: Nothing was ever published, announced, or hidden. Every version is 0. + value: + publication: + state: closed + closed_reason: never_published + fields: [] + consent_id: null + published_at: null + version: 0 + search_status: + value: not_looking + lapsed: false + confirmed_at: null + lapses_at: null + version: 0 + hidden_organizations_total: 0 + PublishedCandidatePrivacySettings: + summary: A published profile with a confirmed search status + value: + publication: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: '2026-10-06T09:10:00Z' + version: 1 + search_status: + value: looking + lapsed: false + confirmed_at: '2026-10-06T09:12:00Z' + lapses_at: '2026-11-05T09:12:00Z' + version: 1 + hidden_organizations_total: 1 + PublicationUpdatePublish: + summary: Publish the confirmed categories and the stack + value: + expected_version: 0 + state: published + fields: + - categories + - stack + PublicationUpdateClose: + summary: Close the publication + value: + expected_version: 1 + state: closed + fields: [] + PublishedPublication: + summary: The publication after the first publish + value: + state: published + closed_reason: null + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + published_at: '2026-10-06T09:10:00Z' + version: 1 + PrivacyPublishedWithoutFields: + summary: A publication without any field + 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: 3b4c5d6e-7f80-4a91-8b2c-3d4e5f6a7b8c + errors: + - in: body + pointer: /fields + code: invalid + message: A published profile needs at least one field, and a closed one none. + PublicationConsentRequiredConflict: + summary: Publishing without an active C2 consent + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 5d6e7f80-91a2-4cb3-8d4e-5f6a7b8c9d0e + errors: + - in: body + pointer: /state + code: consent_required + message: Publishing needs an active C2 consent of the account. + PrivacyStaleVersion: + summary: The change carried a stale expected_version + description: The setting changed, for example in another tab, after the client read it. Nothing was changed; the client reads the settings again and reapplies its edit. + value: + type: urn:lincodex:problem:version_conflict + title: Resource version conflict + status: 412 + code: version_conflict + detail: The resource changed after it was read. Read it again before retrying. + trace_id: 4c5d6e7f-8091-4ba2-9c3d-4e5f6a7b8c9d + PublishedCardPreview: + summary: The card of a published profile with two fields + description: The fields that are not published are null. The card carries no name and no contact. + value: + state: published + fields: + - categories + - stack + card: + pseudonym: cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + categories: + - specialization: backend + grade: middle + strength: standard + basis: synthetic_demo + stack: + - postgresql + - kafka + self_assessment: null + experience_band: '1_3' + work_formats: null + salary_compatibility: null + projects: null + evidence: + items: + - skill: backend + grade: middle + trust: 1 + basis: synthetic_demo + calibration_status: uncalibrated + observed_year: 2026 + generated_at: '2026-10-06T09:30:00Z' + ClosedCardPreview: + summary: The preview of a closed profile + value: + state: closed + fields: [] + card: null + evidence: null + generated_at: '2026-10-06T09:30:00Z' + SearchStatusUpdateLooking: + summary: Set or confirm the status looking + value: + expected_version: 0 + value: looking + LookingSearchStatus: + summary: A confirmed status that lapses after the policy interval + value: + value: looking + lapsed: false + confirmed_at: '2026-10-06T09:12:00Z' + lapses_at: '2026-11-05T09:12:00Z' + version: 1 + LapsedSearchStatus: + summary: A status that was not confirmed in time + description: The candidate set looking and did not confirm it again, so it holds as not_looking. Nothing else changed; the publication and the hidden organizations are as they were. + value: + value: not_looking + lapsed: true + confirmed_at: '2026-10-06T09:12:00Z' + lapses_at: '2026-11-05T09:12:00Z' + version: 1 + HiddenOrganizationListPage: + summary: One hidden organization + value: + items: + - organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: '2026-10-06T09:20:00Z' + page: + has_more: false + next_cursor: null + HiddenOrganizationRecord: + summary: An organization that the candidate hides the profile from + value: + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + hidden_at: '2026-10-06T09:20:00Z' + HiddenOrganizationLimitReached: + summary: The candidate hides the maximum number of organizations + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 6e7f8091-a2b3-4dc4-9e5f-6a7b8c9d0e1f + errors: + - in: path + pointer: /org_id + code: limit_reached + message: The candidate already hides the maximum number of organizations. + PrivacyEventListPage: + summary: A publication, a hiding, and a confirmed status + value: + items: + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9f01 + kind: organization_hidden + occurred_at: '2026-10-06T09:20:00Z' + fields: null + consent_id: null + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e02 + kind: search_status_confirmed + occurred_at: '2026-10-06T09:12:00Z' + fields: null + consent_id: null + organization: null + - id: 01928f7a-b1c2-7d3e-8f4a-5b6c7d8e9e01 + kind: publication_opened + occurred_at: '2026-10-06T09:10:00Z' + fields: + - categories + - stack + consent_id: 01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60 + organization: null + page: + has_more: false + next_cursor: null + CardAccessListPage: + summary: An anonymous view and a contact read + value: + items: + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a02 + kind: contact_read + occurred_at: '2026-10-07T08:00:00Z' + organization: + id: 01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01 + name: ООО Пример Платежи + - id: 01928f7a-c1d2-7e3f-8a4b-5c6d7e8f9a01 + kind: card_viewed + occurred_at: '2026-10-06T12:00:00Z' + organization: null + page: + has_more: false + next_cursor: null + EvidenceFactListPage: + summary: A confirmed junior backend result with one fact and two tags of the same event + value: + items: + - id: 01928f7a-d1e2-7f3a-8b4c-5d6e7f8a9b01 + kind: measurement + source: + type: assessment_result + event_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01 + result_id: 01928f7a-e1f2-7a3b-8c4d-5e6f7a8b9c01 + skills: + - backend + - go + result: + grade: junior + basis: synthetic_demo + calibration_status: uncalibrated + attribution: personal + trust: 1 + occurred_at: '2026-10-08T10:15:00Z' + visibility: visible + page: + has_more: false + next_cursor: null + SupportCaseListPage: + summary: The last page of the case summaries of the current account + value: + items: + - id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + object: null + assessment_target: + specialization: backend + grade: middle + response_target: + kind: operational_goal + business_days: 5 + due_at: '2026-10-13T09:00:00Z' + answered_at: null + late: false + policy_version: 1 + decision_outcome: null + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + - id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + response_target: + kind: operational_goal + business_days: 10 + due_at: '2026-10-15T10:00:00Z' + answered_at: '2026-10-09T14:30:00Z' + late: false + policy_version: 1 + decision_outcome: not_upheld + created_at: '2026-10-01T10:00:00Z' + updated_at: '2026-10-09T14:30:00Z' + - id: 01928f7a-4c5d-7e6f-8a9b-0c1d2e3f4a5b + number: SC-2026-000088 + type: support + status: in_review + object: null + assessment_target: + specialization: backend + grade: senior + response_target: + kind: operational_goal + business_days: 3 + due_at: '2026-10-02T12:00:00Z' + answered_at: '2026-10-01T09:20:00Z' + late: false + policy_version: 1 + decision_outcome: null + created_at: '2026-09-29T12:00:00Z' + updated_at: '2026-10-01T09:20:00Z' + page: + has_more: false + next_cursor: null + SupportCaseCreateManualAssessment: + summary: A manual assessment of a category instead of the automated one + value: + type: manual_assessment + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + assessment_target: + specialization: backend + grade: middle + SupportCaseCreateGradeAppeal: + summary: An appeal of the result of an own attempt + value: + type: grade_appeal + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + SupportCaseCreateCategoryAppeal: + summary: An appeal of a category that a manual assessment assigned + description: The category came from an expert without an attempt, so the appeal references the resolved manual assessment case. + value: + type: grade_appeal + description: Эксперт подтвердил Junior, но в рубрике Middle я выполнил все обязательные пункты. Прошу пересмотреть. + object: + type: support_case + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + SupportCaseCreateTestUnavailable: + summary: A support case about a test that is not available + value: + type: support + description: Тест на Senior пока недоступен, хотя я сдал Middle полгода назад. + assessment_target: + specialization: backend + grade: senior + SupportCaseCreateComplaint: + summary: A complaint about the salary terms of an offer + value: + type: complaint + description: После принятия приглашения компания предложила сумму ниже указанной вилки. + complaint_reason: salary_terms_violation + object: + type: invitation + id: 01928f7a-7f8a-7b9c-8d0e-1f2a3b4c5d6e + SupportCaseManualAssessmentCreated: + summary: A new manual assessment request with its rubric and response target + description: The server moves the case to waiting_expert in the same transaction as the creation, so the 201 already shows both events. + value: + id: 01928f7a-6e7f-7a8b-9c0d-1e2f3a4b5c6d + number: SC-2026-000123 + type: manual_assessment + status: waiting_expert + description: Прошу провести ручную оценку по рубрике Backend Middle вместо автоматической категоризации. + object: null + assessment_target: + specialization: backend + grade: middle + complaint_reason: null + rubric_version: 3 + response_target: + kind: operational_goal + business_days: 5 + due_at: '2026-10-13T09:00:00Z' + answered_at: null + late: false + policy_version: 1 + decision: null + history: + - sequence: 1 + kind: created + actor: user + occurred_at: '2026-10-06T09:00:00Z' + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: '2026-10-06T09:00:00Z' + status: waiting_expert + message: null + created_at: '2026-10-06T09:00:00Z' + updated_at: '2026-10-06T09:00:00Z' + SupportCaseBlankDescription: + summary: The description is empty or contains only whitespace + 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: 5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d + errors: + - in: body + pointer: /description + code: invalid + message: The value does not match the contract. + SupportCaseUnknownType: + summary: The case type is not one of the five types + description: An unknown discriminator of the top-level oneOf concerns the whole body, so the pointer is empty. + 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: 6b7c8d9e-0f1a-4b2c-9d3e-4f5a6b7c8d9e + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + SupportCaseUnknownField: + summary: The client sent its own status or decision + description: Status, decision, moderator, priority, and response target are never request fields; any unknown field fails validation, and an unknown top-level field points at the whole body. + 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: 7c8d9e0f-1a2b-4c3d-8e4f-5a6b7c8d9e0f + errors: + - in: body + pointer: '' + code: invalid + message: The value does not match the contract. + SupportCaseMalformedReference: + summary: The object identifier is not a UUID + description: The decoder rejects the identifier inside the selected variant, and the pointer names it. + 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: 0f1a2b3c-4d5e-4f6a-9b7c-8d9e0f1a2b3c + errors: + - in: body + pointer: /object/id + code: invalid + message: The value does not match the contract. + SupportCaseComplaintNeedsInvitation: + summary: The complaint reason requires an invitation reference + 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: 8d9e0f1a-2b3c-4d4e-9f5a-6b7c8d9e0f1a + errors: + - in: body + pointer: /object/type + code: invalid + message: The value does not match the contract. + SupportCaseAppealExists: + summary: The attempt or the manual assessment already has an appeal of this type + value: + type: urn:lincodex:problem:state_conflict + title: Resource state conflict + status: 409 + code: state_conflict + detail: The resource is in a state that does not allow this operation. + trace_id: 9e0f1a2b-3c4d-4e5f-8a6b-7c8d9e0f1a2b + SupportCaseGradeAppealResolved: + summary: An own grade appeal with a public decision + value: + id: 01928f7a-5d6e-7f8a-9b0c-1d2e3f4a5b6c + number: SC-2026-000097 + type: grade_appeal + status: resolved + description: Практика не засчитана, хотя решение проходит публичные примеры. Прошу пересмотреть результат. + object: + type: assessment_attempt + id: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b + assessment_target: null + complaint_reason: null + rubric_version: null + response_target: + kind: operational_goal + business_days: 10 + due_at: '2026-10-15T10:00:00Z' + answered_at: '2026-10-09T14:30:00Z' + late: false + policy_version: 1 + decision: + outcome: not_upheld + reason: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + decided_at: '2026-10-09T14:30:00Z' + history: + - sequence: 1 + kind: created + actor: user + occurred_at: '2026-10-01T10:00:00Z' + status: submitted + message: null + - sequence: 2 + kind: status_changed + actor: system + occurred_at: '2026-10-01T10:00:00Z' + status: waiting_expert + message: null + - sequence: 3 + kind: status_changed + actor: support + occurred_at: '2026-10-07T08:15:00Z' + status: in_review + message: null + - sequence: 4 + kind: decision + actor: support + occurred_at: '2026-10-09T14:30:00Z' + status: resolved + message: Решение не проходит вторую группу скрытых проверок на пустом входе. Исходный результат остается в силе; повторная попытка на тот же грейд откроется по обычным правилам. + created_at: '2026-10-01T10:00:00Z' + updated_at: '2026-10-09T14:30:00Z' + PreconditionRequired: + summary: The operation requires If-Match + value: + type: urn:lincodex:problem:precondition_required + title: Precondition required + status: 428 + code: precondition_required + detail: Send If-Match with the ETag of the version you read. + trace_id: 5a6b7c8d-9e0f-4a1b-8c2d-4e5f6a7b8c9d diff --git a/api/core/openapi.yml b/api/core/openapi.yml index 0b97e09..054f39b 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -4,6 +4,1134 @@ 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. + - name: catalog + description: >- + Public reference data: directions, specializations with their + assessment availability, and the grade scale. + - name: candidate + description: >- + Data of the current candidate: the questionnaire with the chosen + specializations and self-assessed grades, and the private profile + with full name, contacts, stack, roles, experience, soft skills, and + desired terms. Confirmed grades and categories come only from + assessment results. + - name: assessment + description: >- + Assessment attempts of the current candidate: availability, start and + resume, answers and the code practice, finalization, and the result. + Answers, keys, and attempt history are visible only to the candidate. + - name: organization + description: >- + Organizations of employer accounts: the profile with its contacts and + representatives, the verification level that only the server sets, and + the memberships that give an account its role in an organization. The + organization in the path is authoritative and is checked against an + active membership on every request; no body carries a role, a + membership, or a verification level. + - name: need + description: >- + Hiring needs of an organization: requirements with their confirmation + state and provenance, immutable versions, readiness, and category + recommendations. Access comes only from an active membership in the + organization; a need never requires a vacancy. + - name: invitation + description: >- + Invitations from an organization to one candidate: drafts with + complete terms, immutable terms versions, sending, the candidate's + inbox, acceptance with the consent C4, structured declines, + withdrawal and cancellation, and the contact grant. Contacts are + readable only through an active grant, in a response separate from + the terms. + - name: privacy + description: >- + Visibility of the current candidate: the publication of the anonymous + card (a setting that refers to the C2 consent of the ledger and never + replaces it), the search status that is not a consent, the + organizations that the candidate hides the profile from, the preview + of the card, and the history of the settings and of the accesses. + Everything is closed by default, and no change makes a candidate more + visible than they chose. No schema here reaches a contact, a name, or + the lowest salary. + - name: evidence + description: >- + Skill evidence derived from confirmed assessment results: one fact per + source event with its skills, trust level, attribution, date, and + visibility. The candidate reads their own facts; an organization reads + only the permitted projection of a currently visible card. Raw + answers, failures, and anti-cheat data are never part of it. + - name: notification + description: >- + The in-platform inbox of the current account: references to delivered + events with a read state, in the candidate cabinet and in the cabinet of + one organization. The inbox is the source of the delivery state inside + the platform and never depends on email. It stores no text: the content + of every item is resolved from the current source for the recipient on + each read, and an item whose source is gone or no longer visible stays + in the list without content. + - name: consent + description: >- + The consent ledger of the current account: the independent consents + C1-C5 with their text versions, sources, states, and revocations. The + ledger is append-only and returns only the caller's own records. + - name: support + description: >- + Support cases of the current account: questions, complaints, appeals + of a grade or an anti-cheat decision, and manual assessment requests. + The author sees the number, the status, the response target, the + decision, and the public history; moderators and internal notes stay + hidden. +# 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/me/consent-texts/{purpose}: + $ref: ./routes/my_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/email-verifications/code: + $ref: ./routes/identity_email_verification_codes.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 + /api/v1/specializations: + $ref: ./routes/catalog_specializations.yml + /api/v1/me/questionnaire: + $ref: ./routes/candidate_questionnaire.yml + /api/v1/me/profile: + $ref: ./routes/candidate_profile.yml + /api/v1/me/profile/repository-checks: + $ref: ./routes/candidate_profile_repository_checks.yml + /api/v1/me/assessment-availability: + $ref: ./routes/candidate_assessment_availability.yml + /api/v1/me/assessment-results: + $ref: ./routes/candidate_assessment_results.yml + /api/v1/me/assessment-signal-notice: + $ref: ./routes/candidate_assessment_signal_notice.yml + /api/v1/me/assessment-attempts: + $ref: ./routes/candidate_assessment_attempts.yml + /api/v1/me/assessment-attempts/{attempt_id}: + $ref: ./routes/candidate_assessment_attempt.yml + /api/v1/me/assessment-attempts/{attempt_id}/sessions: + $ref: ./routes/candidate_assessment_attempt_sessions.yml + /api/v1/me/assessment-attempts/{attempt_id}/signals: + $ref: ./routes/candidate_assessment_signals.yml + /api/v1/me/assessment-attempts/{attempt_id}/work-session: + $ref: ./routes/candidate_assessment_attempt_work_session.yml + /api/v1/me/assessment-attempts/{attempt_id}/answers: + $ref: ./routes/candidate_assessment_attempt_answers.yml + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs: + $ref: ./routes/candidate_assessment_attempt_practice_runs.yml + /api/v1/me/assessment-attempts/{attempt_id}/practice-runs/{run_id}: + $ref: ./routes/candidate_assessment_attempt_practice_run.yml + /api/v1/me/assessment-attempts/{attempt_id}/finalize: + $ref: ./routes/candidate_assessment_attempt_finalize.yml + /api/v1/me/assessment-attempts/{attempt_id}/result: + $ref: ./routes/candidate_assessment_attempt_result.yml + /api/v1/me/organizations: + $ref: ./routes/my_organizations.yml + /api/v1/organizations: + $ref: ./routes/organizations.yml + /api/v1/organizations/{org_id}: + $ref: ./routes/organization.yml + /api/v1/organizations/{org_id}/needs: + $ref: ./routes/organization_needs.yml + /api/v1/organizations/{org_id}/needs/{need_id}: + $ref: ./routes/organization_need.yml + /api/v1/organizations/{org_id}/matches: + $ref: ./routes/matches.yml + /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}: + $ref: ./routes/organization_candidate_card.yml + /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}/evidence: + $ref: ./routes/organization_candidate_card_evidence.yml + /api/v1/organizations/{org_id}/invitations: + $ref: ./routes/organization_invitations.yml + /api/v1/organizations/{org_id}/invitations/{invitation_id}: + $ref: ./routes/organization_invitation.yml + /api/v1/organizations/{org_id}/invitations/{invitation_id}/send: + $ref: ./routes/organization_invitation_send.yml + /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise: + $ref: ./routes/organization_invitation_salary_raise.yml + /api/v1/organizations/{org_id}/invitations/{invitation_id}/withdraw: + $ref: ./routes/organization_invitation_withdraw.yml + /api/v1/organizations/{org_id}/invitations/{invitation_id}/contacts: + $ref: ./routes/organization_invitation_contacts.yml + /api/v1/me/invitations: + $ref: ./routes/candidate_invitations.yml + /api/v1/me/invitations/{invitation_id}: + $ref: ./routes/candidate_invitation.yml + /api/v1/me/invitations/{invitation_id}/view: + $ref: ./routes/candidate_invitation_view.yml + /api/v1/me/invitations/{invitation_id}/accept: + $ref: ./routes/candidate_invitation_accept.yml + /api/v1/me/invitations/{invitation_id}/decline: + $ref: ./routes/candidate_invitation_decline.yml + /api/v1/me/invitations/{invitation_id}/cancel: + $ref: ./routes/candidate_invitation_cancel.yml + /api/v1/me/notifications: + $ref: ./routes/candidate_notifications.yml + /api/v1/me/notifications/{notification_id}/read: + $ref: ./routes/candidate_notification_read.yml + /api/v1/organizations/{org_id}/notifications: + $ref: ./routes/organization_notifications.yml + /api/v1/organizations/{org_id}/notifications/{notification_id}/read: + $ref: ./routes/organization_notification_read.yml + /api/v1/me/consents: + $ref: ./routes/consents.yml + /api/v1/me/consents/{purpose}: + $ref: ./routes/my_consent.yml + /api/v1/me/consents/c4/organizations/{org_id}: + $ref: ./routes/my_consent_c4.yml + /api/v1/me/account-deletion-requests: + $ref: ./routes/account_deletion_requests.yml + /api/v1/me/privacy: + $ref: ./routes/candidate_privacy.yml + /api/v1/me/privacy/publication: + $ref: ./routes/candidate_privacy_publication.yml + /api/v1/me/privacy/preview: + $ref: ./routes/candidate_privacy_preview.yml + /api/v1/me/privacy/search-status: + $ref: ./routes/candidate_privacy_search_status.yml + /api/v1/me/privacy/hidden-organizations: + $ref: ./routes/candidate_privacy_hidden_organizations.yml + /api/v1/me/privacy/hidden-organizations/{org_id}: + $ref: ./routes/candidate_privacy_hidden_organization.yml + /api/v1/me/privacy/history: + $ref: ./routes/candidate_privacy_history.yml + /api/v1/me/privacy/access-history: + $ref: ./routes/candidate_privacy_access_history.yml + /api/v1/me/evidence: + $ref: ./routes/candidate_evidence.yml + /api/v1/me/support-cases: + $ref: ./routes/support_cases.yml + /api/v1/me/support-cases/{case_id}: + $ref: ./routes/support_case.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs: + $ref: ./routes/candidate_assessment_attempt_labs.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}: + $ref: ./routes/candidate_assessment_attempt_lab.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/console-sessions: + $ref: ./routes/candidate_assessment_attempt_lab_console_sessions.yml + /api/v1/me/assessment-attempts/{attempt_id}/labs/{lab_id}/submission: + $ref: ./routes/candidate_assessment_attempt_lab_submission.yml +components: + schemas: + Problem: + $ref: ./components/schemas.yml#/Problem + ProblemCode: + $ref: ./components/schemas.yml#/ProblemCode + ProblemFieldError: + $ref: ./components/schemas.yml#/ProblemFieldError + ProblemFieldLocation: + $ref: ./components/schemas.yml#/ProblemFieldLocation + Timestamp: + $ref: ./components/schemas.yml#/Timestamp + PageInfo: + $ref: ./components/schemas.yml#/PageInfo + 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 + ConsentSettingsPurpose: + $ref: ./components/schemas.yml#/ConsentSettingsPurpose + ConsentSettingsRevokePurpose: + $ref: ./components/schemas.yml#/ConsentSettingsRevokePurpose + 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 + DirectionCode: + $ref: ./components/schemas.yml#/DirectionCode + SpecializationCode: + $ref: ./components/schemas.yml#/SpecializationCode + GradeCode: + $ref: ./components/schemas.yml#/GradeCode + TaskLanguage: + $ref: ./components/schemas.yml#/TaskLanguage + TestAvailabilityStatus: + $ref: ./components/schemas.yml#/TestAvailabilityStatus + TestAvailability: + $ref: ./components/schemas.yml#/TestAvailability + CatalogSpecialization: + $ref: ./components/schemas.yml#/CatalogSpecialization + CatalogDirection: + $ref: ./components/schemas.yml#/CatalogDirection + CatalogGrade: + $ref: ./components/schemas.yml#/CatalogGrade + SpecializationCatalog: + $ref: ./components/schemas.yml#/SpecializationCatalog + QuestionnaireVersion: + $ref: ./components/schemas.yml#/QuestionnaireVersion + StackTag: + $ref: ./components/schemas.yml#/StackTag + WorkFormat: + $ref: ./components/schemas.yml#/WorkFormat + WorkContext: + $ref: ./components/schemas.yml#/WorkContext + CandidateExperience: + $ref: ./components/schemas.yml#/CandidateExperience + QuestionnaireSpecialization: + $ref: ./components/schemas.yml#/QuestionnaireSpecialization + CandidateQuestionnaire: + $ref: ./components/schemas.yml#/CandidateQuestionnaire + CandidateQuestionnaireUpdate: + $ref: ./components/schemas.yml#/CandidateQuestionnaireUpdate + ProfileVersion: + $ref: ./components/schemas.yml#/ProfileVersion + ProfileItemStatus: + $ref: ./components/schemas.yml#/ProfileItemStatus + ProfileClaimStatus: + $ref: ./components/schemas.yml#/ProfileClaimStatus + ProfileClaimOrigin: + $ref: ./components/schemas.yml#/ProfileClaimOrigin + ProfileClaimTrustLevel: + $ref: ./components/schemas.yml#/ProfileClaimTrustLevel + ProfileClaimQuote: + $ref: ./components/schemas.yml#/ProfileClaimQuote + ProfileClaimSource: + $ref: ./components/schemas.yml#/ProfileClaimSource + ProfileLocationName: + $ref: ./components/schemas.yml#/ProfileLocationName + ProfileSalaryMinimum: + $ref: ./components/schemas.yml#/ProfileSalaryMinimum + ProfileSoftSkill: + $ref: ./components/schemas.yml#/ProfileSoftSkill + ProfileEmployerName: + $ref: ./components/schemas.yml#/ProfileEmployerName + ProfileExperienceSummary: + $ref: ./components/schemas.yml#/ProfileExperienceSummary + ProfileYearMonth: + $ref: ./components/schemas.yml#/ProfileYearMonth + ProfileFullNameClaim: + $ref: ./components/schemas.yml#/ProfileFullNameClaim + ProfileEmailClaim: + $ref: ./components/schemas.yml#/ProfileEmailClaim + ProfilePhoneClaim: + $ref: ./components/schemas.yml#/ProfilePhoneClaim + ProfileTelegramClaim: + $ref: ./components/schemas.yml#/ProfileTelegramClaim + ProfileLocationClaim: + $ref: ./components/schemas.yml#/ProfileLocationClaim + ProfileRelocationClaim: + $ref: ./components/schemas.yml#/ProfileRelocationClaim + ProfileSalaryMinimumClaim: + $ref: ./components/schemas.yml#/ProfileSalaryMinimumClaim + ProfileContacts: + $ref: ./components/schemas.yml#/ProfileContacts + ProfileTerms: + $ref: ./components/schemas.yml#/ProfileTerms + ProfileStackItem: + $ref: ./components/schemas.yml#/ProfileStackItem + ProfileSoftSkillItem: + $ref: ./components/schemas.yml#/ProfileSoftSkillItem + ProfileRoleItem: + $ref: ./components/schemas.yml#/ProfileRoleItem + ProfileExperienceItem: + $ref: ./components/schemas.yml#/ProfileExperienceItem + ProfileExperienceOverlapStatus: + $ref: ./components/schemas.yml#/ProfileExperienceOverlapStatus + ProfileExperienceOverlap: + $ref: ./components/schemas.yml#/ProfileExperienceOverlap + ProfileExperiencePeriod: + $ref: ./components/schemas.yml#/ProfileExperiencePeriod + ProfileParallelPeriodConfirmation: + $ref: ./components/schemas.yml#/ProfileParallelPeriodConfirmation + ProfileConfirmedCategory: + $ref: ./components/schemas.yml#/ProfileConfirmedCategory + CandidateProfile: + $ref: ./components/schemas.yml#/CandidateProfile + ProfileFullNameInput: + $ref: ./components/schemas.yml#/ProfileFullNameInput + ProfileEmailInput: + $ref: ./components/schemas.yml#/ProfileEmailInput + ProfilePhoneInput: + $ref: ./components/schemas.yml#/ProfilePhoneInput + ProfileTelegramInput: + $ref: ./components/schemas.yml#/ProfileTelegramInput + ProfileLocationInput: + $ref: ./components/schemas.yml#/ProfileLocationInput + ProfileRelocationInput: + $ref: ./components/schemas.yml#/ProfileRelocationInput + ProfileSalaryMinimumInput: + $ref: ./components/schemas.yml#/ProfileSalaryMinimumInput + ProfileContactsInput: + $ref: ./components/schemas.yml#/ProfileContactsInput + ProfileTermsInput: + $ref: ./components/schemas.yml#/ProfileTermsInput + ProfileStackItemInput: + $ref: ./components/schemas.yml#/ProfileStackItemInput + ProfileSoftSkillItemInput: + $ref: ./components/schemas.yml#/ProfileSoftSkillItemInput + ProfileRoleItemInput: + $ref: ./components/schemas.yml#/ProfileRoleItemInput + ProfileExperienceItemInput: + $ref: ./components/schemas.yml#/ProfileExperienceItemInput + CandidateProfileUpdate: + $ref: ./components/schemas.yml#/CandidateProfileUpdate + AssessmentMode: + $ref: ./components/schemas.yml#/AssessmentMode + AssessmentAttemptVersion: + $ref: ./components/schemas.yml#/AssessmentAttemptVersion + AssessmentAttemptState: + $ref: ./components/schemas.yml#/AssessmentAttemptState + AssessmentVersionLabel: + $ref: ./components/schemas.yml#/AssessmentVersionLabel + AssessmentVersions: + $ref: ./components/schemas.yml#/AssessmentVersions + AssessmentSessions: + $ref: ./components/schemas.yml#/AssessmentSessions + AssessmentAttemptCreate: + $ref: ./components/schemas.yml#/AssessmentAttemptCreate + AssessmentAttemptSessionStart: + $ref: ./components/schemas.yml#/AssessmentAttemptSessionStart + AssessmentItemId: + $ref: ./components/schemas.yml#/AssessmentItemId + AssessmentOptionId: + $ref: ./components/schemas.yml#/AssessmentOptionId + AssessmentOption: + $ref: ./components/schemas.yml#/AssessmentOption + ChoiceItemContent: + $ref: ./components/schemas.yml#/ChoiceItemContent + NumberItemContent: + $ref: ./components/schemas.yml#/NumberItemContent + StringItemContent: + $ref: ./components/schemas.yml#/StringItemContent + OrderItemContent: + $ref: ./components/schemas.yml#/OrderItemContent + CodeLine: + $ref: ./components/schemas.yml#/CodeLine + FindErrorItemContent: + $ref: ./components/schemas.yml#/FindErrorItemContent + ConfigurationItemContent: + $ref: ./components/schemas.yml#/ConfigurationItemContent + PracticeExample: + $ref: ./components/schemas.yml#/PracticeExample + PracticeItemContent: + $ref: ./components/schemas.yml#/PracticeItemContent + ItemContent: + $ref: ./components/schemas.yml#/ItemContent + AssessmentItem: + $ref: ./components/schemas.yml#/AssessmentItem + AssessmentProgress: + $ref: ./components/schemas.yml#/AssessmentProgress + PracticeKind: + $ref: ./components/schemas.yml#/PracticeKind + PracticeStatus: + $ref: ./components/schemas.yml#/PracticeStatus + PracticeFailureReason: + $ref: ./components/schemas.yml#/PracticeFailureReason + PracticeGroupResult: + $ref: ./components/schemas.yml#/PracticeGroupResult + PracticeVerdict: + $ref: ./components/schemas.yml#/PracticeVerdict + AssessmentPractice: + $ref: ./components/schemas.yml#/AssessmentPractice + PracticeRunTest: + $ref: ./components/schemas.yml#/PracticeRunTest + PracticeRunCreate: + $ref: ./components/schemas.yml#/PracticeRunCreate + PracticeRunState: + $ref: ./components/schemas.yml#/PracticeRunState + PracticeRunOutcome: + $ref: ./components/schemas.yml#/PracticeRunOutcome + PracticeRunTestSource: + $ref: ./components/schemas.yml#/PracticeRunTestSource + PracticeRunTestResult: + $ref: ./components/schemas.yml#/PracticeRunTestResult + PracticeRunResult: + $ref: ./components/schemas.yml#/PracticeRunResult + PracticeRun: + $ref: ./components/schemas.yml#/PracticeRun + AssessmentAttempt: + $ref: ./components/schemas.yml#/AssessmentAttempt + ChoiceAnswer: + $ref: ./components/schemas.yml#/ChoiceAnswer + NumberAnswer: + $ref: ./components/schemas.yml#/NumberAnswer + StringAnswer: + $ref: ./components/schemas.yml#/StringAnswer + OrderAnswer: + $ref: ./components/schemas.yml#/OrderAnswer + FindErrorAnswer: + $ref: ./components/schemas.yml#/FindErrorAnswer + ConfigurationAnswer: + $ref: ./components/schemas.yml#/ConfigurationAnswer + PracticeAnswer: + $ref: ./components/schemas.yml#/PracticeAnswer + AssessmentAnswer: + $ref: ./components/schemas.yml#/AssessmentAnswer + AssessmentAnswerSubmission: + $ref: ./components/schemas.yml#/AssessmentAnswerSubmission + AssessmentSignalEvent: + $ref: ./components/schemas.yml#/AssessmentSignalEvent + AssessmentFocusLossSignal: + $ref: ./components/schemas.yml#/AssessmentFocusLossSignal + AssessmentClipboardSignal: + $ref: ./components/schemas.yml#/AssessmentClipboardSignal + AssessmentFullscreenExitSignal: + $ref: ./components/schemas.yml#/AssessmentFullscreenExitSignal + AssessmentSignalBatch: + $ref: ./components/schemas.yml#/AssessmentSignalBatch + AssessmentSignalReceipt: + $ref: ./components/schemas.yml#/AssessmentSignalReceipt + AssessmentFinalization: + $ref: ./components/schemas.yml#/AssessmentFinalization + AssessmentOutcome: + $ref: ./components/schemas.yml#/AssessmentOutcome + AssessmentNotDeterminedReason: + $ref: ./components/schemas.yml#/AssessmentNotDeterminedReason + AssessmentStrength: + $ref: ./components/schemas.yml#/AssessmentStrength + CalibrationStatus: + $ref: ./components/schemas.yml#/CalibrationStatus + AssessmentLimitation: + $ref: ./components/schemas.yml#/AssessmentLimitation + AssessmentInterval: + $ref: ./components/schemas.yml#/AssessmentInterval + AssessmentUncertainty: + $ref: ./components/schemas.yml#/AssessmentUncertainty + BasicScore: + $ref: ./components/schemas.yml#/BasicScore + AssessmentGap: + $ref: ./components/schemas.yml#/AssessmentGap + AssessmentDurations: + $ref: ./components/schemas.yml#/AssessmentDurations + AssessmentPracticeResult: + $ref: ./components/schemas.yml#/AssessmentPracticeResult + AssessmentNextAction: + $ref: ./components/schemas.yml#/AssessmentNextAction + AssessmentNextStep: + $ref: ./components/schemas.yml#/AssessmentNextStep + AssessmentResult: + $ref: ./components/schemas.yml#/AssessmentResult + AssessmentRealResult: + $ref: ./components/schemas.yml#/AssessmentRealResult + AssessmentCategoryDecisionView: + $ref: ./components/schemas.yml#/AssessmentCategoryDecisionView + AssessmentResultHistoryPage: + $ref: ./components/schemas.yml#/AssessmentResultHistoryPage + AssessmentGradeAvailabilityStatus: + $ref: ./components/schemas.yml#/AssessmentGradeAvailabilityStatus + AssessmentGradeAvailability: + $ref: ./components/schemas.yml#/AssessmentGradeAvailability + AssessmentSpecializationAvailability: + $ref: ./components/schemas.yml#/AssessmentSpecializationAvailability + AssessmentAvailability: + $ref: ./components/schemas.yml#/AssessmentAvailability + NeedVersion: + $ref: ./components/schemas.yml#/NeedVersion + NeedTitle: + $ref: ./components/schemas.yml#/NeedTitle + NeedSourceText: + $ref: ./components/schemas.yml#/NeedSourceText + NeedValueStatus: + $ref: ./components/schemas.yml#/NeedValueStatus + NeedItemStatus: + $ref: ./components/schemas.yml#/NeedItemStatus + NeedValueOrigin: + $ref: ./components/schemas.yml#/NeedValueOrigin + NeedSourceQuote: + $ref: ./components/schemas.yml#/NeedSourceQuote + NeedVersionLabel: + $ref: ./components/schemas.yml#/NeedVersionLabel + NeedValueSource: + $ref: ./components/schemas.yml#/NeedValueSource + SkillName: + $ref: ./components/schemas.yml#/SkillName + SkillTaxonomyCode: + $ref: ./components/schemas.yml#/SkillTaxonomyCode + NeedTaskText: + $ref: ./components/schemas.yml#/NeedTaskText + NeedDomainName: + $ref: ./components/schemas.yml#/NeedDomainName + NeedLocationName: + $ref: ./components/schemas.yml#/NeedLocationName + RubAmount: + $ref: ./components/schemas.yml#/RubAmount + CurrencyCode: + $ref: ./components/schemas.yml#/CurrencyCode + SalaryPeriod: + $ref: ./components/schemas.yml#/SalaryPeriod + SalaryTaxBasis: + $ref: ./components/schemas.yml#/SalaryTaxBasis + SalaryRange: + $ref: ./components/schemas.yml#/SalaryRange + NeedSpecialization: + $ref: ./components/schemas.yml#/NeedSpecialization + NeedGrade: + $ref: ./components/schemas.yml#/NeedGrade + NeedDomain: + $ref: ./components/schemas.yml#/NeedDomain + NeedWorkFormats: + $ref: ./components/schemas.yml#/NeedWorkFormats + NeedLocation: + $ref: ./components/schemas.yml#/NeedLocation + NeedSalary: + $ref: ./components/schemas.yml#/NeedSalary + NeedSkill: + $ref: ./components/schemas.yml#/NeedSkill + NeedTask: + $ref: ./components/schemas.yml#/NeedTask + NeedSpecializationInput: + $ref: ./components/schemas.yml#/NeedSpecializationInput + NeedGradeInput: + $ref: ./components/schemas.yml#/NeedGradeInput + NeedDomainInput: + $ref: ./components/schemas.yml#/NeedDomainInput + NeedWorkFormatsInput: + $ref: ./components/schemas.yml#/NeedWorkFormatsInput + NeedLocationInput: + $ref: ./components/schemas.yml#/NeedLocationInput + NeedSalaryInput: + $ref: ./components/schemas.yml#/NeedSalaryInput + NeedSkillInput: + $ref: ./components/schemas.yml#/NeedSkillInput + NeedTaskInput: + $ref: ./components/schemas.yml#/NeedTaskInput + NeedRequirementSet: + $ref: ./components/schemas.yml#/NeedRequirementSet + NeedFieldName: + $ref: ./components/schemas.yml#/NeedFieldName + NeedMissingReason: + $ref: ./components/schemas.yml#/NeedMissingReason + NeedMissingField: + $ref: ./components/schemas.yml#/NeedMissingField + NeedReadinessStatus: + $ref: ./components/schemas.yml#/NeedReadinessStatus + NeedReadinessReport: + $ref: ./components/schemas.yml#/NeedReadinessReport + NeedRecommendationStatus: + $ref: ./components/schemas.yml#/NeedRecommendationStatus + NeedSkillOverlap: + $ref: ./components/schemas.yml#/NeedSkillOverlap + NeedMoneyStatus: + $ref: ./components/schemas.yml#/NeedMoneyStatus + NeedMoneyFit: + $ref: ./components/schemas.yml#/NeedMoneyFit + NeedSupplyBand: + $ref: ./components/schemas.yml#/NeedSupplyBand + NeedCategoryRecommendation: + $ref: ./components/schemas.yml#/NeedCategoryRecommendation + NeedCategoryRecommendations: + $ref: ./components/schemas.yml#/NeedCategoryRecommendations + Need: + $ref: ./components/schemas.yml#/Need + NeedSummary: + $ref: ./components/schemas.yml#/NeedSummary + NeedList: + $ref: ./components/schemas.yml#/NeedList + NeedCreate: + $ref: ./components/schemas.yml#/NeedCreate + NeedUpdate: + $ref: ./components/schemas.yml#/NeedUpdate + SupportCaseNumber: + $ref: ./components/schemas.yml#/SupportCaseNumber + SupportCaseType: + $ref: ./components/schemas.yml#/SupportCaseType + SupportCaseStatus: + $ref: ./components/schemas.yml#/SupportCaseStatus + SupportCaseObjectType: + $ref: ./components/schemas.yml#/SupportCaseObjectType + SupportCaseObjectReference: + $ref: ./components/schemas.yml#/SupportCaseObjectReference + SupportCaseAttemptReference: + $ref: ./components/schemas.yml#/SupportCaseAttemptReference + SupportCaseGradeAppealReference: + $ref: ./components/schemas.yml#/SupportCaseGradeAppealReference + SupportCaseComplaintReference: + $ref: ./components/schemas.yml#/SupportCaseComplaintReference + SupportCaseAssessmentTarget: + $ref: ./components/schemas.yml#/SupportCaseAssessmentTarget + SupportCaseComplaintReason: + $ref: ./components/schemas.yml#/SupportCaseComplaintReason + SupportCaseDescription: + $ref: ./components/schemas.yml#/SupportCaseDescription + SupportCasePublicText: + $ref: ./components/schemas.yml#/SupportCasePublicText + SupportCaseCreateSupport: + $ref: ./components/schemas.yml#/SupportCaseCreateSupport + SupportCaseCreateComplaint: + $ref: ./components/schemas.yml#/SupportCaseCreateComplaint + SupportCaseCreateGradeAppeal: + $ref: ./components/schemas.yml#/SupportCaseCreateGradeAppeal + SupportCaseCreateAnticheatAppeal: + $ref: ./components/schemas.yml#/SupportCaseCreateAnticheatAppeal + SupportCaseCreateManualAssessment: + $ref: ./components/schemas.yml#/SupportCaseCreateManualAssessment + SupportCaseCreate: + $ref: ./components/schemas.yml#/SupportCaseCreate + SupportResponseTarget: + $ref: ./components/schemas.yml#/SupportResponseTarget + SupportCaseDecisionOutcome: + $ref: ./components/schemas.yml#/SupportCaseDecisionOutcome + SupportCaseDecision: + $ref: ./components/schemas.yml#/SupportCaseDecision + SupportCaseActorKind: + $ref: ./components/schemas.yml#/SupportCaseActorKind + SupportCaseEventKind: + $ref: ./components/schemas.yml#/SupportCaseEventKind + SupportCaseEvent: + $ref: ./components/schemas.yml#/SupportCaseEvent + SupportCase: + $ref: ./components/schemas.yml#/SupportCase + SupportCaseSummary: + $ref: ./components/schemas.yml#/SupportCaseSummary + SupportCaseList: + $ref: ./components/schemas.yml#/SupportCaseList + InvitationVersion: + $ref: ./components/schemas.yml#/InvitationVersion + InvitationTermsVersion: + $ref: ./components/schemas.yml#/InvitationTermsVersion + InvitationState: + $ref: ./components/schemas.yml#/InvitationState + InvitationExpiryReason: + $ref: ./components/schemas.yml#/InvitationExpiryReason + InvitationResponsePeriod: + $ref: ./components/schemas.yml#/InvitationResponsePeriod + CandidateHandle: + $ref: ./components/schemas.yml#/CandidateHandle + InvitationRoleTitle: + $ref: ./components/schemas.yml#/InvitationRoleTitle + InvitationTeamDescription: + $ref: ./components/schemas.yml#/InvitationTeamDescription + InvitationOfferType: + $ref: ./components/schemas.yml#/InvitationOfferType + InvitationCommunicationChannel: + $ref: ./components/schemas.yml#/InvitationCommunicationChannel + InvitationCommunicationMethod: + $ref: ./components/schemas.yml#/InvitationCommunicationMethod + InvitationCommunicationNote: + $ref: ./components/schemas.yml#/InvitationCommunicationNote + InvitationPackageItemText: + $ref: ./components/schemas.yml#/InvitationPackageItemText + InvitationPackageItemProvided: + $ref: ./components/schemas.yml#/InvitationPackageItemProvided + InvitationPackageItemNotProvided: + $ref: ./components/schemas.yml#/InvitationPackageItemNotProvided + InvitationPackageItem: + $ref: ./components/schemas.yml#/InvitationPackageItem + InvitationPackage: + $ref: ./components/schemas.yml#/InvitationPackage + InvitationTerms: + $ref: ./components/schemas.yml#/InvitationTerms + InvitationNeedReference: + $ref: ./components/schemas.yml#/InvitationNeedReference + InvitationSalaryFit: + $ref: ./components/schemas.yml#/InvitationSalaryFit + InvitationContactAccessState: + $ref: ./components/schemas.yml#/InvitationContactAccessState + InvitationContactAccess: + $ref: ./components/schemas.yml#/InvitationContactAccess + InvitationOrganization: + $ref: ./components/schemas.yml#/InvitationOrganization + InvitationDeclineReason: + $ref: ./components/schemas.yml#/InvitationDeclineReason + InvitationDeclineComment: + $ref: ./components/schemas.yml#/InvitationDeclineComment + InvitationDeclineRecord: + $ref: ./components/schemas.yml#/InvitationDeclineRecord + OrganizationInvitation: + $ref: ./components/schemas.yml#/OrganizationInvitation + OrganizationInvitationSummary: + $ref: ./components/schemas.yml#/OrganizationInvitationSummary + OrganizationInvitationList: + $ref: ./components/schemas.yml#/OrganizationInvitationList + OrganizationInvitationCreate: + $ref: ./components/schemas.yml#/OrganizationInvitationCreate + OrganizationInvitationUpdate: + $ref: ./components/schemas.yml#/OrganizationInvitationUpdate + InvitationCommand: + $ref: ./components/schemas.yml#/InvitationCommand + InvitationSalaryRaise: + $ref: ./components/schemas.yml#/InvitationSalaryRaise + CandidateInvitation: + $ref: ./components/schemas.yml#/CandidateInvitation + CandidateInvitationSummary: + $ref: ./components/schemas.yml#/CandidateInvitationSummary + CandidateInvitationList: + $ref: ./components/schemas.yml#/CandidateInvitationList + InvitationAcceptance: + $ref: ./components/schemas.yml#/InvitationAcceptance + InvitationDeclineRequest: + $ref: ./components/schemas.yml#/InvitationDeclineRequest + ContactFieldKind: + $ref: ./components/schemas.yml#/ContactFieldKind + ContactConsentText: + $ref: ./components/schemas.yml#/ContactConsentText + ContactConsentOffer: + $ref: ./components/schemas.yml#/ContactConsentOffer + ContactConsentAcceptance: + $ref: ./components/schemas.yml#/ContactConsentAcceptance + ContactGrantState: + $ref: ./components/schemas.yml#/ContactGrantState + ContactAccessBlock: + $ref: ./components/schemas.yml#/ContactAccessBlock + ContactRevocationReason: + $ref: ./components/schemas.yml#/ContactRevocationReason + ContactGrant: + $ref: ./components/schemas.yml#/ContactGrant + ContactPhoneNumber: + $ref: ./components/schemas.yml#/ContactPhoneNumber + ContactTelegramUsername: + $ref: ./components/schemas.yml#/ContactTelegramUsername + ContactFullName: + $ref: ./components/schemas.yml#/ContactFullName + ContactDisclosure: + $ref: ./components/schemas.yml#/ContactDisclosure + ConsentPurposeCode: + $ref: ./components/schemas.yml#/ConsentPurposeCode + ConsentState: + $ref: ./components/schemas.yml#/ConsentState + ConsentSource: + $ref: ./components/schemas.yml#/ConsentSource + ConsentRevocationSource: + $ref: ./components/schemas.yml#/ConsentRevocationSource + ConsentOrganization: + $ref: ./components/schemas.yml#/ConsentOrganization + ConsentRecord: + $ref: ./components/schemas.yml#/ConsentRecord + ConsentRecordList: + $ref: ./components/schemas.yml#/ConsentRecordList + ConsentSettingsGrantRequest: + $ref: ./components/schemas.yml#/ConsentSettingsGrantRequest + ConsentDeletionRequest: + $ref: ./components/schemas.yml#/ConsentDeletionRequest + OrganizationVersion: + $ref: ./components/schemas.yml#/OrganizationVersion + OrganizationName: + $ref: ./components/schemas.yml#/OrganizationName + OrganizationDescription: + $ref: ./components/schemas.yml#/OrganizationDescription + OrganizationSphere: + $ref: ./components/schemas.yml#/OrganizationSphere + OrganizationWebsite: + $ref: ./components/schemas.yml#/OrganizationWebsite + OrganizationContactChannels: + $ref: ./components/schemas.yml#/OrganizationContactChannels + OrganizationRepresentative: + $ref: ./components/schemas.yml#/OrganizationRepresentative + OrganizationVerificationLevel: + $ref: ./components/schemas.yml#/OrganizationVerificationLevel + OrganizationVerificationBasis: + $ref: ./components/schemas.yml#/OrganizationVerificationBasis + OrganizationVerification: + $ref: ./components/schemas.yml#/OrganizationVerification + CandidateOrganizationCard: + $ref: ./components/schemas.yml#/CandidateOrganizationCard + Organization: + $ref: ./components/schemas.yml#/Organization + OrganizationCreate: + $ref: ./components/schemas.yml#/OrganizationCreate + OrganizationUpdate: + $ref: ./components/schemas.yml#/OrganizationUpdate + OrganizationRole: + $ref: ./components/schemas.yml#/OrganizationRole + MembershipState: + $ref: ./components/schemas.yml#/MembershipState + OrganizationMembership: + $ref: ./components/schemas.yml#/OrganizationMembership + OrganizationSummary: + $ref: ./components/schemas.yml#/OrganizationSummary + MyOrganization: + $ref: ./components/schemas.yml#/MyOrganization + MyOrganizationList: + $ref: ./components/schemas.yml#/MyOrganizationList + PublicationVersion: + $ref: ./components/schemas.yml#/PublicationVersion + SearchStatusVersion: + $ref: ./components/schemas.yml#/SearchStatusVersion + CardField: + $ref: ./components/schemas.yml#/CardField + CardFieldSet: + $ref: ./components/schemas.yml#/CardFieldSet + PublicationState: + $ref: ./components/schemas.yml#/PublicationState + PublicationClosedReason: + $ref: ./components/schemas.yml#/PublicationClosedReason + Publication: + $ref: ./components/schemas.yml#/Publication + PublicationUpdate: + $ref: ./components/schemas.yml#/PublicationUpdate + SearchStatusValue: + $ref: ./components/schemas.yml#/SearchStatusValue + SearchStatus: + $ref: ./components/schemas.yml#/SearchStatus + SearchStatusUpdate: + $ref: ./components/schemas.yml#/SearchStatusUpdate + PrivacyOrganization: + $ref: ./components/schemas.yml#/PrivacyOrganization + HiddenOrganization: + $ref: ./components/schemas.yml#/HiddenOrganization + HiddenOrganizationList: + $ref: ./components/schemas.yml#/HiddenOrganizationList + PrivacySettings: + $ref: ./components/schemas.yml#/PrivacySettings + CardCategory: + $ref: ./components/schemas.yml#/CardCategory + AnonymousCardContent: + $ref: ./components/schemas.yml#/AnonymousCardContent + CardPreview: + $ref: ./components/schemas.yml#/CardPreview + PrivacyEventKind: + $ref: ./components/schemas.yml#/PrivacyEventKind + PrivacyEvent: + $ref: ./components/schemas.yml#/PrivacyEvent + PrivacyEventList: + $ref: ./components/schemas.yml#/PrivacyEventList + CardAccessKind: + $ref: ./components/schemas.yml#/CardAccessKind + CardAccess: + $ref: ./components/schemas.yml#/CardAccess + CardAccessList: + $ref: ./components/schemas.yml#/CardAccessList + EvidenceKind: + $ref: ./components/schemas.yml#/EvidenceKind + EvidenceSourceType: + $ref: ./components/schemas.yml#/EvidenceSourceType + EvidenceAttribution: + $ref: ./components/schemas.yml#/EvidenceAttribution + EvidenceTrustLevel: + $ref: ./components/schemas.yml#/EvidenceTrustLevel + EvidenceVisibility: + $ref: ./components/schemas.yml#/EvidenceVisibility + EvidenceSkillCode: + $ref: ./components/schemas.yml#/EvidenceSkillCode + EvidenceBasis: + $ref: ./components/schemas.yml#/EvidenceBasis + EvidenceCalibrationStatus: + $ref: ./components/schemas.yml#/EvidenceCalibrationStatus + EvidenceResult: + $ref: ./components/schemas.yml#/EvidenceResult + EvidenceSource: + $ref: ./components/schemas.yml#/EvidenceSource + EvidenceFact: + $ref: ./components/schemas.yml#/EvidenceFact + EvidenceFactList: + $ref: ./components/schemas.yml#/EvidenceFactList + OrganizationEvidenceFact: + $ref: ./components/schemas.yml#/OrganizationEvidenceFact + OrganizationEvidence: + $ref: ./components/schemas.yml#/OrganizationEvidence + NotificationKind: + $ref: ./components/schemas.yml#/NotificationKind + NotificationContent: + $ref: ./components/schemas.yml#/NotificationContent + Notification: + $ref: ./components/schemas.yml#/Notification + NotificationList: + $ref: ./components/schemas.yml#/NotificationList + NotificationReadReceipt: + $ref: ./components/schemas.yml#/NotificationReadReceipt + AssessmentLabNodeName: + $ref: ./components/schemas.yml#/AssessmentLabNodeName + AssessmentLabNodeKind: + $ref: ./components/schemas.yml#/AssessmentLabNodeKind + AssessmentLabNode: + $ref: ./components/schemas.yml#/AssessmentLabNode + LabItemContent: + $ref: ./components/schemas.yml#/LabItemContent + LabAnswer: + $ref: ./components/schemas.yml#/LabAnswer + AssessmentLabState: + $ref: ./components/schemas.yml#/AssessmentLabState + AssessmentLabFailureReason: + $ref: ./components/schemas.yml#/AssessmentLabFailureReason + AssessmentLab: + $ref: ./components/schemas.yml#/AssessmentLab + AssessmentLabCreate: + $ref: ./components/schemas.yml#/AssessmentLabCreate + AssessmentLabConsoleSessionCreate: + $ref: ./components/schemas.yml#/AssessmentLabConsoleSessionCreate + AssessmentLabConsoleSession: + $ref: ./components/schemas.yml#/AssessmentLabConsoleSession + AssessmentLabSubmission: + $ref: ./components/schemas.yml#/AssessmentLabSubmission + parameters: + IdempotencyKey: + $ref: ./components/parameters.yml#/IdempotencyKey + IfMatch: + $ref: ./components/parameters.yml#/IfMatch + PageLimit: + $ref: ./components/parameters.yml#/PageLimit + PageCursor: + $ref: ./components/parameters.yml#/PageCursor + AssessmentAttemptId: + $ref: ./components/parameters.yml#/AssessmentAttemptId + OrganizationId: + $ref: ./components/parameters.yml#/OrganizationId + NeedId: + $ref: ./components/parameters.yml#/NeedId + SupportCaseId: + $ref: ./components/parameters.yml#/SupportCaseId + InvitationId: + $ref: ./components/parameters.yml#/InvitationId + MyInvitationId: + $ref: ./components/parameters.yml#/MyInvitationId + HiddenOrganizationId: + $ref: ./components/parameters.yml#/HiddenOrganizationId + NotificationId: + $ref: ./components/parameters.yml#/NotificationId + headers: + ETag: + $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 + Unauthenticated: + $ref: ./components/responses.yml#/Unauthenticated + Forbidden: + $ref: ./components/responses.yml#/Forbidden + NotFound: + $ref: ./components/responses.yml#/NotFound + IdempotencyInProgress: + $ref: ./components/responses.yml#/IdempotencyInProgress + StateConflict: + $ref: ./components/responses.yml#/StateConflict + PreconditionFailed: + $ref: ./components/responses.yml#/PreconditionFailed + PayloadTooLarge: + $ref: ./components/responses.yml#/PayloadTooLarge + UnprocessableContent: + $ref: ./components/responses.yml#/UnprocessableContent + PreconditionRequired: + $ref: ./components/responses.yml#/PreconditionRequired + TooManyRequests: + $ref: ./components/responses.yml#/TooManyRequests + Internal: + $ref: ./components/responses.yml#/Internal + NotImplemented: + $ref: ./components/responses.yml#/NotImplemented + Problem: + $ref: ./components/responses.yml#/Problem + RegistrationValidationFailed: + $ref: ./components/responses.yml#/RegistrationValidationFailed + EmailVerificationFailed: + $ref: ./components/responses.yml#/EmailVerificationFailed + InvalidCredentials: + $ref: ./components/responses.yml#/InvalidCredentials + CsrfCheckFailed: + $ref: ./components/responses.yml#/CsrfCheckFailed + CsrfCheckFailedOrForbidden: + $ref: ./components/responses.yml#/CsrfCheckFailedOrForbidden + QuestionnaireValidationFailed: + $ref: ./components/responses.yml#/QuestionnaireValidationFailed + QuestionnaireVersionConflict: + $ref: ./components/responses.yml#/QuestionnaireVersionConflict + ProfileValidationFailed: + $ref: ./components/responses.yml#/ProfileValidationFailed + ProfileVersionConflict: + $ref: ./components/responses.yml#/ProfileVersionConflict + AssessmentAttemptCreateValidationFailed: + $ref: ./components/responses.yml#/AssessmentAttemptCreateValidationFailed + AssessmentAnswerValidationFailed: + $ref: ./components/responses.yml#/AssessmentAnswerValidationFailed + AssessmentCommandConflict: + $ref: ./components/responses.yml#/AssessmentCommandConflict + AssessmentFinalizeConflict: + $ref: ./components/responses.yml#/AssessmentFinalizeConflict + AssessmentCreateConflict: + $ref: ./components/responses.yml#/AssessmentCreateConflict + AssessmentResultNotReady: + $ref: ./components/responses.yml#/AssessmentResultNotReady + AssessmentVersionConflict: + $ref: ./components/responses.yml#/AssessmentVersionConflict + NeedValidationFailed: + $ref: ./components/responses.yml#/NeedValidationFailed + NeedVersionConflict: + $ref: ./components/responses.yml#/NeedVersionConflict + SupportCaseValidationFailed: + $ref: ./components/responses.yml#/SupportCaseValidationFailed + SupportCaseCreateConflict: + $ref: ./components/responses.yml#/SupportCaseCreateConflict + InvitationValidationFailed: + $ref: ./components/responses.yml#/InvitationValidationFailed + InvitationAcceptValidationFailed: + $ref: ./components/responses.yml#/InvitationAcceptValidationFailed + InvitationVersionConflict: + $ref: ./components/responses.yml#/InvitationVersionConflict + InvitationCommandConflict: + $ref: ./components/responses.yml#/InvitationCommandConflict + OrganizationValidationFailed: + $ref: ./components/responses.yml#/OrganizationValidationFailed + OrganizationVersionConflict: + $ref: ./components/responses.yml#/OrganizationVersionConflict + PrivacyValidationFailed: + $ref: ./components/responses.yml#/PrivacyValidationFailed + PrivacyVersionConflict: + $ref: ./components/responses.yml#/PrivacyVersionConflict + PublicationConsentRequired: + $ref: ./components/responses.yml#/PublicationConsentRequired + HiddenOrganizationLimit: + $ref: ./components/responses.yml#/HiddenOrganizationLimit + 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/account_deletion_requests.yml b/api/core/routes/account_deletion_requests.yml new file mode 100644 index 0000000..53ae8a5 --- /dev/null +++ b/api/core/routes/account_deletion_requests.yml @@ -0,0 +1,27 @@ +post: + operationId: RequestMyAccountDeletion + summary: Revoke C1 and request account deletion. + description: |- + Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. In one transaction, revokes any active C1 record, creates or returns the subject's active durable deletion request, and writes the outbox intent. The API does not delete the account synchronously. Repeating the request returns the same active request; a later C1 grant never cancels it. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + responses: + "202": + description: The durable account-deletion request is queued for processing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentDeletionRequest + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed. + $ref: ../components/responses.yml#/CsrfCheckFailed + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt.yml b/api/core/routes/candidate_assessment_attempt.yml new file mode 100644 index 0000000..93c184f --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt.yml @@ -0,0 +1,50 @@ +get: + operationId: GetMyAssessmentAttempt + summary: Read an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the stored attempt projection with its state, fixed versions, time and session limits, progress, the item to answer now, and the practices. This GET is read-only: it never starts or resumes a work session, consumes session quota, advances the version, or commits expiry or finalization. A reload, a retried request, or a new session returns the same item instance with the same text and option order; a lost connection never creates a new attempt. After `idle_timeout_seconds`, the candidate explicitly starts or resumes work with StartMyAssessmentAttemptSession. The response never says whether an earlier answer was correct and never contains answer keys, item scores, family or variant identifiers, seeds, hidden checks, or anti-cheat signals. + + When the deadline passes, this read still returns the stored state and deadline. A command or background transition commits the due outcome; if the stored state is still active, GetMyAssessmentResult answers 409 until that transition is committed. The client polls this operation while a practice is `pending`, but polling alone never changes attempt state. + + The attempt must belong to the candidate of the session: an attempt of another candidate answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. An employer account answers 403 forbidden; no operation gives an employer the answers, qualification evidence, or attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + responses: + "200": + description: The attempt. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + adaptive_resumed: + $ref: ../components/examples.yml#/AssessmentAttemptResumed + practice_pending: + $ref: ../components/examples.yml#/AssessmentAttemptPracticePending + practice_verdict_pending: + $ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending + sandbox_failed: + $ref: ../components/examples.yml#/AssessmentAttemptSandboxFailed + ready_to_finalize: + $ref: ../components/examples.yml#/AssessmentAttemptReadyToFinalize + additional_practice_pending: + $ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending + completed: + $ref: ../components/examples.yml#/AssessmentAttemptCompleted + insufficient_bank: + $ref: ../components/examples.yml#/AssessmentAttemptInsufficientBank + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_answers.yml b/api/core/routes/candidate_assessment_attempt_answers.yml new file mode 100644 index 0000000..2e1ef04 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_answers.yml @@ -0,0 +1,90 @@ +post: + operationId: SubmitMyAssessmentAnswer + summary: Answer the current item or submit a practice of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the item and carries the answer in the format of that item: `choice`, `number`, `string`, `order`, `find_error`, `configuration`, or `practice`. It never carries a score, a duration, or a correctness flag; the server records the times itself and scores the answer with the key of the fixed item instance. Time never enters the ability estimate or the grade decision. + + Lab: an item with format `lab` takes no answer here. Its lab is started with CreateMyAssessmentLab and submitted with SubmitMyAssessmentLab; any answer to a lab item answers 400 validation_failed with the pointer `/answer/format`, like an answer in the wrong format, and stores nothing. + + The response is the attempt with the next item to answer. It never says whether the answer was correct. Items are answered in order and each answer is final. + + A work command requires an active session. After `idle_timeout_seconds` of inactivity, the candidate calls StartMyAssessmentAttemptSession to explicitly start or resume a session; this answer command never starts one or consumes session quota. Reading the attempt or result is always read-only. A command that finds a due deadline transition may commit it before returning; a command that finds an expired idle session answers 409 until the candidate explicitly starts the next session. + + Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation. + + One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not stored under the Idempotency-Key and is checked before the stored answer is replayed. + + Repeats and conflicts, per item: + - A retry with the same Idempotency-Key and body within 24 hours replays the stored response. + - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice. + - A different answer for an item that already has one answers 409 state_conflict when `expected_version` is current; with a stale version the version check comes first and answers 412. + - Exception for a practice whose latest verdict is `failed`: the repeat rule does not apply. A submission with the same or a different solution, with the current `expected_version`, queues it again and advances the version. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing; the client reads the attempt again. 412 is the repository status for a stale version, also used by SaveMyQuestionnaire; 409 state_conflict is kept for commands that the attempt state does not allow at the current version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found for an unknown attempt or one of another candidate; a due deadline transition may be committed, but this request never starts a work session), the repeat of the stored answer (200, skipped for a practice whose latest verdict is `failed`), the version (412), the state (409 state_conflict: the attempt is terminal, the work session ended, the item is not current, the item has a different answer, or the practice verdict is pending or finished), then the answer against the item (400 with a pointer such as `/answer/format` or `/answer/option_ids/0`). Following the Idempotency-Key convention, 404 and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. The rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + - $ref: ../components/parameters.yml#/AttemptClient + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAnswerSubmission + examples: + choice: + $ref: ../components/examples.yml#/AssessmentChoiceAnswer + order: + $ref: ../components/examples.yml#/AssessmentOrderAnswer + number: + $ref: ../components/examples.yml#/AssessmentNumberAnswer + string: + $ref: ../components/examples.yml#/AssessmentStringAnswer + find_error: + $ref: ../components/examples.yml#/AssessmentFindErrorAnswer + configuration: + $ref: ../components/examples.yml#/AssessmentConfigurationAnswer + practice: + $ref: ../components/examples.yml#/AssessmentPracticeAnswer + responses: + "200": + description: >- + The answer was stored, or this exact answer was already stored, and + the response is the attempt with the next item. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + accepted: + $ref: ../components/examples.yml#/AssessmentAnswerAccepted + practice_submitted: + $ref: ../components/examples.yml#/AssessmentAttemptPracticeVerdictPending + "400": + $ref: ../components/responses.yml#/AssessmentAnswerValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentCommandConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_finalize.yml b/api/core/routes/candidate_assessment_attempt_finalize.yml new file mode 100644 index 0000000..7df844a --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_finalize.yml @@ -0,0 +1,69 @@ +post: + operationId: FinalizeMyAssessmentAttempt + summary: Ask for the grade decision of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. Finalize always answers with the attempt, never with the result: the decision may continue the attempt, and one response type keeps that unambiguous for every generated client. When the returned state is `completed`, the client reads the result with GetMyAssessmentResult. + + Finalize is a work command and requires an active session. After `idle_timeout_seconds` of inactivity, the candidate first calls StartMyAssessmentAttemptSession with the latest `expected_version`; finalize never starts a session. GET attempt and result operations do not change state. A command or background transition may commit a due deadline outcome. + + Allowed in `ready_to_finalize`, where every required part is done, and in `additional_practice_pending` while the additional practice is `not_started` or `failed`. The server decides from the stored answers with the policy, bank, and algorithm versions fixed at creation: + - `demo_basic` compares the raw score with the pass mark of the recorded basic grading policy and completes the attempt. It never offers an additional practice. + - `adaptive` applies the probability bands of the recorded policy. Confirmation or rejection completes the attempt. A probability in the band below confirmation (0.50 to below 0.80 in the demo policy) on the first finalize, while time and sessions remain, completes nothing: the server appends an `additional` practice, moves the attempt to `additional_practice_pending`, and answers 200 with it. The additional practice continues the same attempt, keeps its limits, and spends no new attempt. The next finalize, after its verdict, decides with the added evidence; a probability still below confirmation gives `not_confirmed`. An attempt offers at most one additional practice. + - Finalize in `additional_practice_pending` declines the offer and gives `not_confirmed` with the current evidence. A retry of the first finalize with a new key cannot decline by accident: it carries the version from before the offer and answers 412. + + A failed attempt never lowers a confirmed grade. Repeats return the same outcome: a retry with the same Idempotency-Key replays the stored response, and a finalize of a `completed` attempt answers 200 with that attempt even with a new key or an older `expected_version`; the result is computed once. When `expires_at` passes or the session limit is reached, a command or background transition finalizes `ready_to_finalize` without offering an additional practice. A finalize after this transition answers 200 with the stored `completed` attempt; a GET never commits it. + + An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for a stale version. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt (404 not_found; a due deadline transition may be committed, but this request never starts a work session), the repeat on a `completed` attempt (200), the version (412), then the state (409 state_conflict, including an ended idle session). 404 and 409 state_conflict are stored under the key; 400 and 412 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentFinalization + examples: + finalize: + $ref: ../components/examples.yml#/AssessmentFinalization + responses: + "200": + description: >- + The attempt after the decision: `completed`, with the result available + from GetMyAssessmentResult, or `additional_practice_pending` when an + adaptive attempt offers an additional practice. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + demo_basic_completed: + $ref: ../components/examples.yml#/AssessmentAttemptCompleted + additional_practice_offered: + $ref: ../components/examples.yml#/AssessmentAttemptAdditionalPracticePending + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentFinalizeConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_lab.yml b/api/core/routes/candidate_assessment_attempt_lab.yml new file mode 100644 index 0000000..1b63c1b --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_lab.yml @@ -0,0 +1,55 @@ +get: + operationId: GetMyAssessmentLab + summary: Read the lab of an assessment attempt item. + description: |- + Requires the session cookie of a candidate account. Returns the state of a lab started with CreateMyAssessmentLab: whether it is still provisioning, ready for the consoles, being checked after the submission, or ended. It never contains a node address, a credential, the seed, the checker state, or the result of the check. This GET is read-only; the server may record a due timer transition, such as `ready` to `expired`, before it answers. + + A lab of another candidate's attempt, a lab of another attempt, and an unknown identifier all answer 404 not_found. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + responses: + "200": + description: The lab. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + examples: + ready: + summary: A ready lab whose consoles can be opened. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: ready + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: "2026-10-11T09:00:00Z" + ready_at: "2026-10-11T09:00:40Z" + expires_at: "2026-10-11T09:45:00Z" + finished_at: null + failure_reason: null + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_lab_console_sessions.yml b/api/core/routes/candidate_assessment_attempt_lab_console_sessions.yml new file mode 100644 index 0000000..fc5cf56 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_lab_console_sessions.yml @@ -0,0 +1,70 @@ +post: + operationId: CreateMyAssessmentLabConsoleSession + summary: Open a console session of one node of a ready lab. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body names a node of the lab by its task name. + + The response describes one console session: the client opens a WebSocket to `websocket_path` on the same origin before `expires_at`. The upgrade is authorized by the session cookie and the Origin check, and the server relays the serial console of the node through the lab provisioner. The response never carries a node address, a port, a password, a key, or a token; the browser never connects to a node or to the provisioner. Console traffic is not stored as an answer and is not logged. + + The WebSocket relay is planned together with the candidate interface of labs; this contract fixes the session shape it uses. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt and the lab (404 not_found for an unknown attempt, lab, or one of another candidate), the node (400 with the pointer `/node`), the state (409 state_conflict: the lab is not `ready`, the attempt is terminal, or its work session ended), the limit of open sessions per lab (429 rate_limited with Retry-After), then the provisioner (503 service_unavailable without Retry-After; nothing was opened). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - name: lab_id + in: path + required: true + description: Identifier of a lab of this attempt. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabConsoleSessionCreate + examples: + r1: + summary: Open the console of r1. + value: + node: r1 + responses: + "201": + description: The console session was opened. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabConsoleSession + examples: + opened: + summary: A console session of r1. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + node: r1 + websocket_path: /api/v1/me/assessment-lab-consoles/0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a90 + expires_at: "2026-10-11T09:02:00Z" + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/StateConflict + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_lab_submission.yml b/api/core/routes/candidate_assessment_attempt_lab_submission.yml new file mode 100644 index 0000000..f0241d1 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_lab_submission.yml @@ -0,0 +1,89 @@ +post: + operationId: SubmitMyAssessmentLab + summary: Submit the lab of the current lab item as its answer. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version last read and the answer with format `lab`, which names the lab. + + The server closes the consoles, freezes the lab, and answers 202 with the lab `checking`; the checker of the task reads the state of the nodes asynchronously, the answer is recorded, and the lab becomes `submitted` and is deleted. The client polls GetMyAssessmentLab and then reads the attempt, which moves to the next item. Neither response says whether the answer was correct, and the candidate never sees the checker criteria or their results. + + When the checker cannot reach the nodes because of the lab infrastructure, the lab becomes `failed` with `lab_error`: nothing is recorded or consumed, the attempt version is unchanged, and the candidate may start a new lab of the item while it is current. A failure of the infrastructure is never scored as a wrong answer. + + Optimistic concurrency: `expected_version` must equal the current attempt version, otherwise the server answers 412 version_conflict and stores nothing. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the lab (404 not_found for an unknown attempt or lab, or one of another candidate), the version (412), the state (409 state_conflict: the lab is not `ready`, `answer.lab_id` is not the lab in the path, the item is not current, the attempt is terminal, or its work session ended), then the provisioner (503 service_unavailable without Retry-After; nothing was stored and the lab keeps running). Following the Idempotency-Key convention, 202, 404, and 409 state_conflict are stored under the key and replayed; 400, 412, 429, and 5xx are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + - name: lab_id + in: path + required: true + description: Identifier of the lab to submit. + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabSubmission + examples: + submit: + summary: Submit the lab as the answer of its item. + value: + expected_version: 7 + answer: + format: lab + lab_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + responses: + "202": + description: The submission was accepted and the lab is being checked. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + examples: + checking: + summary: A submitted lab whose nodes are being checked. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: checking + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: "2026-10-11T09:00:00Z" + ready_at: "2026-10-11T09:00:40Z" + expires_at: "2026-10-11T09:45:00Z" + finished_at: null + failure_reason: null + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentCommandConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_labs.yml b/api/core/routes/candidate_assessment_attempt_labs.yml new file mode 100644 index 0000000..53a8be7 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_labs.yml @@ -0,0 +1,86 @@ +post: + operationId: CreateMyAssessmentLab + summary: Start the lab of the current lab item of an assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the current item, whose content has the format `lab`. + + The server asks the lab provisioner for a lab of the variant fixed for this item instance and answers 201 with the lab `provisioning`; the client polls GetMyAssessmentLab until it is `ready`. The lab lives until `expires_at`, the earlier of the item's `time_limit_seconds` and the attempt deadline, and is then deleted with everything done in it. Creating a lab does not change the attempt version, the current item, or any answer. + + One lab per item at a time. While the item has a lab in `provisioning`, `ready`, or `checking`, the server answers 200 with that lab and starts no second one. After a `failed` lab the candidate may start a new one while the item is current; after `submitted` or `expired` the item cannot start another lab (409 state_conflict). + + Busy pool. When the lab pool of the provisioner has no free capacity, the server answers 503 service_unavailable with Retry-After, for example `{"type": "urn:lincodex:problem:service_unavailable", "title": "Service unavailable", "status": 503, "code": "service_unavailable", "detail": "No lab capacity is free. The attempt is unchanged; retry later."}`. Nothing was stored: no lab exists, the attempt version and the current item are unchanged, the lab lifetime has not started, and the attempt is not consumed; the client retries after Retry-After with a new Idempotency-Key. When labs are not enabled on this server, or the provisioner cannot be reached, the server answers 503 service_unavailable without Retry-After and stores nothing either. The attempt deadline keeps running in both cases. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the attempt and the item (404 not_found for an unknown attempt or item, or one of another candidate), the state (409 state_conflict: the attempt is terminal or its work session ended, the item is not current, its format is not `lab`, or its lab was submitted or expired), the rate limit (429), then the availability of labs and the capacity (503). Following the Idempotency-Key convention, 201, 200, 404, and 409 state_conflict are stored under the key and replayed; 400, 429, and 503 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLabCreate + examples: + start: + summary: Start the lab of the current item. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + responses: + "200": + description: The item already has an active lab; it is returned and no second lab is started. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + "201": + description: The lab was requested and is provisioning. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentLab + examples: + provisioning: + summary: A lab of two routers that is being prepared. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a80 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a61 + state: provisioning + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + created_at: "2026-10-11T09:00:00Z" + ready_at: null + expires_at: "2026-10-11T09:45:00Z" + finished_at: null + failure_reason: null + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentCommandConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_practice_run.yml b/api/core/routes/candidate_assessment_attempt_practice_run.yml new file mode 100644 index 0000000..7a0ee9e --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_practice_run.yml @@ -0,0 +1,64 @@ +get: + operationId: GetMyAssessmentPracticeRun + summary: Read a debug run of a practice solution. + description: |- + Requires the session cookie of a candidate account. Returns the state of a debug run started with CreateMyAssessmentPracticeRun and, once it is `finished`, the outcome of the public examples and of the tests of the candidate. It never contains a hidden check, its outcome, the score, or the source. This GET is read-only. + + A run of another candidate's attempt, a run of another attempt, and an unknown identifier all answer 404 not_found. The graded solution submitted with SubmitMyAssessmentAnswer is not a debug run and is not readable here. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - name: run_id + in: path + required: true + description: Identifier of a debug run of this attempt. + schema: + type: string + format: uuid + responses: + "200": + description: The run. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PracticeRun + examples: + finished: + summary: A finished run whose test of the candidate failed. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: finished + created_at: "2026-10-05T09:30:00Z" + finished_at: "2026-10-05T09:30:04Z" + failure_reason: null + result: + outcome: wrong_answer + compile_diagnostic: null + tests: + - source: example + index: 1 + outcome: accepted + time_ms: 21 + memory_kb: 9216 + diagnostic: null + - source: candidate + index: 1 + outcome: wrong_answer + time_ms: 20 + memory_kb: 9180 + diagnostic: null + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_practice_runs.yml b/api/core/routes/candidate_assessment_attempt_practice_runs.yml new file mode 100644 index 0000000..1edf6c4 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_practice_runs.yml @@ -0,0 +1,78 @@ +post: + operationId: CreateMyAssessmentPracticeRun + summary: Start a debug run of a practice solution. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body names the practice item of the attempt and carries the language, the source, and up to ten tests of the candidate. + + A debug run executes the solution in the isolated sandbox against the public examples of the task and the tests of the candidate only. It never runs, lists, or scores a hidden check, and it changes neither the practice state, the verdict, nor the attempt version; the graded solution is submitted with SubmitMyAssessmentAnswer. The run is stored with its own identifier and executed asynchronously: the response is 202 with the run `queued`, and the client polls GetMyAssessmentPracticeRun. The source is never echoed. + + The practice must be the current item: the attempt is in `practice_pending` for the main practice or `additional_practice_pending` for the additional one, and its deadline has not passed. Otherwise the server answers 409 state_conflict. + + Limits. Debug runs are bounded by a per-candidate rate limit and by one unfinished run per practice; either answers 429 rate_limited with Retry-After. The sandbox queue holds one running and ten waiting runs and submissions together; when it is full the server answers 503 service_unavailable with Retry-After and stores nothing. When code practice is not enabled on this server, the server answers 503 service_unavailable without Retry-After and stores nothing. + + Repeats. A retry with the same Idempotency-Key and body within 24 hours returns the stored run in its current state with 202, without starting another run. A different body with the same key answers 422 idempotency_key_reused. Refusals (400, 404, 409, 429, 503) are not stored under the key and are evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the availability of code practice (503), the Idempotency-Key (422, replay), the attempt and the practice (404 not_found for an unknown attempt or item, or one of another candidate), the state (409), the solution against the item (400 with a pointer such as `/language` or `/source_code`), the limits (429), then the queue (503). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PracticeRunCreate + examples: + run: + summary: A Python solution with one test of the candidate. + value: + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + language: python + source_code: "print(sum(map(int, input().split())))\n" + tests: + - input: "2 3\n" + expected_output: "5\n" + responses: + "202": + description: The run is queued, or this request was already accepted and the stored run is returned. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PracticeRun + examples: + queued: + summary: A queued run. + value: + id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a70 + item_id: 0192a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60 + state: queued + created_at: "2026-10-05T09:30:00Z" + finished_at: null + failure_reason: null + result: null + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/StateConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + "503": + $ref: ../components/responses.yml#/ServiceUnavailable + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_result.yml b/api/core/routes/candidate_assessment_attempt_result.yml new file mode 100644 index 0000000..f3be564 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_result.yml @@ -0,0 +1,48 @@ +get: + operationId: GetMyAssessmentResult + summary: Read the result of an assessment attempt of the current candidate. + description: |- + Requires the session cookie of a candidate account. Returns the immutable result of a terminal attempt: `completed`, `expired`, or `insufficient_bank`. A real result records the mode, policy, bank, and algorithm versions, decision, previously confirmed grade, calibration status and limitations, uncertainty where the method computes it, practice verdicts, weak domains, working time as a separate label, and allowed next steps. A corrective result also carries the root attempt and its immutable chain deadline. A `demo_express` result is a short educational summary only: it has no category, percentile, confirmed grade, score, uncertainty, or qualification evidence. A later policy, bank, or algorithm version never changes a result. + + Fields that the method does not compute are null and never zero: a `demo_basic` result has null `uncertainty` and `strength`. The result never contains answers, per-item correctness, answer keys, seeds, hidden checks, or anti-cheat signals. + + An active attempt answers 409 state_conflict; an attempt in `additional_practice_pending` is active and has no result yet. This GET is read-only and never commits a due transition. If a deadline has passed but the due transition is not yet stored by a command or background worker, the attempt remains active for this read and answers 409; wait for the transition and retry. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; employers see only the current category through a separate projection, never this result or the attempt history. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + responses: + "200": + description: The result. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentResult + examples: + demo_basic: + $ref: ../components/examples.yml#/AssessmentDemoBasicResult + adaptive_confirmed: + $ref: ../components/examples.yml#/AssessmentAdaptiveResult + adaptive_not_confirmed: + $ref: ../components/examples.yml#/AssessmentNotConfirmedResult + insufficient_bank: + $ref: ../components/examples.yml#/AssessmentInsufficientBankResult + corrective: + $ref: ../components/examples.yml#/AssessmentCorrectiveResult + demo_express: + $ref: ../components/examples.yml#/AssessmentExpressResult + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentResultNotReady + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_sessions.yml b/api/core/routes/candidate_assessment_attempt_sessions.yml new file mode 100644 index 0000000..3b419f2 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_sessions.yml @@ -0,0 +1,65 @@ +post: + operationId: StartMyAssessmentAttemptSession + summary: Start or resume a work session for the current candidate's attempt. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The body carries the attempt version the candidate last read. The server checks ownership, idempotency, and `expected_version` atomically before starting a session; a stale version answers 412 and consumes no session. Repeating the same key and body within 24 hours replays the stored response. + + Creation starts session 1. After `idle_timeout_seconds` of inactivity, the candidate uses this command to start the next session. Calling it while a session is already active returns the current attempt without consuming another session or advancing its version. Starting a session advances the version once. The command cannot extend `expires_at` or `chain_deadline`. + + If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it. + + One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in another window. That refusal is not stored under the Idempotency-Key, because it lasts only until the other page closes or stops renewing. A real attempt that nobody holds is not refused. + + The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + - $ref: ../components/parameters.yml#/AttemptClient + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttemptSessionStart + example: + expected_version: 7 + responses: + "200": + description: >- + The current attempt after starting or resuming work, or after a due + terminal transition was committed. A replay returns the stored body. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + resumed: + $ref: ../components/examples.yml#/AssessmentAttemptResumed + terminal: + $ref: ../components/examples.yml#/AssessmentAttemptCompleted + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/AssessmentCommandConflict + "412": + $ref: ../components/responses.yml#/AssessmentVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempt_work_session.yml b/api/core/routes/candidate_assessment_attempt_work_session.yml new file mode 100644 index 0000000..29de5a6 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempt_work_session.yml @@ -0,0 +1,74 @@ +put: + operationId: HoldMyAssessmentWorkSession + summary: Hold the single active work session of a real assessment attempt for this page. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page at a time. The page that works on the attempt calls this operation when the candidate starts or resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until `held_until`. + + - If nobody holds the work session, the previous holder released it, or its hold expired, the page becomes the holder and the answer is 200. + - If the same page holds it, the hold is renewed and the answer is 200. + - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops renewing and its hold expires. The client tells the candidate that the attempt is open in another window and does not show the task. + + The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a candidate who closes a page, reloads, or opens the attempt on another device can continue when the hold is released or has expired (at most two minutes after the last renewal). It is not a security boundary: a client that never calls this operation is refused only while another page holds the session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound to the attempt; it never stores or returns either value. A change of the User-Agent digest during an attempt is a weak server signal for a manual review, never an automatic decision. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the hold (409 state_conflict). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/AttemptClientRequired + responses: + "200": + description: The page holds the work session until `held_until`. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentWorkSession + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/StateConflict + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: ReleaseMyAssessmentWorkSession + summary: Release the work session that this page holds. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can open the attempt in another window at once instead of waiting for the hold to expire. The request is idempotent and reveals nothing: it answers 204 whether this page held the session, another page holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a lost response succeeds. A page that is killed without calling it loses the hold within two minutes. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the release (204). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/AttemptClientRequired + responses: + "204": + description: This page no longer holds the work session. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_attempts.yml b/api/core/routes/candidate_assessment_attempts.yml new file mode 100644 index 0000000..c41a624 --- /dev/null +++ b/api/core/routes/candidate_assessment_attempts.yml @@ -0,0 +1,74 @@ +post: + operationId: CreateMyAssessmentAttempt + summary: Start a real, corrective, or training assessment attempt. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The request is one of three disjoint shapes. A real assessment names a specialization, target grade, and task language; the server picks `demo_basic` or `adaptive` and fixes the policy, bank, and algorithm versions, limits, and item variants. A corrective real assessment also names `root_attempt_id`; the server verifies the lower-grade chain and reuses its fixed quota and deadline. The client never sends a real mode, a seed, a version, or a chain deadline. Explicit `demo_express` starts a separate interactive training run that lasts 3 to 5 minutes, has no category or target grade, and creates no qualification evidence or percentile. Creation starts session 1. The self-assessed grade only chooses where a real test starts and adds no points. An adaptive retest starts from the previous ability estimate of the specialization, adjusted for the time passed, so a new attempt adds evidence instead of starting the measurement over. + + A specialization has at most one active real attempt. A new root attempt cannot start while one is active, during a retry or promotion interval, past the root quota, or when the bank is insufficient; each such preflight refusal answers 409 state_conflict and creates nothing or consumes no root slot. Starting a root attempt reserves one slot in the root quota. A corrective attempt must reference its root, target a strictly lower grade not already attempted in that chain, and remain inside the root's fixed quota and deadline (72 hours from the root start in the current policy). It gets its own item, practice, and session limits, but spends no additional root slot and cannot reset the chain deadline or any 30/90-day timer. After a failure, including the first test, a lower grade can be tested at once. An expired or incomplete attempt does not create a free new chain; an insufficient bank or sandbox failure does not grant another root slot. `demo_express` is outside real-assessment availability, quotas, retry intervals, and qualification history. + + The limits are server-side: `expires_at` and `sessions` come from the policy version, the client clock never extends them, and after them the attempt accepts no work command. For a corrective attempt, `expires_at` is no later than the root's immutable `chain_deadline`. Within these limits the attempt is also bounded by the item limit of its policy. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 or 409 state_conflict response and creates nothing, so a lost response never creates a second attempt. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer, for example `/specialization` for a specialization that is not in the questionnaire or `/task_language` for a language that the bank does not offer), then availability (409 state_conflict). The rate limit can answer 429 with Retry-After before any of them; it is not stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttemptCreate + examples: + backend_junior_go: + $ref: ../components/examples.yml#/AssessmentAttemptCreateBackendJunior + corrective_backend_junior_go: + summary: Start a lower-grade assessment inside an existing correction chain + value: + kind: corrective + specialization: backend + target_grade: junior + task_language: go + root_attempt_id: 01928f7b-1111-7a2b-8c3d-4e5f6a7b8c9d + demo_express: + summary: Start a short educational training run + value: + kind: demo_express + responses: + "201": + description: >- + The attempt was created, or a retry with the same Idempotency-Key + replayed its creation. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAttempt + examples: + demo_basic_created: + $ref: ../components/examples.yml#/AssessmentAttemptCreated + corrective_created: + $ref: ../components/examples.yml#/AssessmentCorrectiveAttemptCreated + demo_express_created: + $ref: ../components/examples.yml#/AssessmentExpressAttemptCreated + "400": + $ref: ../components/responses.yml#/AssessmentAttemptCreateValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "409": + $ref: ../components/responses.yml#/AssessmentCreateConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_availability.yml b/api/core/routes/candidate_assessment_availability.yml new file mode 100644 index 0000000..7350905 --- /dev/null +++ b/api/core/routes/candidate_assessment_availability.yml @@ -0,0 +1,32 @@ +get: + operationId: GetMyAssessmentAvailability + summary: Read which assessment attempts the current candidate can start. + description: |- + Requires the session cookie of a candidate account; the candidate comes from the session. For each specialization of the questionnaire, returns the confirmed grade, the active attempt, and for every grade whether an attempt can start now, in which mode, and with which limits: the time limit, the session limit, the item limit, and whether a code practice is required. The client shows them before the start, together with the method and the signals that are collected, and resumes an active attempt by `active_attempt_id`, for example after it lost the response of CreateMyAssessmentAttempt. + + `insufficient_bank` is the state of a category whose bank is not published or has too few families that this candidate has not seen; the server limits attempts instead of repeating families. `cooldown` carries the date when the attempt opens, so the client can explain a blocked attempt with that date and offer support. Specializations and their retry intervals are independent. Attempts that ended as `insufficient_bank` or with the reason `sandbox_unavailable` are platform limitations and never cause a `cooldown`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - assessment + responses: + "200": + description: Assessment availability of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentAvailability + examples: + backend_and_network_engineer: + $ref: ../components/examples.yml#/AssessmentAvailability + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_results.yml b/api/core/routes/candidate_assessment_results.yml new file mode 100644 index 0000000..9325906 --- /dev/null +++ b/api/core/routes/candidate_assessment_results.yml @@ -0,0 +1,41 @@ +get: + operationId: ListMyAssessmentResults + summary: List immutable real assessment results of the current candidate. + description: |- + Requires a candidate session. Returns only completed root and corrective results owned by this candidate, newest first by decided_at and attempt_id. demo_express training results never appear. The cursor is opaque and bound to this candidate and listing; a malformed or foreign cursor returns 400 validation_failed. + + A v2 result includes the category decision captured when that attempt ended, including the confirmed grade then in force. Legacy v1 results omit category_decision because a later category must not be projected backward. Later policy, bank, review, or category changes do not alter either result. Employers cannot read this history; their separate projection contains only the current permitted category and no answers. + security: + - sessionCookie: [] + tags: + - assessment + parameters: + - name: limit + in: query + required: false + description: Maximum number of results per page. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 50 + default: 20 + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: One owner-scoped page of immutable results. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentResultHistoryPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_signal_notice.yml b/api/core/routes/candidate_assessment_signal_notice.yml new file mode 100644 index 0000000..c183519 --- /dev/null +++ b/api/core/routes/candidate_assessment_signal_notice.yml @@ -0,0 +1,71 @@ +get: + operationId: GetMyAssessmentSignalNotice + summary: Read whether the current candidate acknowledged the signal notice. + description: |- + Requires the session cookie of a candidate account with a confirmed email; the candidate comes from the session. Returns the notice version that the server requires now and whether this candidate acknowledged it. The notice lists the signals that are collected during a real assessment attempt and states that images, sound, and clipboard contents are not collected. Client signals are the time away from the tab or window, copy, paste and cut with a size only, and exits from fullscreen mode. Server signals are the response time of each item measured by the server, a change of network address during the attempt, parallel sessions, and the comparison of answers to variants of the same task by candidates. The server stores for these only one-way keyed digests: it stores no network address, no session token, and no answer text. Client signals are stored only while the C3 consent is current. The notice also lists the measures that the page applies during a real attempt: fullscreen mode, hiding the task when the candidate leaves fullscreen, the tab, or the window, blocking copy, selection, the context menu, drag, and printing of the task text, and blocking paste into answer fields (paste into the practice code editor is allowed and recorded as a signal with a size only). A watermark on the task page is announced as planned. These measures are applied by the client and never change a score, a category, or a quota. The client shows the notice before a real attempt starts and does not start the attempt until the notice is acknowledged. + + The acknowledgement is stored on the server per account and notice version, so it survives a reload and a new browser. An acknowledgement of an earlier version never counts for the current one: when the text gains a version, every candidate acknowledges it again. It is not a consent and never changes C3: the signal operation still requires a current C3 consent, and an unacknowledged notice does not make that operation fail. The demo_express training mode collects no signals and needs no acknowledgement. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account or an unconfirmed email answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - assessment + responses: + "200": + description: The notice version and the acknowledgement state of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalNotice + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem +put: + operationId: AcknowledgeMyAssessmentSignalNotice + summary: Record that the current candidate read the signal notice. + description: |- + Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body carries the notice version the candidate was shown. The server stores the acknowledgement for the account and that version; the response carries the server time of the first acknowledgement. + + The operation needs no Idempotency-Key: it is idempotent. Repeating it for an acknowledged version changes nothing, keeps the first time, and answers 200, so a retry after a lost response succeeds. A version other than the one the server requires answers 409 state_conflict and stores nothing; the client reads the notice again. + + The acknowledgement is not a consent. It does not grant, replace, or hide C3, and it does not affect the signal operation or any score, category, or quota. The body carries no signal, answer, or clipboard data. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account (403 forbidden), then the version (409). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalNoticeAcknowledgement + responses: + "200": + description: The stored acknowledgement, new or repeated. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalNotice + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "409": + $ref: ../components/responses.yml#/StateConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_assessment_signals.yml b/api/core/routes/candidate_assessment_signals.yml new file mode 100644 index 0000000..3b08129 --- /dev/null +++ b/api/core/routes/candidate_assessment_signals.yml @@ -0,0 +1,53 @@ +post: + operationId: RecordMyAssessmentAttemptSignals + summary: Store a bounded batch of client-reported assessment signals. + description: |- + Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt, remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks every item_instance_id against that attempt, and commits the receipt and any events in one transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express remains a separate training mode and receives no signal storage or grade effect. + + The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents, arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers. Client timestamps must be within five minutes before attempt creation and five minutes after the database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed with the assessment attempt or account; this release does not promise an independent expiry schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses. + + A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt without storing another batch; using that key with another body answers 422. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - assessment + parameters: + - $ref: ../components/parameters.yml#/AssessmentAttemptId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalBatch + responses: + "200": + description: >- + The stored or replayed receipt. A saturated receipt explicitly says + that none of this batch's events was stored. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AssessmentSignalReceipt + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/StateConflict + "413": + $ref: ../components/responses.yml#/PayloadTooLarge + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_evidence.yml b/api/core/routes/candidate_evidence.yml new file mode 100644 index 0000000..6f95620 --- /dev/null +++ b/api/core/routes/candidate_evidence.yml @@ -0,0 +1,39 @@ +get: + operationId: ListMyEvidence + summary: List the skill evidence of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own facts. Returns a page, newest event first with the fact identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + A fact is derived from the immutable result of a confirmed real assessment (root or corrective), in the same transaction that stores the result. Each fact names its source (the event and the result, which the candidate can open at `GetMyAssessmentResult`), the skills of the event, the grade that was passed with its basis and calibration, the attribution, the date, the visibility, and the trust level. An online assessment without a reliable confirmation of the identity has trust 1. One source event is one fact: its skills are tags of that fact, so several tags never make several facts. + + The list never carries raw answers, items, scores, failed attempts, or anti-cheat data. A failed attempt, a result without a reviewed category source, and an express training run (`demo_express`) create no fact, so reading the list before and after an express run shows no new fact. The list includes facts the candidate hid, with `visibility` `hidden`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account, or a candidate with an unverified email, answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another candidate, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - evidence + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the skill evidence of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EvidenceFactList + examples: + page: + $ref: ../components/examples.yml#/EvidenceFactListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_invitation.yml b/api/core/routes/candidate_invitation.yml new file mode 100644 index 0000000..21f444b --- /dev/null +++ b/api/core/routes/candidate_invitation.yml @@ -0,0 +1,46 @@ +get: + operationId: GetMyInvitation + summary: Open the terms of an invitation addressed to the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session; the invitation must be addressed to this candidate. + + Returns the organization, the current terms version with the full terms, the state, and the deadline. While an acceptance is possible (`delivered` or `viewed` before the deadline), `contact_consent` holds the published text of the consent C4 for this organization and the kinds of contact that the profile holds, with nothing preselected; otherwise it is null. It is null as well when the profile holds no contact: a grant must cover at least one field, so the client asks the candidate to add a contact to the profile before accepting. After an answer the response holds the candidate's own decline or the contact grant that the acceptance created, with the selected kinds, its status, and whether the organization can read it now (`readable`, with `blocked_by` `visibility` when the profile is not published or is hidden from the organization), never contact values. The response never carries the candidate's handle, the need of the organization, the salary indicator of the organization, or any contact or salary minimum of the candidate. + + Reading has no side effect on the invitation: it never records a view. The client records that the candidate opened the terms with ViewMyInvitation, an explicit command, so a prefetch, a retry, or a cache refresh never changes the state that the organization sees. The only change a read can cause is the due expiry: a read at the deadline or later first applies the server transition to `expired` with `invitation_timeout`, which would happen without the read as well, and the response shows it. Reading earlier terms versions is planned as a separate operation. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found, so identifiers cannot be enumerated. An `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/MyInvitationId + responses: + "200": + description: The invitation in its current state. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateInvitation + examples: + delivered: + $ref: ../components/examples.yml#/CandidateInvitationDelivered + viewed: + $ref: ../components/examples.yml#/CandidateInvitationViewed + accepted: + $ref: ../components/examples.yml#/CandidateInvitationAccepted + declined: + $ref: ../components/examples.yml#/CandidateInvitationDeclined + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_invitation_accept.yml b/api/core/routes/candidate_invitation_accept.yml new file mode 100644 index 0000000..18df52e --- /dev/null +++ b/api/core/routes/candidate_invitation_accept.yml @@ -0,0 +1,69 @@ +post: + operationId: AcceptMyInvitation + summary: Accept the current terms and disclose the selected contacts. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. + + Only an acceptance of the current terms version with the consent C4 creates access to contacts (PRD FR12). The body names the `terms_version` the candidate read and accepts, the `expected_version` of the invitation, and `consent_c4`: the C4 text version that the candidate saw, `accepted: true`, and the contact fields the candidate selected. At least one field is required and nothing is preselected or defaulted, so a grant never covers a field the candidate did not choose. The fields come only from the candidate's profile; the request never carries contact values. + + Allowed in `delivered` and `viewed` before `response_deadline_at`; accepting directly from `delivered` is allowed, as in the PRD FR12 transition table. In one transaction the server moves the invitation to `accepted`, records the consent C4 in the consent ledger with the organization, the fields, the invitation, the terms version, and the text version and its hash, creates the contact grant for exactly those fields, and writes the audit event. The response is the invitation with `contact_grant`. The acceptance never publishes the profile (C2) and never bypasses a profile hidden from the organization: the grant alone does not guarantee a read, and the organization reads only while the visibility allows it. + + 412 or 409: a `terms_version` or `expected_version` that is not current answers 412 version_conflict, the repository status for a stale version, and records nothing; this is the stale terms case, for example after the organization raised the salary, and the client reads the invitation again and shows the new terms for a new decision. A state that does not allow an acceptance answers 409 state_conflict: `withdrawn`, `expired`, `declined`, `cancelled_by_candidate`, the planned `counter`, or a command received at the deadline or later, which is late. A terminal state and a passed deadline are checked before the versions: the server first applies the due expiry, and the client then gets 409 for a withdrawn, expired, or late invitation even when its versions are stale, so it shows the final state instead of rereading and retrying. The repository rule keeps 412 for any stale version, so clients branch on `version_conflict` to reread and on `state_conflict` to show the final state. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and an acceptance of an invitation that is already `accepted` whose `terms_version` and set of fields equal those of its `contact_grant`, the terms version and fields that the candidate accepted, answers 200 with it even with a new key, an older `expected_version`, or a current `terms_version` that a later raise advanced; no second consent, grant, or audit event is created. A different terms version or field set on an accepted invitation answers 409 state_conflict; changing the disclosed fields is a matter of the consent operations. Of two concurrent acceptances only one makes the transition. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on an accepted invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the versions), the versions (412), any other state that does not allow an acceptance (409 state_conflict), then the consent rules (400 with the pointer `/consent_c4/text_version` for a text version that is not the published one, or `/consent_c4/fields/0` for a field that the profile does not hold). The schema rejects a missing `terms_version`, an empty or repeated field list, an unknown field kind, `accepted` other than true, and unknown fields such as `email` or `phone`. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/MyInvitationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/InvitationAcceptance + examples: + email_only: + $ref: ../components/examples.yml#/InvitationAcceptEmailOnly + stale_terms: + $ref: ../components/examples.yml#/InvitationAcceptStaleTerms + responses: + "200": + description: >- + The accepted invitation with the contact grant, or the same + invitation when this acceptance was already made. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateInvitation + examples: + accepted: + $ref: ../components/examples.yml#/CandidateInvitationAccepted + visibility_blocked: + $ref: ../components/examples.yml#/CandidateInvitationAcceptedVisibilityBlocked + "400": + $ref: ../components/responses.yml#/InvitationAcceptValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/InvitationCommandConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_invitation_cancel.yml b/api/core/routes/candidate_invitation_cancel.yml new file mode 100644 index 0000000..4714c88 --- /dev/null +++ b/api/core/routes/candidate_invitation_cancel.yml @@ -0,0 +1,63 @@ +post: + operationId: CancelMyInvitation + summary: Cancel the participation in an invitation and revoke its contact grant. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. + + Moves an unfinished invitation to the terminal state `cancelled_by_candidate` (PRD FR12): `delivered`, `viewed`, `accepted`, and the planned stages up to `negotiation`. The process closes. In the same transaction the server revokes the contact grant that the acceptance of this invitation created, with the reason `participation_cancelled`, so the next contact read of the organization answers 404. Grants of other invitations or applications stay; revoking the consent C4 for the organization as a whole, which closes all of them, belongs to the consent operations. + + Cancel differs from decline and withdraw: a decline is the structured answer before an acceptance and counts as a response; a cancellation leaves the process at any unfinished stage, mostly after an acceptance, and carries no reason; a withdrawal is the organization's command and keeps the grant. Before an answer the client offers the decline. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a cancellation of an invitation that is already `cancelled_by_candidate` answers 200 with it even with a new key or an older `expected_version`. A terminal state other than `cancelled_by_candidate` answers 409 state_conflict even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 version_conflict. The deadline does not limit a cancellation. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a cancelled invitation (200), a terminal state (409 state_conflict, whatever the version), then the version (412). The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/MyInvitationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/InvitationCommand + examples: + cancel: + $ref: ../components/examples.yml#/InvitationCancelCommand + responses: + "200": + description: >- + The invitation in the state `cancelled_by_candidate` with its grant + revoked. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateInvitation + examples: + cancelled: + $ref: ../components/examples.yml#/CandidateInvitationCancelled + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/InvitationCommandConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_invitation_decline.yml b/api/core/routes/candidate_invitation_decline.yml new file mode 100644 index 0000000..f0029e3 --- /dev/null +++ b/api/core/routes/candidate_invitation_decline.yml @@ -0,0 +1,65 @@ +post: + operationId: DeclineMyInvitation + summary: Decline an invitation with a structured reason. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The candidate comes from the session. + + Allowed in `delivered`, `viewed`, and the planned `counter`, before `response_deadline_at`. Moves the invitation to the terminal state `declined` with the reason and the optional comment; no consent and no access arise (PRD FR12). A timely decline counts as an answer for the responsiveness metrics, not as a consent or a hire. The reason is one of InvitationDeclineReason, including the neutral `other`; no reason requires a comment. + + Visibility: the organization sees only the state `declined` and `responded_at`. It never sees the reason or the comment of an individual decline, because a reason such as `salary` would tell it that the hidden minimum is above the range. Reasons feed only aggregates with a minimum group size (planned); the comment is never shown to the organization, published, logged, or sent in a notification. The candidate reads both back in `decline`. A new invitation of the same organization to this candidate is possible only after the 30-day pause. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a decline of an invitation that is already `declined` with the same reason and comment answers 200 with it even with a new key or an older `expected_version`. A terminal state, another reason or comment on a declined invitation, and a command at the deadline or later answer 409 state_conflict even with a stale `expected_version`; otherwise a stale `expected_version` answers 412 version_conflict. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a declined invitation (200), a terminal state or a passed deadline (409 state_conflict, whatever the version), the version (412), then any other state that does not allow a decline (409 state_conflict). The schema rejects an unknown reason, an empty comment or one of only white space, a comment over 500 characters, and unknown fields. The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/MyInvitationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/InvitationDeclineRequest + examples: + other_without_comment: + $ref: ../components/examples.yml#/InvitationDeclineOther + with_comment: + $ref: ../components/examples.yml#/InvitationDeclineWithComment + responses: + "200": + description: >- + The declined invitation with the candidate's own reason, or the same + invitation when this decline was already made. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateInvitation + examples: + declined: + $ref: ../components/examples.yml#/CandidateInvitationDeclined + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/InvitationCommandConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_invitation_view.yml b/api/core/routes/candidate_invitation_view.yml new file mode 100644 index 0000000..294ab87 --- /dev/null +++ b/api/core/routes/candidate_invitation_view.yml @@ -0,0 +1,47 @@ +post: + operationId: ViewMyInvitation + summary: Record that the current candidate opened the terms of an invitation. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The candidate comes from the session. The request has no body. + + The view transition of PRD FR12 is an explicit command, so reading the invitation with GetMyInvitation stays free of side effects. The client sends it when the candidate opens the terms screen. For a `delivered` invitation the server moves it to `viewed`, sets `viewed_at`, advances `version`, and keeps the deadline. In any other state, including `viewed`, `accepted`, and the terminal states, it changes nothing and answers 200 with the current invitation. A view never reopens, extends, or answers an invitation, and the organization sees only the state `viewed` and `viewed_at`. + + The command is idempotent by its effect: the first view wins and every repeat returns the current invitation. It therefore needs no Idempotency-Key and no `expected_version`: a view must never fail because the invitation changed after the client read it, for example after a salary raise. A view at the deadline or later first applies the due expiry and answers 200 with `expired`. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; a draft, an invitation addressed to another candidate, and an unknown identifier all answer 404 not_found. An `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/MyInvitationId + responses: + "200": + description: >- + The invitation, now `viewed` when it was `delivered`, otherwise in + its current state. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateInvitation + examples: + viewed: + $ref: ../components/examples.yml#/CandidateInvitationViewed + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_invitations.yml b/api/core/routes/candidate_invitations.yml new file mode 100644 index 0000000..8df47da --- /dev/null +++ b/api/core/routes/candidate_invitations.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyInvitations + summary: List the invitations addressed to the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns a page of the candidate's inbox, newest first by delivery time with the identifier as the tie-breaker, with cursor pagination: every invitation that was delivered to this candidate, in any later state, including withdrawn and expired ones. Drafts and invitations addressed to other candidates are never listed. + + A summary has the organization, the state, the versions, the role, the salary range, the work formats, and the deadline. Listing never records a view: the state `delivered` stays until ViewMyInvitation records that the candidate opened the terms. Responsiveness metrics of the organization and filters by state are planned and add fields or optional parameters. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the invitations of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateInvitationList + examples: + last_page: + $ref: ../components/examples.yml#/CandidateInvitationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_notification_read.yml b/api/core/routes/candidate_notification_read.yml new file mode 100644 index 0000000..d9d19a6 --- /dev/null +++ b/api/core/routes/candidate_notification_read.yml @@ -0,0 +1,43 @@ +post: + operationId: MarkMyNotificationRead + summary: Mark an item of the inbox of the current candidate as read. + description: |- + Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request has no body. + + The command is idempotent by its effect: the first mark stores the read time and every repeat returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no content, so marking an item whose content is no longer available still works. It changes no other item. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/NotificationId + responses: + "200": + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationReadReceipt + examples: + read: + $ref: ../components/examples.yml#/NotificationReadReceipt + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_notifications.yml b/api/core/routes/candidate_notifications.yml new file mode 100644 index 0000000..b494b94 --- /dev/null +++ b/api/core/routes/candidate_notifications.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyNotifications + summary: List the inbox of the current candidate. + description: |- + Requires the session cookie of a candidate account with a confirmed email. The recipient comes from the session, never from a request parameter, so the response holds only the caller's own items. Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The inbox is the in-platform delivery state of a notification. An item exists as soon as the event reached the platform, whether or not any email was sent, and an email that failed or was never sent does not block it. The inbox stores a reference to the event, not its text: the `content` of every item is resolved from the current source for this recipient on this read. When the source is gone or the recipient may not see it now (for example the candidate hid the organization), the item stays in the list with `content` null, and no earlier text is shown. An event that is delivered twice is one item. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the inbox of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationList + examples: + page: + $ref: ../components/examples.yml#/NotificationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy.yml b/api/core/routes/candidate_privacy.yml new file mode 100644 index 0000000..980f184 --- /dev/null +++ b/api/core/routes/candidate_privacy.yml @@ -0,0 +1,34 @@ +get: + operationId: GetMyPrivacySettings + summary: Read the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. Returns the publication of the candidate card, the search status, and the number of hidden organizations in one read. The response is `Cache-Control: no-store`. + + A profile is closed by default. A candidate who never published reads `publication.state` `closed` with `closed_reason` `never_published`, an empty field set, and version 0; creating or saving the profile (`SaveMyProfile`) never publishes it, and no operation of the profile, the questionnaire, or an assessment changes these settings. The C2 consent, the search status, and the hidden organizations are three independent settings: the C2 record in the consent ledger proves that the candidate accepted the publication text, the publication records which fields are published, and the search status is a statement of the candidate that is not a consent. A change of one never changes another, and none of them ever makes the candidate more visible by itself: the search status lapses to the non-public `not_looking`, a revoked C2 closes the card, and a new C2 grant publishes nothing. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + "200": + description: The visibility settings of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PrivacySettings + examples: + new_candidate: + $ref: ../components/examples.yml#/NewCandidatePrivacySettings + published_and_looking: + $ref: ../components/examples.yml#/PublishedCandidatePrivacySettings + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_access_history.yml b/api/core/routes/candidate_privacy_access_history.yml new file mode 100644 index 0000000..064e2e9 --- /dev/null +++ b/api/core/routes/candidate_privacy_access_history.yml @@ -0,0 +1,39 @@ +get: + operationId: ListMyCardAccessHistory + summary: List the accesses of organizations to the card of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only accesses to the caller's own card. Returns a page, newest first with the record identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the contacts through an active contact grant (`contact_read`). Reading the history is not an access and writes nothing. A retained access record permits the candidate to see the organization's identifier and current name and to hide their profile from it. The nullable organization field is preserved for records whose organization cannot be presented. The entries carry no employee identity, search query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does not erase earlier permitted accesses from the history. + + Successful organization card reads are recorded transactionally with the visibility and quota checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an accepted workflow status alone never authorizes contact access. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the accesses to the card of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CardAccessList + examples: + page: + $ref: ../components/examples.yml#/CardAccessListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_hidden_organization.yml b/api/core/routes/candidate_privacy_hidden_organization.yml new file mode 100644 index 0000000..8746e53 --- /dev/null +++ b/api/core/routes/candidate_privacy_hidden_organization.yml @@ -0,0 +1,81 @@ +put: + operationId: HideOrganization + summary: Hide the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body: the path names the organization and the candidate comes from the session. The hiding is a record that belongs to the candidate and references the organization; it changes neither the C2 consent, nor the publication, nor the search status. + + The operation sets a state, so it is idempotent and needs no Idempotency-Key: hiding an organization that is already hidden answers 200 with the existing record and its original `hidden_at`, changes nothing, and writes no history record. There is one record per candidate and organization. + + Anti-enumeration: an organization that does not exist and an organization that the candidate cannot see answer the same 404 not_found, with the same body and without a timing or an error code that tells them apart, so the operation is not a way to ask whether an identifier belongs to an organization. The candidate may name an organization in their own card-access history or an existing hidden-organization record. Invitation visibility will be added with the invitation workflow, and a candidate lookup remains planned. The response names the organization only after that check, with its current name. The identifiers are random, the general rate limit applies and can answer 429 with Retry-After before any check, and the record never reveals to an organization that a candidate hides it. + + A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from other conflicts, and changes nothing, and a repeat of an existing hiding is never refused for the limit. + + Hiding an organization that holds an active contact grant of the candidate revokes that grant with the reason `visibility_closed` in the same transaction (planned together with the invitation operations). Lifting the hiding never reopens a grant. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), the organization and its visibility to the candidate (404 not_found), then the repeat (200), then the limit (409 state_conflict). Like every visibility change, hiding needs a verified email (a usecase requirement). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/HiddenOrganizationId + responses: + "200": + description: >- + The organization is hidden from the candidate profile: the new record + or the one that existed. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/HiddenOrganization + examples: + hidden: + $ref: ../components/examples.yml#/HiddenOrganizationRecord + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/HiddenOrganizationLimit + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: UnhideOrganization + summary: Lift the hiding of the candidate profile from one organization. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Deletes the hiding record of the candidate for the organization in the path. The request is idempotent: it answers 204 whether the organization was hidden, was not hidden, or does not exist, so the operation reveals nothing about the organization, and a repeat after a lost response succeeds. The record is deleted, the settings history keeps the event `organization_unhidden` only when a record was deleted. + + Lifting the hiding makes the candidate readable by that organization again only if the profile is published and the organization otherwise may read it. It changes neither the C2 consent, nor the publication, nor the search status, and it never reopens a contact grant that the hiding closed. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation of the path (400), account scenario (403 forbidden for an employer), then the deletion (204). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/HiddenOrganizationId + responses: + "204": + description: The organization is not hidden from the candidate profile. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_hidden_organizations.yml b/api/core/routes/candidate_privacy_hidden_organizations.yml new file mode 100644 index 0000000..513dffb --- /dev/null +++ b/api/core/routes/candidate_privacy_hidden_organizations.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyHiddenOrganizations + summary: List the organizations that the candidate hides the profile from. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records and no request can name another account. Returns a page of the hidden organizations, newest first with the organization identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The records belong to the candidate. An organization never reads them, never learns that it is hidden, and sees a hidden candidate exactly as it sees one who is not published: no search result, no card, no contact read. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the hidden organizations of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/HiddenOrganizationList + examples: + page: + $ref: ../components/examples.yml#/HiddenOrganizationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_history.yml b/api/core/routes/candidate_privacy_history.yml new file mode 100644 index 0000000..5c20ce1 --- /dev/null +++ b/api/core/routes/candidate_privacy_history.yml @@ -0,0 +1,37 @@ +get: + operationId: ListMyPrivacyHistory + summary: List the changes of the visibility settings of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, so the response holds only the caller's own records. Returns a page of the settings history, newest first with the event identifier as the tie-breaker, with cursor pagination. The response is `Cache-Control: no-store`. + + The history is append-only evidence of what the candidate published, hid, and announced, and when. A publication event keeps the published fields and the C2 record behind them, which is what the consent ledger deliberately does not carry (the C2 record proves the consent to the text, not the field set). A revocation of C2 and a lapse of the search status are computed and are not events here; the consent history shows the revocation. The history never contains a profile value. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the settings history of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PrivacyEventList + examples: + page: + $ref: ../components/examples.yml#/PrivacyEventListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_preview.yml b/api/core/routes/candidate_privacy_preview.yml new file mode 100644 index 0000000..4a1ffcf --- /dev/null +++ b/api/core/routes/candidate_privacy_preview.yml @@ -0,0 +1,38 @@ +get: + operationId: GetMyCardPreview + summary: Preview the anonymous card that organizations would read. + description: |- + Requires the session cookie of a candidate account. Returns a private preview of the permitted anonymous-card fields from the current profile, publication, and consent ledger. The response is `Cache-Control: no-store`. + + The preview creates no view or access record and is never shown to an organization. While the profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an organization's pseudonym. Organization-specific visibility filters and cohort checks can further generalize or suppress the card when an organization reads it. + + `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact schema and contains no name, email, phone, Telegram name, employer, salary figure, account identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical skills and generalized experience are exposed; arbitrary profile text and imported excerpts never appear. `categories` contains only confirmed assessment results. Self-assessed grades and work formats appear only through their separate explicit publication choices, and self-assessment never becomes a confirmed category. Salary compatibility is nullable and contains no salary amount. + + `evidence` shows what an organization would read in the evidence section of the card (`GetOrganizationCandidateEvidence`): for each category of the card, the one assessment fact that supports its confirmed grade, with its skill, the passed grade, the trust level, the year, and the basis and calibration (`synthetic_demo`, `uncalibrated`). It is null while `card` is null, and an empty list when the card shows no category or no visible fact supports one. The preview applies no organization or cohort, so an organization can still receive less. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - privacy + responses: + "200": + description: The anonymous card as organizations would read it now. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CardPreview + examples: + published: + $ref: ../components/examples.yml#/PublishedCardPreview + closed: + $ref: ../components/examples.yml#/ClosedCardPreview + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_publication.yml b/api/core/routes/candidate_privacy_publication.yml new file mode 100644 index 0000000..3178058 --- /dev/null +++ b/api/core/routes/candidate_privacy_publication.yml @@ -0,0 +1,56 @@ +put: + operationId: SetMyPublication + summary: Publish or close the anonymous candidate card. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new publication setting: `state` `published` with the non-empty set of card fields, or `closed` with an empty set. It changes only the publication; the search status and the hidden organizations stay as they were. + + Publication is not a consent and does not duplicate one. The consent C2 lives in the consent ledger (`ListMyConsents`); this setting refers to it. Publishing requires an active, unrevoked C2 record of the account and binds the publication to that record, so a client sends no consent identifier and cannot forge one. Without one the server answers 409 state_conflict with the entry `{in: body, pointer: /state, code: consent_required}` in `errors`, which tells it apart from every other conflict, and changes nothing: the client gives C2 first (planned in the consent settings) and then publishes. The server takes the C2 record under a share lock in the transaction that writes the publication, so a revocation that races with a publication either commits first (the publication is refused) or closes the card right after. A revocation of C2 closes the card at once, because `state` is computed from the unrevoked record; a later C2 grant never reopens it, and the candidate publishes again under the new record. The revocation path itself closes the stored publication and revokes the contact grants in its own transaction. A closing sent over a stored publication whose C2 was revoked is a real change: it stores the closing, records `publication_closed`, and revokes the grants as any closing does. Publishing, like every visibility change, needs a verified email (a usecase requirement; the unverified account cleanup deletes only accounts without such records). Publishing never adds a field that the body did not name, and a new `CardField` value is never published for a candidate who did not choose it. + + The field set contains only the groups of `CardField`. The full name, contacts, and the lowest salary have no value there, so no body can publish them. Only values that the candidate confirmed ever reach the card. Contacts reach an organization only through the contact grant (C4), and a profile that is published or closed changes none of the grants that exist; closing the publication, and hiding an organization that holds a grant, revoke the contact grants concerned with the reason `visibility_closed` in the same transaction as the change (planned together with the operations, see the invitation contract). + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first publication. If it is not the current version the server answers 412 version_conflict and changes nothing. The version travels in the body rather than in If-Match because the generated client cannot read the ETag header yet. A body that equals the stored setting changes nothing, keeps the version, and answers 200 even when `expected_version` is older, so a retry after a lost response succeeds without an Idempotency-Key. A version above the current one never existed and always answers 412. Every change is recorded in the settings history with its time, the fields, and the C2 record. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), rules that depend on the body alone (400), an unchanged body (200), a stale version (412), then the active C2 for a publication (409 state_conflict). The schema rejects an unknown field, a repeated or unknown card field, and more fields than there are groups; a published state with no field, and a closed state with a field, answer 400 validation_failed with the pointer `/fields`. Error bodies never repeat a submitted value. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/PublicationUpdate + examples: + publish: + $ref: ../components/examples.yml#/PublicationUpdatePublish + close: + $ref: ../components/examples.yml#/PublicationUpdateClose + responses: + "200": + description: >- + The saved publication with its new version, or the current one when + the body changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Publication + examples: + published: + $ref: ../components/examples.yml#/PublishedPublication + "400": + $ref: ../components/responses.yml#/PrivacyValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "409": + $ref: ../components/responses.yml#/PublicationConsentRequired + "412": + $ref: ../components/responses.yml#/PrivacyVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_privacy_search_status.yml b/api/core/routes/candidate_privacy_search_status.yml new file mode 100644 index 0000000..0f3813f --- /dev/null +++ b/api/core/routes/candidate_privacy_search_status.yml @@ -0,0 +1,54 @@ +put: + operationId: SetMySearchStatus + summary: Set or confirm the search status of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new status: `looking` ("Ищу") or `not_looking`. The status is a statement of the candidate and never a consent. It changes neither the C2 consent, nor the publication, nor the hidden organizations, and it does not close or open any contact grant; a candidate whose profile is closed who sets `looking` becomes visible to no one. + + `looking` stores the moment of the confirmation and a lapse time. The server takes the interval from the `search_status` section of the effective product policy (30 days in the demo policy, `searching_confirmation_interval_days`), stores the policy version it used, and fixes the lapse time then, so a later policy change moves no stored time. Setting `looking` again is the confirmation: it replaces the confirmation time with now and advances the version, also after a lapse. The body carries no time, interval, or policy version. + + After the lapse time the status holds as `not_looking` with `lapsed` true on the next read. The lapse is computed and written nowhere, so it needs no job, it can never make the candidate more visible, and it never touches the publication or the hidden organizations. A reminder before the lapse is a planned notification, not a part of this operation. + + Optimistic concurrency uses `expected_version` in the body, 0 for a candidate who never set the status; a stale or non-existent version answers 412 version_conflict and changes nothing. `not_looking` over a stored `not_looking` changes nothing and answers 200 even with a stale version. `looking` always changes the stored confirmation, so a retry of a confirmation whose response was lost with the old version answers 412 and the client reads the status again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), an unchanged `not_looking` (200), then a stale version (412). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - privacy + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SearchStatusUpdate + examples: + looking: + $ref: ../components/examples.yml#/SearchStatusUpdateLooking + responses: + "200": + description: >- + The saved search status with its new version, or the current one + when the body changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SearchStatus + examples: + looking: + $ref: ../components/examples.yml#/LookingSearchStatus + lapsed: + $ref: ../components/examples.yml#/LapsedSearchStatus + "400": + $ref: ../components/responses.yml#/PrivacyValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "412": + $ref: ../components/responses.yml#/PrivacyVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_profile.yml b/api/core/routes/candidate_profile.yml new file mode 100644 index 0000000..17ad324 --- /dev/null +++ b/api/core/routes/candidate_profile.yml @@ -0,0 +1,96 @@ +get: + operationId: GetMyProfile + summary: Read the private profile of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the profile yet gets 200 with version 0, every single field `unknown`, and empty lists rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing profile is not an error state. + + The profile is personal data that only its owner reads: full name, contacts, work history, and the lowest salary. It is a private resource and never an organization-visible one; organizations see a candidate through the anonymous card and, after an accepted invitation, through the contact grant, and no organization contract refers to this schema. The response is `Cache-Control: no-store`, and the server never writes its values to logs, metrics, URLs, or events. + + Every value carries its confirmation state and provenance, and every claim has trust level 0. The self-assessed grade of a role is separate from `confirmed_categories`, which only assessment results establish and which no request writes. The profile needs no file, no ML extraction, and no FSP account. + + `experience_overlaps` lists every pair of entries whose inclusive month ranges overlap. Its indices refer to this response's `experience` array and are scoped to the same `version`; each pair is either `needs_confirmation` or `confirmed`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - candidate + responses: + "200": + description: The private profile of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateProfile + examples: + new_candidate: + $ref: ../components/examples.yml#/NewCandidateProfile + backend_manual_with_suggestion: + $ref: ../components/examples.yml#/BackendCandidateProfile + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem +put: + operationId: SaveMyProfile + summary: Replace the private profile of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state of every field and list; see CandidateProfileUpdate for the decisions that it carries. It replaces the stored profile as a whole. + + Every field is optional in substance: a profile can be saved with any subset filled and the rest null or empty, so no value requires a resume, the ML service, an FSP account, or any other file or link. A successful save advances an account whose current onboarding step is candidate_profile to candidate_questionnaire, including a no-op save; it never moves a later step backwards. This update is atomic with the profile and its history. + + Provenance is the server's: a value typed in the form is `manual`, confirming a stored suggestion keeps its origin, and every claim keeps trust level 0. The body has no origin, trust level, confirmation time, confirmed grade, or category, and unknown fields are rejected. A self-assessed grade never becomes a confirmed grade or a category. + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing, and the client reads the profile again and reapplies its edits, so a concurrent edit from another tab or device is never lost silently. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for the questionnaire; the status and code are the same as for a failed If-Match. + + The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose values equal the stored ones, with the same decisions, changes nothing, keeps the version, and answers 200 with the current profile even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. A version above the current one never existed and always answers 412 version_conflict, even for an unchanged body. + + The save replaces the stored claims as a whole. A suggestion that an import stored and that the client did not render and send back with the decision `extracted` is dropped by the save; a client therefore sends every suggestion that it received, and a client that read an older version gets 412 instead of silently dropping a suggestion it never saw. + + Experience periods use inclusive calendar months. An overlap is allowed only when `confirmed_parallel_periods` explicitly acknowledges that the two date ranges are genuine parallel work. Each acknowledgement names two distinct experience indices and repeats their exact normalized `started_on` and `ended_on` values; both indices and periods must match the submitted array and `expected_version`. A new or changed period needs an acknowledgement in that PUT. The server carries an earlier acknowledgement only when the same two indices still contain the same dates; reordering or changing either date requires a new acknowledgement. Editing other experience fields does not invalidate a matching date-pair acknowledgement. A missing acknowledgement answers 400 with pointers to the period fields and changes nothing. Duplicate, out-of-range, self, and non-overlapping acknowledgements are invalid. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), a version above the current one (412), domain rules that depend on the body alone (400), then the rules that depend on the stored claims against the version: a decision `extracted` for a value that is not a stored suggestion answers 412 when `expected_version` is stale, because another save may have confirmed that value, and 400 when it is current; an unchanged body (200); any other change over a stale version (412). The schema rejects an unknown field, an unknown specialization or grade, a phone number outside E.164, a Telegram username without the leading @, an email that is not an address, a month outside `YYYY-MM`, a salary that is not a positive multiple of 1000, and more items than a list allows. The server also rejects a repeated tag, skill, or role specialization, a period that ends before it starts or lies in the future, a changed overlap without explicit confirmation, and a decision `extracted` for a value that is not a stored suggestion, with 400 validation_failed and pointers to the items, for example `/roles/1/specialization` or `/stack/1/status`. Error bodies never repeat a submitted value. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateProfileUpdate + examples: + backend_manual: + $ref: ../components/examples.yml#/BackendCandidateProfileUpdate + responses: + "200": + description: >- + The saved profile with its new version, or the current profile when + the body changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateProfile + examples: + backend_manual_with_suggestion: + $ref: ../components/examples.yml#/BackendCandidateProfile + "400": + $ref: ../components/responses.yml#/ProfileValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "412": + $ref: ../components/responses.yml#/ProfileVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_profile_repository_checks.yml b/api/core/routes/candidate_profile_repository_checks.yml new file mode 100644 index 0000000..9405647 --- /dev/null +++ b/api/core/routes/candidate_profile_repository_checks.yml @@ -0,0 +1,32 @@ +post: + operationId: RequestMyRepositoryChecks + summary: Ask the server to check the linked project repositories again. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The request has no body. It schedules a new check of every repository that the current profile links, for example after the candidate made a repository public, and answers 202 with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0. + + A check reads only public metadata from the public GitHub API (`api.github.com`): whether the repository exists and is public, its description, topics, languages, and the beginning of its README as plain text. The server never fetches any other host, never follows a redirect to another host, and never shows the fetched text; it uses it only for semantic ranking. A verified repository does not prove that the candidate wrote the code. + + The operation is limited per candidate: a second request inside the versioned window answers 429 rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + responses: + "202": + description: The checks are scheduled. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ProfileRepositoryCheckRequest + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/candidate_questionnaire.yml b/api/core/routes/candidate_questionnaire.yml new file mode 100644 index 0000000..8d11be8 --- /dev/null +++ b/api/core/routes/candidate_questionnaire.yml @@ -0,0 +1,84 @@ +get: + operationId: GetMyQuestionnaire + summary: Read the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account. The candidate comes from the session, never from a request parameter. A candidate who has not saved the questionnaire yet gets 200 with version 0 and no specializations rather than 404, so the client reads the version for the first save in the same way as for later ones and a missing questionnaire is not an error state. + + The response never contains a confirmed grade or a category; those come only from assessment results. A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account answers 403 forbidden. + security: + - sessionCookie: [] + tags: + - candidate + responses: + "200": + description: The questionnaire of the current candidate. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateQuestionnaire + examples: + new_candidate: + $ref: ../components/examples.yml#/NewCandidateQuestionnaire + backend_go_and_network_engineer: + $ref: ../components/examples.yml#/BackendGoAndNetworkEngineerQuestionnaire + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem +put: + operationId: SaveMyQuestionnaire + summary: Replace the questionnaire of the current candidate. + description: |- + Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body is the complete new state: one or two specializations, each with a self-assessed grade, task languages, stack tags, and stated experience or null, and the working context. It replaces the stored questionnaire as a whole. + + Self-assessment is a claim. It influences where the assessment starts and which grade the assessment step offers first, but it adds no points and never writes a confirmed grade or a category: a self-assessed `senior`, or the word "Senior" in a stack tag, never assigns the Senior category. A real profile stays invisible to employers until an assessment confirms a category. Choosing a specialization whose test is `in_development` is allowed; no assessment starts for it until its bank is published. Removing a specialization from the questionnaire does not change assessment results. + + Optimistic concurrency uses `expected_version` in the body: the client sends the `version` it read, 0 for the first save. If it is not the current version, the server answers 412 version_conflict and changes nothing; the client reads the questionnaire again. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet. The status and code are the same as for a failed If-Match, since the client action is the same. + + The operation needs no Idempotency-Key: it replaces the whole state and is idempotent. A body whose specializations and working context equal the stored ones changes nothing, keeps the version, and answers 200 with the current questionnaire even when `expected_version` is older, so a retry after a lost response of a successful save succeeds instead of failing with 412. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer), domain rules (400), then the version (412). The schema rejects more than two specializations, an unknown grade, specialization, or task language, and unknown fields. The server also rejects a repeated specialization and a task language that the specialization's published bank does not offer, with 400 validation_failed and pointers to the items, for example `/specializations/1/specialization` or `/specializations/0/task_languages/0`. + + A successful save on the onboarding step candidate_questionnaire advances the account to candidate_assessment (planned). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - candidate + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateQuestionnaireUpdate + examples: + backend_go_and_network_engineer: + $ref: ../components/examples.yml#/BackendGoAndNetworkEngineerQuestionnaireUpdate + responses: + "200": + description: The saved questionnaire with its new version. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/CandidateQuestionnaire + examples: + backend_go_and_network_engineer: + $ref: ../components/examples.yml#/BackendGoAndNetworkEngineerQuestionnaire + "400": + $ref: ../components/responses.yml#/QuestionnaireValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "412": + $ref: ../components/responses.yml#/QuestionnaireVersionConflict + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/catalog_specializations.yml b/api/core/routes/catalog_specializations.yml new file mode 100644 index 0000000..7ca2c31 --- /dev/null +++ b/api/core/routes/catalog_specializations.yml @@ -0,0 +1,24 @@ +get: + operationId: GetSpecializationCatalog + summary: Read the catalog of directions, specializations, and grades. + description: |- + Public operation without a session. Returns the directions with their specializations, the assessment availability of each specialization, and the grade scale. The candidate picks specializations and self-assessed grades from this catalog for the questionnaire, and the client joins the codes stored in the questionnaire with the titles here. + + The catalog is public because it is the same for every caller and contains no personal data: the product shows it before registration, and a public read lets intermediaries and the browser cache it. It reveals nothing beyond what the landing pages already show. + + A category is a specialization together with a confirmed grade. Task languages and the stack are attributes of a chosen specialization and never appear as categories. `test_availability` is derived from the published task banks at the time of the request, so it changes when a bank is published, without a contract change: the MVP opens an assessment only for a category with a published bank, and every other specialization is marked `in_development`. Presence in the catalog never means that its test is ready. + security: [] + tags: + - catalog + responses: + "200": + description: The catalog. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SpecializationCatalog + examples: + mvp: + $ref: ../components/examples.yml#/SpecializationCatalog + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/consents.yml b/api/core/routes/consents.yml new file mode 100644 index 0000000..d707f6a --- /dev/null +++ b/api/core/routes/consents.yml @@ -0,0 +1,45 @@ +get: + operationId: ListMyConsents + summary: List the consents of the current account with their history. + description: |- + Requires the session cookie of a candidate or an employer account. The subject comes from the session, never from a request parameter, so the response holds only the caller's own consents: no request can name another account, and records of other accounts are never listed. Returns a page of the consent ledger of the account, newest grant first with the identifier as the tie-breaker, with cursor pagination. + + The ledger is append-only. Every grant is a record with its purpose, the accepted text version, the source, and the grant time; the server also stores the hash of exactly the text the subject saw. A newer text version of the same purpose is a new record, and the earlier one becomes `superseded` without any change. A revocation stamps every unrevoked record of the purpose, and for c4 of one organization, once; a later grant is a new record. Purposes are independent. + + Without `state` the page lists the whole history; `state=active` lists the consents that hold now, one per purpose for c1, c2, c3, and c5 and one per accepted invitation for c4. A c4 record names the organization with the name its consent text showed (a snapshot that a later rename does not change), the selected contact fields, and the invitation with its terms version; it never carries a contact value. A c2 record proves the consent to the publication text; the published field set and its changes are evidence of the publication history. + + Settings grants of c1, c2, c3, and c5 require the currently published text and an explicit acceptance. Revoking c2, c3, or c5 is available in settings; c1 creates a durable account-deletion request, and c4 is revoked only for one organization. C4 is granted only in AcceptMyInvitation. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit`, `cursor`, or `state` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - consent + parameters: + - name: state + in: query + required: false + description: Lists only the records in this state; omit it for the whole history. + schema: + $ref: ../components/schemas.yml#/ConsentState + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the consent ledger of the current account. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentRecordList + examples: + history: + $ref: ../components/examples.yml#/ConsentRecordListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/healthz.yml b/api/core/routes/healthz.yml index a006981..03a25c3 100644 --- a/api/core/routes/healthz.yml +++ b/api/core/routes/healthz.yml @@ -11,3 +11,10 @@ get: application/json: schema: $ref: ../components/schemas.yml#/HealthResponse + examples: + ok: + summary: The process is responding + value: + status: ok + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/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_codes.yml b/api/core/routes/identity_email_verification_codes.yml new file mode 100644 index 0000000..a02ead1 --- /dev/null +++ b/api/core/routes/identity_email_verification_codes.yml @@ -0,0 +1,62 @@ +post: + operationId: ConfirmEmailByCode + summary: Verify an email with the six-digit code from the verification message. + description: |- + Public operation without a session. The verification message carries a six-digit code next to the link. The client sends the address, the code, and the password chosen for the registration that issued the code, so the user types only the code after registration. A reloaded page has no password in memory, so it asks for the address, the password, and the code together. + + The server finds the newest open verification token of the unverified account with this normalized address, whose registration is current and which carries a code. It compares the keyed digest of the code with the stored digest, checks the password against the token's pending password hash, and checks that the code has not expired. The code lives 30 minutes, or until the token ends if the token ends sooner. When all three checks pass, the server consumes the token, verifies the email, and applies the pending credentials in one transaction, exactly as the link confirmation does, and answers 200 with the same body. Success does not start a session. + + Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, or a code that was burned. This keeps the answer from showing which addresses have a pending registration. Every failed attempt of an open code counts against that token. The fifth failed attempt burns the token: the code and the link stop working, and the user must request a new message. A refused attempt changes nothing else. + + The same refusal is returned after the rate limits are checked. The operation is limited per client address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with Retry-After. A body that does not match the contract, such as a code that is not six digits, answers 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` otherwise. + security: [] + tags: + - identity + parameters: + - name: Origin + in: header + required: false + description: >- + The exact configured public application origin. This optional parameter + is read by the server as empty when absent, so the operation answers + csrf_check_failed rather than treating a missing Origin as an allowed + request. + schema: + type: string + minLength: 1 + maxLength: 2048 + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationCodeRequest + examples: + code: + summary: Address, code from the message, and the registration password + value: + email: candidate@example.com + code: "482915" + password: "correct horse battery staple" + 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#/EmailVerificationCodeFailed + "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_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..a03d30a --- /dev/null +++ b/api/core/routes/identity_email_verifications.yml @@ -0,0 +1,63 @@ +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 of the current registration answers verification_token_expired; an unknown, used, replaced, or superseded token answers verification_token_invalid, even when that token is also expired. Neither refusal changes anything. For both, the client offers a new link and sign-in, because the address may already be verified. + + Confirmation also requires the password chosen for the registration that issued this token. A token from a replaced registration cannot apply another registration's password or scenario. The server checks the password against the token's pending password hash before consuming the token, then applies that token's password, scenario, and onboarding step only if the current registration's C1 consent matches its registration version. A wrong password or token without pending registration data answers verification_token_invalid and leaves the account and token unchanged. + + 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. Missing Origin, the special value `null`, or an Origin other than the configured public application origin answers csrf_check_failed. + security: [] + tags: + - identity + parameters: + - name: Origin + in: header + required: false + description: >- + The exact configured public application origin. This optional parameter + is read by the server as empty when absent, so the operation answers + csrf_check_failed rather than treating a missing Origin as an allowed + request. + schema: + type: string + minLength: 1 + maxLength: 2048 + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationRequest + examples: + token: + summary: Token from the link and password chosen during registration + value: + token: q3Zt9b2Kx7LmP4vR8sW1yC6nD0fH5jA2eG9uI3oT7kE + password: "correct horse battery staple" + 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..2bd8c7f --- /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 plus the pending registration credentials, 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 advances the registration version, replaces the C1 record, invalidates every earlier verification token, and queues a message with a new token carrying the pending password hash, scenario, and onboarding step. The account's saved credentials and scenario change only when the address owner confirms that token with its registration password, so a pre-registration with someone else's password cannot take over the account. + - 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/core/routes/matches.yml b/api/core/routes/matches.yml new file mode 100644 index 0000000..b67237e --- /dev/null +++ b/api/core/routes/matches.yml @@ -0,0 +1,68 @@ +post: + operationId: SearchOrganizationMatches + summary: Search the current organization-visible candidate bank. + description: |- + Requires the session cookie of an employer account with an active owner membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The organization comes from the path and the active server-side membership. Hidden profiles, revoked or missing C2 publication, and the organization's visibility restrictions are applied before any result is returned. + + The body selects either a Need's `requirements_version` snapshot or the current organization-visible bank with explicit filters. A need reference uses `Need.requirements_version`, not the general `Need.version`; title or suggestion-only edits do not change the confirmed-requirements snapshot. An empty bank filter searches all otherwise eligible specializations, returning each specialization separately. + + A search reveals card content, so it is charged like card reads. The whole visible bank is ranked, but each group returns at most the versioned per-group limit and no total is returned. In the order `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of the organization (a candidate it already viewed inside the window costs nothing again, so repeating the search or opening the card afterwards does not charge twice) and appears in the candidate's access history with the fields actually returned. When the allowance ends, the entries already counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit, and it carries no count. No new error is returned for an exhausted allowance. + + Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed entries belong to `main` (FR09). Entries in `unconfirmed` are ordered by Fit, then coverage, then a stable internal tie-breaker that is never returned. Their category and strength remain null, and they have no theta, T, P, or test percentile. The search result uses the organization-scoped opaque `candidate_handle` as its display pseudonym and invitation reference, never a candidate account or profile identifier. + + The card context is limited to safe public fields: recognized stack tags, coarse experience, accepted work formats, and coarse salary compatibility. It contains no contact, candidate location, salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data. Evidence explanations use bounded codes, not free text. + + Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed requirements snapshot and the stored vector of the candidate's published card text (roles, recognized stack, and published projects with the public metadata of their verified repositories). The search never calls the ML service: vectors are computed in the background after a change, and an entry whose vectors are missing, stale for the current model, or not computed because ML is unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence` lists, for a need search, the confirmed requirements whose closest published card item reaches a similarity band of the versioned policy; it names a project only by the title that the candidate published with the `projects` card field and says whether its repository is a verified public one, never the repository address or owner. Showing a project title records the `projects` field in the candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5, the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not fail. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without active membership answers 404 not_found. The response is `Cache-Control: no-store`. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - organization + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/MatchSearchRequest + examples: + by_need: + $ref: ../components/examples/matches.yml#/SearchByNeed + by_bank_filters: + $ref: ../components/examples/matches.yml#/SearchByBank + responses: + "200": + description: Organization-visible candidates in separate match groups. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/MatchSearchResponse + examples: + three_groups: + $ref: ../components/examples/matches.yml#/ThreeGroups + empty: + $ref: ../components/examples/matches.yml#/Empty + ml_unavailable: + $ref: ../components/examples/matches.yml#/MLUnavailable + cohort_below_30: + $ref: ../components/examples/matches.yml#/CohortBelow30 + truncated: + $ref: ../components/examples/matches.yml#/Truncated + semantic_evidence: + $ref: ../components/examples/matches.yml#/SemanticEvidence + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/my_consent.yml b/api/core/routes/my_consent.yml new file mode 100644 index 0000000..03ff33c --- /dev/null +++ b/api/core/routes/my_consent.yml @@ -0,0 +1,89 @@ +put: + operationId: GrantMyConsent + summary: Record an explicit consent grant from settings. + description: |- + Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. The body names the current text version the user read and requires `accepted: true`; the server verifies that version is still current and stores the hash of the exact text. A stale version answers 400 validation_failed at `/text_version`, without writing a grant. + + C1 is available to candidate and employer accounts. C2, C3, and C5 are available only to candidate accounts. C4 is excluded and can be granted only by accepting an invitation. A repeated grant of the same current version returns the existing record; after revocation a grant creates a new record and never reopens a publication or restores an older grant. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Independent consent being granted. C4 is not available here. + schema: + $ref: ../components/schemas.yml#/ConsentSettingsPurpose + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentSettingsGrantRequest + responses: + "200": + description: The created or existing consent record. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentRecord + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed, or an employer tried to grant a candidate-only purpose. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + csrf: + $ref: ../components/examples.yml#/CsrfCheckFailed + forbidden: + $ref: ../components/examples.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: RevokeMyConsent + summary: Revoke a non-scoped consent from settings. + description: |- + Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session. Revokes every unrevoked record of c2, c3, or c5, including superseded records, and never changes another purpose. Repeating a revocation is harmless and creates no duplicate event. + + Revoking c2 immediately closes the stored publication and records privacy history in the same transaction; a downstream revocation intent is written to the outbox. A later c2 grant does not reopen publication or restore old grants. Revoking c3 does not block the manual assessment path. Revoking c5 makes the consent gate deny further FSP import and writes a durable stop/delete intent; an external FSP deletion adapter is not available yet. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope. + schema: + $ref: ../components/schemas.yml#/ConsentSettingsRevokePurpose + responses: + "204": + description: Consent revoked, or it was already revoked. + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed, or an employer account tried to revoke candidate consent. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + csrf: + $ref: ../components/examples.yml#/CsrfCheckFailed + forbidden: + $ref: ../components/examples.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/my_consent_c4.yml b/api/core/routes/my_consent_c4.yml new file mode 100644 index 0000000..2968c43 --- /dev/null +++ b/api/core/routes/my_consent_c4.yml @@ -0,0 +1,39 @@ +delete: + operationId: RevokeMyOrganizationContactConsent + summary: Revoke C4 for one organization. + description: |- + Requires a verified candidate session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The subject comes from the session; `org_id` is the only scope the caller may choose. The server revokes every unrevoked C4 record for this subject and organization, using the fields stored on those records to request downstream grant revocation. It does not affect another organization. Repeating the request is harmless and creates no duplicate event. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - consent + parameters: + - name: org_id + in: path + required: true + description: >- + Organization whose stored C4 grants this account revokes. A well-formed + identifier outside the account's stored records changes nothing and + does not reveal whether that organization exists. + schema: + type: string + format: uuid + responses: + "204": + description: C4 revoked for this organization, or no active C4 was present. + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + description: CSRF or Origin validation failed, or the caller is not a candidate. + content: + application/problem+json: + schema: + $ref: ../components/schemas.yml#/Problem + examples: + csrf: + $ref: ../components/examples.yml#/CsrfCheckFailed + forbidden: + $ref: ../components/examples.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/my_consent_texts.yml b/api/core/routes/my_consent_texts.yml new file mode 100644 index 0000000..5828cd9 --- /dev/null +++ b/api/core/routes/my_consent_texts.yml @@ -0,0 +1,36 @@ +get: + operationId: GetMyConsentText + summary: Read a current consent text for account settings. + description: >- + Requires a verified session. Returns the current published text and version + of c1, c2, c3, or c5 so the user can read the exact text before an explicit + settings grant. C4 is excluded: its text includes an organization snapshot + and it is granted only during invitation acceptance. The response is + private and is not cached. + security: + - sessionCookie: [] + tags: + - consent + parameters: + - name: purpose + in: path + required: true + description: Consent whose current text is requested. + schema: + $ref: ../components/schemas.yml#/ConsentSettingsPurpose + responses: + "200": + description: The current published consent text. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsentText + "401": + $ref: ../components/responses.yml#/Unauthenticated + "400": + $ref: ../components/responses.yml#/ValidationFailed + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/my_organizations.yml b/api/core/routes/my_organizations.yml new file mode 100644 index 0000000..4b21a40 --- /dev/null +++ b/api/core/routes/my_organizations.yml @@ -0,0 +1,39 @@ +get: + operationId: ListMyOrganizations + summary: List the organizations available to the current account. + description: |- + Requires the session cookie of an employer account. The account comes from the session, never from a request parameter, so the response holds only the caller's own memberships and no request can name another account. + + Returns a page of the organizations in which the caller has an `active` membership, newest membership first with the organization identifier as the tie-breaker, with cursor pagination. Each item names the organization (`OrganizationSummary`) and holds the caller's role and state in it (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not list its organization, so an organization the caller cannot enter is never named, and one that the caller was removed from disappears from the list at once. + + The list is the directory of the active organization context. The context is not stored on the server: every organization-scoped operation names its organization in the path `org_id`, and the server checks that identifier against the caller's active membership on every request, so a switch between organizations is a different `org_id` in the client's routes and cannot outlive a revoked membership. A client picks the context from this list, may remember the last choice in the browser as a convenience, and must read the list again after any answer 404 `not_found` from an organization path. An account with several memberships sees all of them here and works in one at a time; the rights and the data of the organizations stay separate. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden. An employer account without an organization gets an empty page, which tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - organization + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the organizations available to the current account. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/MyOrganizationList + examples: + one_organization: + $ref: ../components/examples.yml#/MyOrganizationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization.yml b/api/core/routes/organization.yml new file mode 100644 index 0000000..e71b1d5 --- /dev/null +++ b/api/core/routes/organization.yml @@ -0,0 +1,98 @@ +get: + operationId: GetOrganization + summary: Read an organization managed by the caller. + description: |- + Requires the session cookie of a verified employer account with an active owner membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing. + + Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. An active member whose role is not `owner` answers 403 forbidden. A malformed `org_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - organization + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + responses: + "200": + description: The organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Organization + examples: + name_only: + $ref: ../components/examples.yml#/OrganizationNameOnly + complete_card: + $ref: ../components/examples.yml#/OrganizationCompleteCard + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem +patch: + operationId: UpdateOrganization + summary: Change the profile of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the organization (the FR07 matrix gives this to no other role), so a member with another role answers 403 forbidden. The role comes from the server-side membership; the body has no organization, membership, role, owner, or verification field. + + Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null. + + The body can change the profile only. The verification level, its basis, the card, the members, and every role are not fields of it, and unknown fields fail validation, so the owner can neither raise the trust level of the organization nor the rights of anyone by editing the profile; a longer description, a verified-looking website, or a new representative leaves the level unchanged. The level and the roles change only through processes of the server. + + Versions: every committed change creates version `expected_version + 1` and answers 200 with the organization. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the organization again and reapplies its edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for needs. A body that changes nothing when applied to the current profile keeps the version and answers 200 with the current organization even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a change that already succeeded is harmless. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403 forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - organization + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationUpdate + examples: + complete_card: + $ref: ../components/examples.yml#/OrganizationUpdateCompleteCard + responses: + "200": + description: >- + The organization after the change, or the current organization when + the body changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Organization + examples: + complete_card: + $ref: ../components/examples.yml#/OrganizationCompleteCard + "400": + $ref: ../components/responses.yml#/OrganizationValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "412": + $ref: ../components/responses.yml#/OrganizationVersionConflict + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_candidate_card.yml b/api/core/routes/organization_candidate_card.yml new file mode 100644 index 0000000..84bed40 --- /dev/null +++ b/api/core/routes/organization_candidate_card.yml @@ -0,0 +1,45 @@ +get: + operationId: GetOrganizationCandidateCard + summary: Read one currently visible anonymous candidate card. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data. + + `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server resolves it against the current visible cohort, rechecks active membership, effective C2 publication, and the candidate's hiding settings on every request, and applies the cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle, a handle from another organization, a closed or revoked publication, a profile hidden from this organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found. + + The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever available, are a separate operation and require the current explicit C4 grant and contact-access policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks this read immediately. Republishing does not reopen an earlier contact grant. + + Every allowed employer card read is recorded in the access history and consumes the organization's current product-policy card-view quota. A repeated view within the quota window is allowed by the existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - privacy + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/CandidateHandle + responses: + "200": + description: The current anonymous card for this organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/AnonymousCardContent + examples: + published: + $ref: ../components/examples.yml#/OrganizationAnonymousCandidateCard + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_candidate_card_evidence.yml b/api/core/routes/organization_candidate_card_evidence.yml new file mode 100644 index 0000000..5c07161 --- /dev/null +++ b/api/core/routes/organization_candidate_card_evidence.yml @@ -0,0 +1,45 @@ +get: + operationId: GetOrganizationCandidateEvidence + summary: Read the permitted skill evidence of one currently visible candidate card. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and membership come from the current server-side session and path, never from cached search data. + + `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card projection. The server runs the same checks as the card read on every request: active membership, effective C2 publication, the candidate's hiding of this organization, and the minimum cohort. In addition the card must publish the `categories` field and show at least one category after the cohort rules, because the evidence explains those categories and discloses nothing beyond them. An unknown handle, a handle of another organization, a closed or revoked publication, a profile hidden from this organization, a profile suppressed by the minimum cohort, and a card without categories all answer the same 404 not_found. Closing C2 or hiding the organization blocks this read immediately, and a cached response proves nothing. + + The response lists, for each category of the card, the one visible fact that supports its confirmed grade: the earliest assessment that passed exactly that grade, so a lower grade or a retake adds nothing. A fact the candidate hid is absent. Each fact carries only the skill, the passed grade, the trust level, the year of the assessment, and the basis and calibration of the method (`synthetic_demo`, `uncalibrated`), which are the same for every candidate and say that the fact is a demonstration, not a validated measurement. It carries no identifier of the fact, event, result, or candidate, no month or exact time, and never an answer, item, score, failed attempt, review band, or anti-cheat signal. An express training run and a failed attempt create no fact. The answer has no key that joins it to a person, but it is not unlinkable: with the other values of the card it can narrow a small pool of candidates. + + Reading the evidence is a view of the candidate card: it consumes the organization's current card-view quota with the same distinct-card rule and is recorded in the access history with the `categories` field. When the quota is exhausted the operation answers 429 with Retry-After. The response is `Cache-Control: no-store`. + + A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an unknown organization or account without an active membership answers 404 not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - evidence + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/CandidateHandle + responses: + "200": + description: The permitted evidence of this candidate card for this organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationEvidence + examples: + permitted: + $ref: ../components/examples.yml#/OrganizationCandidateEvidence + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_invitation.yml b/api/core/routes/organization_invitation.yml new file mode 100644 index 0000000..f925302 --- /dev/null +++ b/api/core/routes/organization_invitation.yml @@ -0,0 +1,106 @@ +get: + operationId: GetOrganizationInvitation + summary: Read an invitation of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the server-side membership, never from the request. In the MVP only the owner of the organization reads invitations. + + Returns the invitation with the current terms version, the state, the deadline, the coarse salary indicator `salary_fit`, and `contact_access`. The candidate appears only as the opaque `candidate_handle`: before and after an acceptance this response never carries the candidate's name, email address, phone number, or other contact, the exact salary minimum, or the reason and comment of a decline. Contact values come only from GetOrganizationInvitationContacts while `contact_access.status` is `available`. Reading earlier terms versions is planned as a separate operation. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, and an invitation of another organization all answer 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the invitation answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/InvitationId + responses: + "200": + description: The invitation in its current state. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitation + examples: + draft: + $ref: ../components/examples.yml#/OrganizationInvitationDraft + delivered: + $ref: ../components/examples.yml#/OrganizationInvitationDelivered + accepted: + $ref: ../components/examples.yml#/OrganizationInvitationAccepted + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem +patch: + operationId: UpdateOrganizationInvitation + summary: Change the terms, the need link, or the response period of a draft. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The body has no organization, membership, or role field. In the MVP only the owner of the organization changes drafts. + + Only a `draft` can change; any other state answers 409 state_conflict. After sending, the only change of the terms is the one raise of the upper salary bound through RaiseOrganizationInvitationSalary. The candidate of a draft cannot change: a draft for another candidate is a new draft. + + Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged. `terms` is always sent complete and replaces the terms as a whole, with the same validation as on creation, so a package condition is never dropped by omission. `need` sent as null unlinks the need. + + Versions: every committed change creates version `expected_version + 1`; a change of the terms also creates the next terms version, an immutable snapshot, and a change of anything else keeps the terms version. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the invitation again. The version travels in the body because the generated client cannot read the ETag response header yet. The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current invitation even when `expected_version` is older. + + Salary limit: every change that can move `salary_fit` is an indicator-relevant setting: a change of either salary bound, of the tax basis, or of `work_formats`, because the indicator compares with the candidate's minimum for the offered formats, and switching formats or the basis would otherwise probe the minimum for free. Such a change counts against the limit shared by the organization with needs and other drafts, at most three settings a day, and against the withheld counter, which withholds `salary_fit` for seven days from the fifth setting within seven days (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and changes nothing. A change that keeps the range, the basis, and the formats does not count. The operation follows the convention of UpdateOrganizationNeed: no Idempotency-Key, and a body that changes nothing answers 200. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the invitation (404 not_found), a body that changes nothing (200), the version (412), the state (409 state_conflict), domain rules (400 with the pointers of CreateOrganizationInvitation), then the salary limit (429). + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/InvitationId + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitationUpdate + examples: + change_terms: + $ref: ../components/examples.yml#/InvitationUpdateTerms + responses: + "200": + description: >- + The draft after the change, or the current draft when the body + changes nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitation + examples: + updated: + $ref: ../components/examples.yml#/OrganizationInvitationDraftUpdated + "400": + $ref: ../components/responses.yml#/InvitationValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/StateConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_invitation_contacts.yml b/api/core/routes/organization_invitation_contacts.yml new file mode 100644 index 0000000..9fdd29f --- /dev/null +++ b/api/core/routes/organization_invitation_contacts.yml @@ -0,0 +1,43 @@ +get: + operationId: GetOrganizationInvitationContacts + summary: Read the contacts that the candidate disclosed to the organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. In the MVP only the owner of the organization reads contacts; the other roles of PRD FR07 are planned. + + This is the only operation that returns contact values, and its response is separate from the terms and from the invitation. It answers only while a grant created by the acceptance of this invitation is active and the read is allowed now: on every request the server checks the membership, the consent C4 for this organization, the grant and its fields, and the current visibility of the profile (C2 and the organizations the candidate hid the profile from), with no cache in between, so a revocation closes the next read at once. The response holds exactly the fields that the grant covers; every other field is null. A grant of organization A never answers for organization B. + + Without such a grant the contacts do not exist for the caller, and the operation answers 404 not_found, the same as for an unknown invitation: before an acceptance, after a decline or an expiry, after the candidate revoked C4 or cancelled the participation, after the candidate closed the visibility, and while a grant created when the profile was not published or was hidden from the organization stays blocked. The answer does not tell which applies; `contact_access` of GetOrganizationInvitation tells the organization whether access is `not_granted`, `available`, or `closed`, without the reason, and the candidate sees `readable` and `blocked_by` on the grant. Withdrawing the invitation keeps an existing grant. A later publication of the profile never reopens a closed grant; only a new explicit C4 creates a new one. + + Every successful read is recorded in the access audit (planned with the contact access history), and the response has `Cache-Control: no-store`. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown invitation, an invitation of another organization, and an invitation without an active readable grant all answer 404 not_found; a member whose role does not allow reading contacts answers 403 forbidden. An `org_id` or `invitation_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/InvitationId + responses: + "200": + description: The contacts that the active grant of this invitation covers. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ContactDisclosure + examples: + email_only: + $ref: ../components/examples.yml#/InvitationContactsEmailOnly + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_invitation_salary_raise.yml b/api/core/routes/organization_invitation_salary_raise.yml new file mode 100644 index 0000000..655d282 --- /dev/null +++ b/api/core/routes/organization_invitation_salary_raise.yml @@ -0,0 +1,65 @@ +post: + operationId: RaiseOrganizationInvitationSalary + summary: Raise the upper salary bound of a sent invitation once. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization changes invitations. + + After sending, the salary base is fixed and the lower bound never decreases; the upper bound may be raised exactly once in the whole history of the invitation (PRD FR13). The body carries only the new `salary_to`, so the request cannot change the lower bound, the currency, the period, or the tax basis. The new bound must be above the current one and keep the width of the range from 10% to 40% of its midpoint, otherwise 400 validation_failed with the pointer `/salary_to`. The raise creates the next terms version with every other term unchanged and the next invitation version; the candidate sees the new terms, and an acceptance that names the previous terms version answers 412 version_conflict. The deadline does not change. The raise follows its own once-only rule and does not count against the organization-wide daily limit of three range settings, but it counts against the withheld counter of `salary_fit` (five settings within seven days), because it moves the upper bound that the indicator compares. + + Allowed in `delivered`, `viewed`, and `accepted`, and in the planned states `counter`, `interview_scheduled`, `interviewed`, and `no_deal`, where FR13 lets a raise open an early repeated final. During `negotiation`, after `terms_agreed`, in a terminal state, in a `draft` (change the draft instead), and after the raise was used, the server answers 409 state_conflict. A raise after an acceptance changes neither the accepted terms version of the grant nor the grant. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a raise to the same `salary_to` that was already applied answers 200 with the current invitation even with a new key or an older `expected_version`. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat of an applied raise (200), a terminal state (409 state_conflict, whatever the version), the version (412), any other state that does not allow a raise and the used raise (409 state_conflict), then the bound and the width (400). The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/InvitationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/InvitationSalaryRaise + examples: + raise: + $ref: ../components/examples.yml#/InvitationSalaryRaiseCommand + responses: + "200": + description: >- + The invitation with the raised upper bound and the next terms + version, or the current invitation when the same raise was already + applied. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitation + examples: + raised: + $ref: ../components/examples.yml#/OrganizationInvitationSalaryRaised + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/InvitationCommandConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_invitation_send.yml b/api/core/routes/organization_invitation_send.yml new file mode 100644 index 0000000..ffea645 --- /dev/null +++ b/api/core/routes/organization_invitation_send.yml @@ -0,0 +1,65 @@ +post: + operationId: SendOrganizationInvitation + summary: Send a draft to the candidate's inbox. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization sends invitations. + + Sends the current terms version of a `draft`. Sending is internal and never visible as a state: in one transaction the server records the delivery, creates the candidate's inbox entry, starts the deadline `response_deadline_at = delivered_at + response_period_days`, spends one invitation of the weekly organization quota, and writes the outbox event for the notification, then answers 200 with the state `delivered`. A successful answer therefore means the candidate can already read the invitation; an email is a separate notification that never blocks or delays it, and its retries never move the deadline. No contact of the candidate is disclosed by sending. + + The server checks again that the candidate is still visible to the organization: a revoked publication C2 or a profile hidden from the organization answers 409 state_conflict without telling which. It also enforces the limits of the product policy: at most 20 invitations waiting for an answer per need (`delivered`, `viewed`, `counter`) and the 30-day pause for the pair of the organization and the candidate after a decline or a no deal, regardless of the member or the need, both with 409 state_conflict; and the rolling weekly quota of the organization, with 429 and Retry-After. The organization quota, the pending limit, and the pause after a decline are enforced; the pause after a no deal is planned, because no operation produces the state `no_deal` yet. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a send of an invitation that was already sent answers 200 with the invitation in its current state even with a new key or an older `expected_version`; the quota is spent once. A stale `expected_version` on a draft answers 412 version_conflict, so the organization never sends terms it did not read. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found), the repeat of a completed send (200), the version (412), the state, the visibility of the candidate, the pending limit and the pause (409 state_conflict), then the quota (429). 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/InvitationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/InvitationCommand + examples: + send: + $ref: ../components/examples.yml#/InvitationSendCommand + responses: + "200": + description: >- + The invitation in the candidate's inbox with the state `delivered` + and its deadline, or the invitation in its current state when it was + already sent. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitation + examples: + delivered: + $ref: ../components/examples.yml#/OrganizationInvitationDelivered + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/InvitationCommandConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_invitation_withdraw.yml b/api/core/routes/organization_invitation_withdraw.yml new file mode 100644 index 0000000..e918d52 --- /dev/null +++ b/api/core/routes/organization_invitation_withdraw.yml @@ -0,0 +1,62 @@ +post: + operationId: WithdrawOrganizationInvitation + summary: Withdraw an invitation. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. In the MVP only the owner of the organization withdraws invitations. + + Moves an unfinished invitation to the terminal state `withdrawn` (PRD FR12): a `draft`, which the candidate never sees, a `delivered` or `viewed` invitation before the answer, an `accepted` one, and the planned stages up to `negotiation`. The process closes and no further transition happens in it. Withdrawing a delivered invitation frees its place in the pending limit of the need but never returns the weekly quota. Withdrawing never revokes the consent C4 or a grant that already exists: an accepted invitation keeps its `contact_access`, because only the candidate closes the access, by revoking C4, cancelling the participation, or closing the visibility. + + `withdrawn` differs from `cancelled_by_candidate`: the organization withdraws, and the grant stays; the candidate cancels through CancelMyInvitation, and the grant of this invitation is revoked. A terminal invitation (`declined`, `expired`, `cancelled_by_candidate`) answers 409 state_conflict, even with a stale `expected_version`, so the organization sees the final state at once. + + Repeats return the same result: a retry with the same Idempotency-Key replays the stored response, and a withdrawal of an invitation that is already `withdrawn` answers 200 with it even with a new key or an older `expected_version`. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), the invitation (404 not_found, after any due expiry), the repeat on a withdrawn invitation (200), a terminal state (409 state_conflict, whatever the version), then the version (412). The general rate limit can answer 429 with Retry-After before any check. 404 and 409 state_conflict are stored under the key; 400, 412, and 429 are not. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/InvitationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/InvitationCommand + examples: + withdraw: + $ref: ../components/examples.yml#/InvitationWithdrawCommand + responses: + "200": + description: The invitation in the state `withdrawn`. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitation + examples: + withdrawn: + $ref: ../components/examples.yml#/OrganizationInvitationWithdrawn + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/InvitationCommandConflict + "412": + $ref: ../components/responses.yml#/InvitationVersionConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_invitations.yml b/api/core/routes/organization_invitations.yml new file mode 100644 index 0000000..d960691 --- /dev/null +++ b/api/core/routes/organization_invitations.yml @@ -0,0 +1,103 @@ +get: + operationId: ListOrganizationInvitations + summary: List the invitations of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the membership that the server holds for the session account, never from the request. In the MVP only the owner of the organization works with invitations, as with needs; the other roles of the PRD FR07 matrix are planned and change no field of this contract. + + Returns a page of invitation summaries in every state, drafts included, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. A summary names the candidate only by the opaque `candidate_handle` and has the state, the versions, the role, the salary range, the deadline, and the contact access without any contact value. A declined invitation shows the state `declined` without the reason or the comment. Filters by state and need are planned and add optional parameters. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member whose role does not allow reading invitations answers 403 forbidden. A malformed `org_id`, `limit`, or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the invitations of the organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitationList + examples: + last_page: + $ref: ../components/examples.yml#/OrganizationInvitationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem +post: + operationId: CreateOrganizationInvitation + summary: Create an invitation draft for one candidate. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The organization comes from the path and the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization may create an invitation. + + The draft is addressed to one person from a search result of this organization: `candidate_handle` is the opaque handle of that card, never an email address, a phone number, or an account identifier. The server resolves the handle for this organization only. An unknown handle, a handle of another organization, and a profile that the organization may no longer see, because the candidate revoked the publication C2 or hid the profile from it, all answer 400 with the pointer `/candidate_handle`, so a handle never reveals which case applies. `need` is optional: a direct invitation has none, and a need given must be a need of the organization with a `requirements_version` that it has had, otherwise 400 with the pointer `/need`. `response_period_days` is 3, 7, or 14 and defaults to 7. + + The terms are complete from the start (PRD FR12): the role, the specialization and the grade, the offer type, the tasks, the team, the technology stack, the work formats and the place of work, the communication method, the salary range in RUB with its tax basis, and the package. Each package condition is either `provided` with a description or explicitly `not_provided`; leaving one out fails validation. A draft without the tax basis or the communication method therefore cannot exist. The draft is created as version 1 with terms version 1, and the candidate does not see it until SendOrganizationInvitation. + + Salary: SalaryRange applies the same rules as for a need: whole rubles, positive multiples of 1000, `salary_from < salary_to`, and a width from 10% to 40% of the midpoint, checked by the server in integer arithmetic. The response carries `salary_fit`, the coarse indicator of PRD FR13 against the candidate's hidden minimum; the exact minimum appears in no response. The server never rejects a range because of the minimum, since a rejection would reveal it. Creating a draft is an indicator-relevant setting: it counts against the limit shared by the whole organization with the ranges of needs, at most three settings a day, and against the withheld counter, after five settings within seven days the indicator is `withheld` for seven days from the fifth, on every draft and invitation of the organization (PRD FR13, enforcement planned; see InvitationSalaryFit). Over the limit the server answers 429 with Retry-After and creates nothing. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second draft. A different body with the same key answers 422 idempotency_key_reused. 400 and 429 are never stored. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer: `/candidate_handle`, `/need`, `/terms/salary/salary_to` for a reversed range or a width outside 10-40%, `/terms/location` for the `office` or `hybrid` format without a place of work, or `/terms/tech_stack/1` for a repeated technology), then the salary limit (429). The schema already rejects a missing term or package condition, a salary bound that is not a positive multiple of 1000, an unknown currency, period, or tax basis, and unknown fields such as `state`, `version`, `salary_fit`, `candidate_email`, or `salary_minimum`. The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - invitation + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitationCreate + examples: + valid_invitation: + $ref: ../components/examples.yml#/InvitationCreateFromNeed + responses: + "201": + description: >- + The draft was created as version 1 with terms version 1, or a retry + with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationInvitation + examples: + draft: + $ref: ../components/examples.yml#/OrganizationInvitationDraft + "400": + $ref: ../components/responses.yml#/InvitationValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "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/organization_need.yml b/api/core/routes/organization_need.yml new file mode 100644 index 0000000..c64260c --- /dev/null +++ b/api/core/routes/organization_need.yml @@ -0,0 +1,113 @@ +get: + operationId: GetOrganizationNeed + summary: Read the current version of a need of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the server-side membership, never from the request. In the MVP only the owner of the organization reads needs; the other roles of PRD FR07 are planned. + + Returns the current version of the need: `version`, the requirements with the confirmation state and provenance of each field (`status`, and `source` with the origin, the quote, the version whose text the quote belongs to, and the extractor version), the readiness with `missing_fields`, and the category recommendations of the server. A field with status `unknown` has null value and source; an `extracted` value is a suggestion that waits for confirmation and never feeds search or recommendations. + + Versions: every committed change creates a new immutable `version`, and this operation always returns the latest one. `requirements_version` is the version in which the confirmed requirements were last changed; a change of the title, the vacancy link, the text, or suggestions only keeps it. Search runs, selection snapshots, and invitations refer to a need by its identifier and `requirements_version`, so they keep the requirements they used, and only a new `requirements_version` calls for a new selection snapshot. Reading and comparing earlier versions (PRD FR10) are planned as separate operations that return the same NeedRequirementSet for a given version; they add no field here. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, an unknown organization, an unknown need, and a need of another organization all answer 404 not_found, so identifiers cannot be probed; a member whose role does not allow reading the need answers 403 forbidden. An `org_id` or `need_id` that is not a UUID answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - need + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/NeedId + responses: + "200": + description: The current version of the need. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Need + examples: + manual_without_vacancy: + $ref: ../components/examples.yml#/NeedManualWithoutVacancy + from_text_with_unknown_skill: + $ref: ../components/examples.yml#/NeedExtractedWithUnknownSkill + confirmed: + $ref: ../components/examples.yml#/NeedConfirmedAfterUpdate + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem +patch: + operationId: UpdateOrganizationNeed + summary: Confirm, change, or delete requirements of a need. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The organization and the role come from the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization changes needs; the technical expert, who may refine the requirements of assigned needs under PRD FR07, is planned. + + Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; a field decision and each list are replaced entirely and never merged. This keeps every field one optional value in the generated server and client, without nested partial updates. + + Each requirement field is sent as a decision `{value, status}` and each list item as `{name or text, status}`, so confirmation is always explicit: + - Confirm a suggestion: send its stored value with `confirmed`. It keeps its origin and quote. + - Keep a suggestion open: send its stored value with `extracted`, or leave the field out. `extracted` with any other value, or for a field or item without a stored suggestion, answers 400 with the pointer of that `status`, for example `/grade/status` or `/required_skills/2/status`. A client that sends back an unchanged form therefore never confirms a suggestion by accident. + - Change: send another value with `confirmed`. It becomes a confirmed manual value, and its quote is dropped. + - Delete: send null for a nullable field, which makes it `unknown` (or unlinks `vacancy_id`), or leave the item out of a skill or task list, which deletes it. An empty skill or task list deletes every item; a list sent as null answers 400. A deleted requirement really changes the requirements that search uses, not only an explanation, and a deleted suggestion is not proposed again by a later extraction. + - Text: a different `source_text` extracts again. New suggestions replace only the `extracted` values and items of the fields not named in the body; confirmed values are never overwritten, and a suggested skill whose name is already in either skill list is skipped. Null removes the text and keeps every value. + + Versions: every committed change creates version `expected_version + 1` as an immutable snapshot and answers 200 with it. `requirements_version` becomes the new version only when a confirmed requirement was confirmed, changed, or removed. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the need again and reapplies its unsaved edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for the questionnaire. Concurrent changes therefore never overwrite each other silently. + + The operation needs no Idempotency-Key: a body that changes nothing when applied to the current version, such as a retry of a change that already succeeded, keeps the version and answers 200 with the current need even when `expected_version` is older. An incomplete need is a valid result; `readiness.missing_fields` tells what remains. + + Salary limit: the recommendations aggregate candidates' minimums against the upper bound, so setting or changing a confirmed salary range counts against a limit shared by the whole organization, every member and every need, together with ranges set on creation: at most three a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and changes nothing. After five settings within seven days the money component is `withheld` for seven days. Repeated range changes also feed the private organization risk signals. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the need (404 not_found), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/desired_skills/0/name` for a skill that is also in the required list, `/grade/status` or `/required_skills/2/status` for `extracted` with a value that is not the stored suggestion, or `/vacancy_id`), then the salary change limit (429). The schema rejects a missing or non-positive `expected_version`, unknown fields such as `rec_score`, `members`, `candidate_minimum`, or `version`, a field sent as a bare value instead of `{value, status}`, a list sent as null, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - need + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/NeedId + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NeedUpdate + examples: + confirm_suggestions: + $ref: ../components/examples.yml#/NeedUpdateConfirmSuggestions + responses: + "200": + description: >- + The need after the change, or the current need when the body changes + nothing. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Need + examples: + confirmed: + $ref: ../components/examples.yml#/NeedConfirmedAfterUpdate + "400": + $ref: ../components/responses.yml#/NeedValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "412": + $ref: ../components/responses.yml#/NeedVersionConflict + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_needs.yml b/api/core/routes/organization_needs.yml new file mode 100644 index 0000000..1d84d87 --- /dev/null +++ b/api/core/routes/organization_needs.yml @@ -0,0 +1,109 @@ +get: + operationId: ListOrganizationNeeds + summary: List the needs of an organization. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`. The organization and the role come from the membership that the server holds for the session account, never from the request. In the MVP only the owner of the organization works with needs; the other roles of the PRD FR07 matrix (recruiter, hiring manager and technical expert for assigned needs) are planned and change no field of this contract. The list holds only the needs that the role may read. + + Returns a page of need summaries, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. A summary has the current version, the target specialization and grade with their confirmation state, and the readiness; GetOrganizationNeed returns the requirements and the recommendations. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated; a member whose role does not allow reading needs answers 403 forbidden. A malformed `org_id`, `limit`, or `cursor` answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - need + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the needs of the organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NeedList + examples: + last_page: + $ref: ../components/examples.yml#/NeedListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem +post: + operationId: CreateOrganizationNeed + summary: Create a need of an organization from a form, a text, or both. + description: |- + Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The organization comes from the path and the server-side membership; the body has no organization, membership, or role field. In the MVP only the owner of the organization may create a need; the other roles of PRD FR07 are planned. + + A need does not require a vacancy: `vacancy_id` is optional and nullable. When it is given, it must name a vacancy of the same organization; until vacancies exist in the contract, any vacancy identifier answers 400 with the pointer `/vacancy_id`, the same for an unknown vacancy and one of another organization. + + Only `title` is required. A field is sent as a decision `{value, status}` and a list item as `{name or text, status}`; on creation the status must be `confirmed`, and the value becomes a confirmed manual value. When `source_text` is given, the server extracts suggestions for the absent fields with deterministic rules and a dictionary before it answers, so creation works while the ML service is disabled; every suggestion has the status `extracted`, the origin extracted_from_text, a quote where the extractor found one, and the extractor version, and it waits for a member to confirm it. A field that the text does not state stays `unknown` with null value and source; the server never guesses a grade, a format, or a salary. ML suggestions with quotes are planned as an asynchronous addition that creates a new version and never overwrites a confirmed value. + + The need is saved even when critical fields are missing: the response is 201 with version 1, and `readiness.missing_fields` names each critical field without a confirmed value with a specific question. `recommendations` is computed by the server from the confirmed requirements only; the request cannot set a recommendation, its score, or its components. Creating a need never contacts a candidate or sends an invitation. + + Salary limit: setting a salary range counts against a limit shared by the whole organization, every member and every need, on creation as on a change: at most three range settings a day (PRD FR13, enforcement planned). Over the limit the server answers 429 with Retry-After and creates nothing. After five settings within seven days the money component of the recommendations is `withheld` for seven days. The limit keeps an organization from probing hidden candidate minimums with new needs instead of edits; repeated range changes also feed the private organization risk signals. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second need. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate), membership (404 not_found) and role (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer: `/salary/value/salary_to` for a range whose lower bound is not below the upper one or whose width is outside 10-40%, `/required_skills/1/name` for a repeated skill, `/grade/status` or `/required_skills/0/status` for `extracted`, which a new need cannot have, or `/vacancy_id`), then the salary limit (429). The schema already rejects unknown fields such as `rec_score`, `members`, or `candidate_minimum`, a field sent as a bare value instead of `{value, status}`, a salary bound that is not a positive multiple of 1000, and an unknown currency, period, or tax basis. The general rate limit can answer 429 with Retry-After before any check. 429 is never stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - need + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NeedCreate + examples: + manual_without_vacancy: + $ref: ../components/examples.yml#/NeedCreateManual + from_text: + $ref: ../components/examples.yml#/NeedCreateFromText + responses: + "201": + description: >- + The need was created as version 1, or a retry with the same + Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Need + examples: + manual_without_vacancy: + $ref: ../components/examples.yml#/NeedManualWithoutVacancy + from_text_with_unknown_skill: + $ref: ../components/examples.yml#/NeedExtractedWithUnknownSkill + "400": + $ref: ../components/responses.yml#/NeedValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "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/organization_notification_read.yml b/api/core/routes/organization_notification_read.yml new file mode 100644 index 0000000..843a4d1 --- /dev/null +++ b/api/core/routes/organization_notification_read.yml @@ -0,0 +1,44 @@ +post: + operationId: MarkOrganizationNotificationRead + summary: Mark an item of the inbox of the current employer in one organization as read. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session and the organization from the path and the server-side membership. The request has no body. + + The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The item must belong to the caller in this organization. + + The general rate limit can answer 429 with Retry-After before any check. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization, an unknown organization, an item of another account, an item of another organization, and an unknown identifier all answer 404 not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/NotificationId + responses: + "200": + description: The read state of the item, newly set or repeated. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationReadReceipt + examples: + read: + $ref: ../components/examples.yml#/NotificationReadReceipt + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organization_notifications.yml b/api/core/routes/organization_notifications.yml new file mode 100644 index 0000000..5a8809b --- /dev/null +++ b/api/core/routes/organization_notifications.yml @@ -0,0 +1,40 @@ +get: + operationId: ListOrganizationNotifications + summary: List the inbox of the current employer in one organization. + description: |- + Requires the session cookie of an employer account with a confirmed email and an active membership in `org_id`, whatever its role. The recipient comes from the session and the organization from the path and the membership that the server holds, never from the request. Returns only the items addressed to the caller in this organization, newest delivery first with the identifier as the tie-breaker, with cursor pagination. An item of the same account in another organization, and an item of another member, are never listed. The response is `Cache-Control: no-store`. + + Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email never blocks an item, and the `content` of every item is resolved from the current source for this recipient on this read. An employer sees content only while the membership is active. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an account without an active membership in the organization and an unknown organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`, `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed. + security: + - sessionCookie: [] + tags: + - notification + parameters: + - $ref: ../components/parameters.yml#/OrganizationId + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the inbox of the current employer in the organization. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/NotificationList + examples: + page: + $ref: ../components/examples.yml#/NotificationListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/Forbidden + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/organizations.yml b/api/core/routes/organizations.yml new file mode 100644 index 0000000..40ad889 --- /dev/null +++ b/api/core/routes/organizations.yml @@ -0,0 +1,60 @@ +post: + operationId: CreateOrganization + summary: Create an organization; the caller becomes its owner. + description: |- + Requires the session cookie of an employer account with a confirmed email, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the session: the body has no owner, membership, role, verification, or version field, and unknown fields fail validation. + + The server creates the organization and the owner membership of the caller (role `owner`, state `active`) in one transaction, so an organization never exists without its owner. The organization starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be requested: the creator of a company with a corporate domain, a long description, or many representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of the server that do not exist yet. Only `name` is required; the rest of the card can be completed with UpdateOrganization. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second organization. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. Two requests with different keys are two organizations; the product may limit the number of organizations per account (open question), which would answer 409 `state_conflict` without a change of the schema. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a website that is not an https URL of a host name, `/name` for a name with surrounding whitespace). The general rate limit can answer 429 with Retry-After before any check; 429 is never stored. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - organization + parameters: + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/OrganizationCreate + examples: + name_only: + $ref: ../components/examples.yml#/OrganizationCreateNameOnly + complete_card: + $ref: ../components/examples.yml#/OrganizationCreateCompleteCard + responses: + "201": + description: >- + The organization was created with the caller as its owner, or a retry + with the same Idempotency-Key replayed its creation. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/Organization + examples: + name_only: + $ref: ../components/examples.yml#/OrganizationNameOnly + complete_card: + $ref: ../components/examples.yml#/OrganizationCompleteCard + "400": + $ref: ../components/responses.yml#/OrganizationValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "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/support_case.yml b/api/core/routes/support_case.yml new file mode 100644 index 0000000..cb5b4ad --- /dev/null +++ b/api/core/routes/support_case.yml @@ -0,0 +1,40 @@ +get: + operationId: GetMySupportCase + summary: Read a support case of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns the case with its number, type, object reference, status, response target, decision, and public history. The owner reads the case whatever happened to the object since then: a revoked access, a closed invitation, or a refused test never hides the case from its author. + + The case never contains the identity of a moderator, an expert, or a support agent, internal notes, evidence, assessment answers, anti-cheat or risk signals, or contact data of another person. `decision` is null until the case is `resolved`. + + The history lists every public event and is never truncated: the server keeps a case within 200 events by rejecting a staff event that would leave no room for the terminal one. + + The case must belong to the account of the session: a case of another account, including another member of the same organization, answers 404 not_found, the same as an unknown identifier, so identifiers cannot be probed. The contract answers 404, so the client shows the same "not found" state for a foreign and an unknown case. A malformed `case_id` answers 400 validation_failed with the path pointer. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: ../components/parameters.yml#/SupportCaseId + responses: + "200": + description: The case. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCase + examples: + manual_assessment_created: + $ref: ../components/examples.yml#/SupportCaseManualAssessmentCreated + grade_appeal_resolved: + $ref: ../components/examples.yml#/SupportCaseGradeAppealResolved + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "404": + $ref: ../components/responses.yml#/NotFound + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/core/routes/support_cases.yml b/api/core/routes/support_cases.yml new file mode 100644 index 0000000..a599be1 --- /dev/null +++ b/api/core/routes/support_cases.yml @@ -0,0 +1,122 @@ +get: + operationId: ListMySupportCases + summary: List the support cases of the current account. + description: |- + Requires the session cookie of a candidate or an employer account. Returns a page of the cases that this account created, newest first by creation time with the identifier as the tie-breaker, with cursor pagination. Each item is a summary with the number, type, status, object reference, category, response target, and decision outcome; it has no description and no history, which GetMySupportCase returns with the full case. Cases of other accounts are never listed, including cases of other members of the same organization. + + Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated. A malformed `limit` or `cursor` answers 400 validation_failed. Filters by status and type are planned and add optional parameters. + security: + - sessionCookie: [] + tags: + - support + parameters: + - $ref: ../components/parameters.yml#/PageLimit + - $ref: ../components/parameters.yml#/PageCursor + responses: + "200": + description: A page of the cases of the current account. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCaseList + examples: + last_page: + $ref: ../components/examples.yml#/SupportCaseListPage + "400": + $ref: ../components/responses.yml#/ValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + default: + $ref: ../components/responses.yml#/Problem +post: + operationId: CreateMySupportCase + summary: Open a support case, a complaint, an appeal, or a manual assessment request. + description: |- + Requires the session cookie, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The author is the account of the session; the body has no user, account, or organization field. A case is reachable from any screen, including a screen that denies access to an assessment: being refused an action never removes the path to a case about it. + + The client sends only what the user states: `type`, a non-blank `description`, and the fields of the type. It never sets the status, the decision, the outcome, the priority, the response target, the rubric, the assignee, or the moderator: every variant has `additionalProperties: false`, so such fields answer 400. Attachments are not part of the MVP; they are planned as an optional field and change no existing one. + + Types, accounts, and allowed references: + + | Type | Accounts | Object reference | Other fields | + | --- | --- | --- | --- | + | `support` | candidate, employer | optional; `assessment_attempt` of the caller, an `organization` that the caller can see, an `invitation` addressed to the caller, or another `support_case` of the caller | optional `assessment_target` | + | `complaint` | candidate | required; an `organization` that the caller can see or an `invitation` addressed to the caller | required `complaint_reason`; `offer_content` and `salary_terms_violation` require an invitation | + | `grade_appeal` | candidate | required; `assessment_attempt` of the caller in a terminal state, so it has a result, or a `support_case` of the caller of type `manual_assessment` that is `resolved` with the outcome `assessed`, for a category that an expert assigned without an attempt | none | + | `anticheat_appeal` | candidate | required; `assessment_attempt` of the caller with an anti-cheat review decision | none | + | `manual_assessment` | candidate | optional; a prior `assessment_attempt` of the caller in the same specialization | required `assessment_target` | + + An organization is visible to a candidate when it sent the candidate an invitation or when the organization contract shows the candidate its profile, and to an employer account when the account has an active membership in it. Invitations are in the contract but not implemented yet, so until they are, every `invitation` reference answers 404 not_found; anti-cheat review decisions are not either, so until review decisions are implemented, every anti-cheat appeal answers 409 state_conflict. The schema rejects an object type that the case type does not accept, for example an organization in a grade appeal. + + Ownership of the reference: the server checks the object against the session account on every create. An unknown object and an object of someone else, such as another candidate's attempt, another account's case, or an invitation addressed to another person, both answer 404 not_found, so a reference never reveals whether a foreign object exists. An own case that a grade appeal cannot dispute, because it is not a manual assessment, is not resolved yet, or was resolved with another outcome, answers 409 state_conflict. An identifier that is not a UUID fails validation with the pointer `/object/id`. The case stores only the type and the identifier of the object. + + Limits: an attempt and a resolved manual assessment each accept at most one grade appeal, and an attempt at most one anti-cheat appeal, in any status; a disagreement with the decision goes into a support case that references the appeal as `support_case`. A specialization accepts one open manual assessment, and an object accepts one open complaint; open means not `resolved` or `closed`. A second one answers 409 state_conflict. A grade appeal of an attempt that is still active also answers 409. Every create that passed authentication, validation, and the account scenario counts against a per-account limit from the product policy, including replays, 404, and 409, so the limit also bounds probing of references; over the limit the server answers 429 with Retry-After and creates nothing. + + Description check: the schema pattern `\S` uses the ECMAScript white space set in both generated validators (ogen converts it for Go), so a description of spaces such as U+00A0 or U+3000 already fails validation with the pointer `/description`. ECMAScript white space omits U+0085 (NEL), which Go `unicode.IsSpace` includes, so the server also applies a domain check: a description whose every character is `unicode.IsSpace` or U+FEFF answers 400 validation_failed with the pointer `/description`. This check comes with the implementation; generated Zod accepts a description of NEL, and the server stays authoritative. + + The new case gets a number and the status `submitted`. A grade appeal, an anti-cheat appeal, and a manual assessment are moved to `waiting_expert` by a `system` event in the same transaction, so the 201 already shows that status with both events; a support case and a complaint stay `submitted`. Each case gets a response target from the product policy version and the configured business calendar: 5 business days for a manual assessment and 10 for an appeal (PRD FR18 and C3), and a policy value for support and complaints. The target is an operational goal, not a deadline set by law. A manual assessment fixes the published rubric version of the category, or null when the category has none yet; the expert assesses with the same rubric as the automated assessment, and the request assigns no category by itself. Creating a case never grants, revokes, or changes a consent, a grade, or an attempt. + + Replies: the case itself is the channel. Support replies and decisions appear in the public `history` and `decision`. The server may also notify the verified email address of the account that the case changed, with the case number and a link, never with the description, the reply, or assessment details. No request field names another address or contact, so the operation cannot send mail to an address that the user typed. + + Idempotency: a retry with the same key and body within 24 hours replays the stored 201 with the same number and creates nothing, so a lost response never opens a second case. The replay is the snapshot stored at creation, following the repository convention; the client reads the current status and history with GetMySupportCase. 404 and 409 state_conflict are stored and replayed as well. A different body with the same key answers 422 idempotency_key_reused. 400, 403, and 429 are never stored. + + Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for an employer account with a type other than `support`), the per-account case limit (429), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with the pointer `/description` for a text of only Unicode spaces or `/object/type` for a complaint reason that requires an invitation), the object reference (404 not_found), then the state of the object and the limits (409 state_conflict). The general rate limit can answer 429 with Retry-After before any check. + security: + - sessionCookie: [] + sessionCsrf: [] + tags: + - support + parameters: + - $ref: ../components/parameters.yml#/IdempotencyKey + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCaseCreate + examples: + manual_assessment: + $ref: ../components/examples.yml#/SupportCaseCreateManualAssessment + own_grade_appeal: + $ref: ../components/examples.yml#/SupportCaseCreateGradeAppeal + appeal_of_manual_assessment: + $ref: ../components/examples.yml#/SupportCaseCreateCategoryAppeal + test_unavailable: + $ref: ../components/examples.yml#/SupportCaseCreateTestUnavailable + salary_terms_complaint: + $ref: ../components/examples.yml#/SupportCaseCreateComplaint + responses: + "201": + description: >- + The case was created, with the status `submitted` or, for an appeal + or a manual assessment, `waiting_expert`; or a retry with the same + Idempotency-Key replayed the stored creation response. + headers: + Cache-Control: + $ref: ../components/headers.yml#/CacheControlNoStore + content: + application/json: + schema: + $ref: ../components/schemas.yml#/SupportCase + examples: + manual_assessment: + $ref: ../components/examples.yml#/SupportCaseManualAssessmentCreated + "400": + $ref: ../components/responses.yml#/SupportCaseValidationFailed + "401": + $ref: ../components/responses.yml#/Unauthenticated + "403": + $ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden + "404": + $ref: ../components/responses.yml#/NotFound + "409": + $ref: ../components/responses.yml#/SupportCaseCreateConflict + "422": + $ref: ../components/responses.yml#/UnprocessableContent + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/components/parameters.yml b/api/labd/components/parameters.yml new file mode 100644 index 0000000..e1e714b --- /dev/null +++ b/api/labd/components/parameters.yml @@ -0,0 +1,11 @@ +LabId: + name: lab_id + in: path + required: true + description: >- + Random UUID chosen by the backend for one lab. It is the idempotency key + of CreateLab and must not encode a candidate, attempt, or task + identifier. + schema: + type: string + format: uuid diff --git a/api/labd/components/responses.yml b/api/labd/components/responses.yml new file mode 100644 index 0000000..cf67c53 --- /dev/null +++ b/api/labd/components/responses.yml @@ -0,0 +1,67 @@ +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + summary: The template is unknown + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: body + pointer: /template_id + code: invalid + message: The value does not match the contract. + state_conflict: + summary: The lab is not ready + value: + type: urn:lincodex:problem:state_conflict + title: State conflict + status: 409 + code: state_conflict + detail: The lab is not ready. + lab_unavailable: + summary: The checker could not reach a node + value: + type: urn:lincodex:problem:lab_unavailable + title: Lab unavailable + status: 503 + code: lab_unavailable + detail: The lab could not be evaluated. Nothing was checked. +LabPoolBusy: + description: >- + The lab does not fit the memory budget or the lab limit of the + provisioner, or the provisioner is draining; code lab_pool_busy. Nothing + was stored and no capacity was reserved. Retry with the same lab ID after + Retry-After. + headers: + Retry-After: + description: Number of seconds to wait before retrying the request. + required: true + schema: + type: integer + format: int32 + minimum: 0 + maximum: 3600 + example: 30 + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + lab_pool_busy: + summary: No capacity for another lab + value: + type: urn:lincodex:problem:lab_pool_busy + title: Lab pool busy + status: 503 + code: lab_pool_busy + detail: No capacity for another lab. Retry later with the same lab ID. diff --git a/api/labd/components/schemas.yml b/api/labd/components/schemas.yml new file mode 100644 index 0000000..38a7441 --- /dev/null +++ b/api/labd/components/schemas.yml @@ -0,0 +1,391 @@ +LabdHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok +LabdReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready +TemplateId: + type: string + minLength: 1 + maxLength: 48 + pattern: ^[a-z0-9][a-z0-9-]{0,47}$ + description: Identifier of a lab template known to the provisioner, such as `mikrotik-ospf-pair`. Templates are part of the provisioner build; the request never carries node images, commands, or configuration. +NodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a node inside its template, such as `r1` or `srv`. It is the same in every lab of the template and is not an LXD instance name or a host name. +NodeKind: + type: string + description: 'Guest system of a node. + + + - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. + + - ubuntu: a small Ubuntu VM; its console is a Linux login. + + + Adding a value is a contract change.' + enum: + - mikrotik + - ubuntu +LabCreateRequest: + type: object + description: A lab of one template variant. It has no field for a candidate, account, attempt, task, or company. + additionalProperties: false + required: + - template_id + - template_version + - seed + - ttl_seconds + properties: + template_id: + $ref: '#/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + description: Version of the template. The provisioner refuses a version it does not hold, so a lab always matches the variant the backend served. + seed: + type: string + minLength: 64 + maxLength: 64 + pattern: ^[0-9a-f]{64}$ + description: 'Variant seed: 32 random bytes in lowercase hex chosen by the backend for the item instance. The template renders the variant configuration of every node and the checker criteria from it. It is never returned by the provisioner.' + ttl_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of the lab from its creation. The provisioner refuses a value above its configured maximum. +LabState: + type: string + description: 'State of a lab. + + + - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. + + - ready: every node answers on its management port; console tokens and checks are allowed. + + - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed. + + - deleted: every instance and bridge of the lab is gone and its capacity is free. + + - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID. + + + Adding a value is a contract change.' + enum: + - provisioning + - ready + - deleting + - deleted + - failed +LabFailureReason: + type: string + description: 'Why a lab failed. None of the reasons depends on the person who uses the lab. + + + - provisioning_failed: LXD refused or failed an operation of the provisioning. + + - provisioning_timed_out: a node did not answer on its management port within the provisioning timeout. + + - interrupted: the provisioner process stopped while the lab was provisioning.' + enum: + - provisioning_failed + - provisioning_timed_out + - interrupted +LabNode: + type: object + description: A node of a lab by its template name and kind. It never carries an address, a MAC address, an instance name, or a credential. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/NodeName' + kind: + $ref: '#/NodeKind' +LabStatus: + type: object + description: State of a lab after one call. It never contains the seed, a node address, a key, a password, or an LXD object name. + additionalProperties: false + required: + - lab_id + - state + - template_id + - template_version + - created_at + - expires_at + - nodes + properties: + lab_id: + type: string + format: uuid + state: + $ref: '#/LabState' + template_id: + $ref: '#/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + created_at: + type: string + format: date-time + ready_at: + type: string + format: date-time + description: Time the lab became `ready`; absent before. + expires_at: + type: string + format: date-time + description: Time the provisioner deletes the lab. It never moves, also not across restarts of the provisioner. + deleted_at: + type: string + format: date-time + description: Time the last resource of the lab was removed; absent before. + failure_reason: + $ref: '#/LabFailureReason' + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the template in template order. + items: + $ref: '#/LabNode' +ConsoleTokenRequest: + type: object + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/NodeName' +ConsoleToken: + type: object + description: 'Single-use console token for one node. The token is a secret of the console gateway: it is never logged, stored by the backend, or passed to a browser.' + additionalProperties: false + required: + - token + - node + - expires_at + - attach_path + properties: + token: + type: string + minLength: 43 + maxLength: 43 + pattern: ^[A-Za-z0-9_-]{43}$ + description: 32 random bytes in unpadded base64url. + node: + $ref: '#/NodeName' + expires_at: + type: string + format: date-time + attach_path: + type: string + maxLength: 128 + pattern: ^/v1/labs/[0-9a-f-]{36}/console$ + description: Path of the WebSocket attach on the provisioner origin. +CriterionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque identifier of a checker criterion of the template. +CriterionResult: + type: object + additionalProperties: false + required: + - id + - passed + properties: + id: + $ref: '#/CriterionId' + passed: + type: boolean +LabCheckResult: + type: object + description: 'Result of one check: whether each criterion of the variant holds on the nodes. It carries no node output, address, or configuration text.' + additionalProperties: false + required: + - lab_id + - checked_at + - score + - max_score + - criteria + properties: + lab_id: + type: string + format: uuid + checked_at: + type: string + format: date-time + score: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of passed criteria. + max_score: + type: integer + format: int32 + minimum: 1 + maximum: 50 + description: Number of criteria. + criteria: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/CriterionResult' +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the lab provisioner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable error code of the lab provisioner API. 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 semantic rule, such as an unknown template or node; `errors` points at the fields. + + - unauthenticated (401): the bearer token is missing or wrong. + + - not_found (404): the route or the lab does not exist. + + - method_not_allowed (405): the route does not support the method. + + - state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready. + + - 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 lab ID was already used with a different payload. + + - internal (500): unexpected server error. + + - not_implemented (501): the route is described but not implemented yet, such as the console attach. + + - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After. + + - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check. + + + The Problem shape is the api/core shape; only this enum is specific to the lab provisioner.' + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - state_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - not_implemented + - lab_pool_busy + - lab_unavailable +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/ttl_seconds`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/lab_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/labd/components/schemas/health_schemas.yml b/api/labd/components/schemas/health_schemas.yml new file mode 100644 index 0000000..353249e --- /dev/null +++ b/api/labd/components/schemas/health_schemas.yml @@ -0,0 +1,22 @@ +schemas: + LabdHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + LabdReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready diff --git a/api/labd/components/schemas/lab_schemas.yml b/api/labd/components/schemas/lab_schemas.yml new file mode 100644 index 0000000..d79ce65 --- /dev/null +++ b/api/labd/components/schemas/lab_schemas.yml @@ -0,0 +1,259 @@ +schemas: + TemplateId: + type: string + minLength: 1 + maxLength: 48 + pattern: "^[a-z0-9][a-z0-9-]{0,47}$" + description: >- + Identifier of a lab template known to the provisioner, such as + `mikrotik-ospf-pair`. Templates are part of the provisioner build; the + request never carries node images, commands, or configuration. + NodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: "^[a-z][a-z0-9-]{0,14}$" + description: >- + Name of a node inside its template, such as `r1` or `srv`. It is the + same in every lab of the template and is not an LXD instance name or a + host name. + NodeKind: + type: string + description: |- + Guest system of a node. + + - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. + - ubuntu: a small Ubuntu VM; its console is a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + LabCreateRequest: + type: object + description: >- + A lab of one template variant. It has no field for a candidate, + account, attempt, task, or company. + additionalProperties: false + required: + - template_id + - template_version + - seed + - ttl_seconds + properties: + template_id: + $ref: "#/schemas/TemplateId" + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + description: >- + Version of the template. The provisioner refuses a version it does + not hold, so a lab always matches the variant the backend served. + seed: + type: string + minLength: 64 + maxLength: 64 + pattern: "^[0-9a-f]{64}$" + description: >- + Variant seed: 32 random bytes in lowercase hex chosen by the + backend for the item instance. The template renders the variant + configuration of every node and the checker criteria from it. It + is never returned by the provisioner. + ttl_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: >- + Lifetime of the lab from its creation. The provisioner refuses a + value above its configured maximum. + LabState: + type: string + description: |- + State of a lab. + + - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. + - ready: every node answers on its management port; console tokens and checks are allowed. + - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed. + - deleted: every instance and bridge of the lab is gone and its capacity is free. + - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - deleting + - deleted + - failed + LabFailureReason: + type: string + description: |- + Why a lab failed. None of the reasons depends on the person who uses the lab. + + - provisioning_failed: LXD refused or failed an operation of the provisioning. + - provisioning_timed_out: a node did not answer on its management port within the provisioning timeout. + - interrupted: the provisioner process stopped while the lab was provisioning. + enum: + - provisioning_failed + - provisioning_timed_out + - interrupted + LabNode: + type: object + description: >- + A node of a lab by its template name and kind. It never carries an + address, a MAC address, an instance name, or a credential. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: "#/schemas/NodeName" + kind: + $ref: "#/schemas/NodeKind" + LabStatus: + type: object + description: >- + State of a lab after one call. It never contains the seed, a node + address, a key, a password, or an LXD object name. + additionalProperties: false + required: + - lab_id + - state + - template_id + - template_version + - created_at + - expires_at + - nodes + properties: + lab_id: + type: string + format: uuid + state: + $ref: "#/schemas/LabState" + template_id: + $ref: "#/schemas/TemplateId" + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + created_at: + type: string + format: date-time + ready_at: + type: string + format: date-time + description: Time the lab became `ready`; absent before. + expires_at: + type: string + format: date-time + description: >- + Time the provisioner deletes the lab. It never moves, also not + across restarts of the provisioner. + deleted_at: + type: string + format: date-time + description: Time the last resource of the lab was removed; absent before. + failure_reason: + $ref: "#/schemas/LabFailureReason" + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the template in template order. + items: + $ref: "#/schemas/LabNode" + ConsoleTokenRequest: + type: object + additionalProperties: false + required: + - node + properties: + node: + $ref: "#/schemas/NodeName" + ConsoleToken: + type: object + description: >- + Single-use console token for one node. The token is a secret of the + console gateway: it is never logged, stored by the backend, or passed + to a browser. + additionalProperties: false + required: + - token + - node + - expires_at + - attach_path + properties: + token: + type: string + minLength: 43 + maxLength: 43 + pattern: "^[A-Za-z0-9_-]{43}$" + description: 32 random bytes in unpadded base64url. + node: + $ref: "#/schemas/NodeName" + expires_at: + type: string + format: date-time + attach_path: + type: string + maxLength: 128 + pattern: "^/v1/labs/[0-9a-f-]{36}/console$" + description: Path of the WebSocket attach on the provisioner origin. + CriterionId: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9][a-z0-9_-]{0,31}$" + description: Opaque identifier of a checker criterion of the template. + CriterionResult: + type: object + additionalProperties: false + required: + - id + - passed + properties: + id: + $ref: "#/schemas/CriterionId" + passed: + type: boolean + LabCheckResult: + type: object + description: >- + Result of one check: whether each criterion of the variant holds on the + nodes. It carries no node output, address, or configuration text. + additionalProperties: false + required: + - lab_id + - checked_at + - score + - max_score + - criteria + properties: + lab_id: + type: string + format: uuid + checked_at: + type: string + format: date-time + score: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of passed criteria. + max_score: + type: integer + format: int32 + minimum: 1 + maximum: 50 + description: Number of criteria. + criteria: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: "#/schemas/CriterionResult" diff --git a/api/labd/components/schemas/problem_schemas.yml b/api/labd/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..dfa0cda --- /dev/null +++ b/api/labd/components/schemas/problem_schemas.yml @@ -0,0 +1,144 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. This is the lab provisioner copy of + the public api/core Problem schema; keep both copies identical except + for descriptions and the ProblemCode enum. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier of the call when the caller propagated one; it is + not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable error code of the lab provisioner API. 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 semantic rule, such as an unknown template or node; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the lab does not exist. + - method_not_allowed (405): the route does not support the method. + - state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready. + - 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 lab ID was already used with a different payload. + - internal (500): unexpected server error. + - not_implemented (501): the route is described but not implemented yet, such as the console attach. + - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After. + - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check. + + The Problem shape is the api/core shape; only this enum is specific to the lab provisioner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - state_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - not_implemented + - lab_pool_busy + - lab_unavailable + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/ttl_seconds`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/lab_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/labd/openapi.bundle.yml b/api/labd/openapi.bundle.yml new file mode 100644 index 0000000..460916b --- /dev/null +++ b/api/labd/openapi.bundle.yml @@ -0,0 +1,721 @@ +openapi: 3.2.0 +info: + title: Lincodex Lab Provisioner API + version: 0.1.0 + description: |- + Internal API of the lab provisioner `labd`. Only the Go backend calls it; + it is never exposed to browsers or to the public network. `labd` is the + only component that talks to the LXD API on the app host: the backend + never receives the LXD socket, an LXD certificate, or a node address. + + Transport and authentication: `labd` listens on a private address of the + app host that only the backend network reaches and serves HTTPS (TLS + 1.3). Every operation except the health routes requires `Authorization: + Bearer `; the token is a shared random secret of at least 32 + characters that comes from the deployment secret store, never from this + repository. A missing or wrong token answers 401 `unauthenticated`. Plain + HTTP exists only behind an explicit development switch. + + Data minimization: a lab request carries only a template reference, a + variant seed, and a lifetime. It has no candidate, account, attempt, + task, or company identifier. The lab ID is a random UUID chosen by the + backend for idempotency. Responses never carry node addresses, MAC + addresses, bridge or instance names, keys, or passwords: the backend + reaches a node only through a console token and learns a lab's state + only through these operations. + + Lifecycle: CreateLab reserves capacity and answers immediately with the + lab in `provisioning`; `labd` clones the nodes of the template from + prepared snapshots, connects them with per-lab L2-only bridges, boots + them, and waits until their management ports answer. The caller polls + GetLab until `ready`. Every lab has a fixed `expires_at`; `labd` deletes + it at that time even after a restart of its own process, and DeleteLab + deletes it earlier. A deleted lab stays readable as `deleted` for a + bounded time, then answers 404. + + Capacity: the number of concurrent labs follows the host memory budget of + `labd`. A request that does not fit answers 503 `lab_pool_busy` with + Retry-After and stores nothing; it is a capacity signal, not an + infrastructure failure. `labd` does not queue labs. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + get: + operationId: GetLabdHealthz + summary: Check whether the lab provisioner process is responding. + security: [] + tags: + - health + responses: + '200': + description: The process is responding. + content: + application/json: + schema: + $ref: '#/components/schemas/LabdHealthResponse' + default: + $ref: '#/components/responses/Problem' + /readyz: + get: + operationId: GetLabdReadyz + summary: Check whether the provisioner can create and delete labs. + description: Ready means that the lab records were loaded, the startup reconciliation with LXD finished, the LXD API answered the latest probe, and the process is not draining. A provisioner without free capacity is still ready; capacity is reported by CreateLab. + security: [] + tags: + - health + responses: + '200': + description: The provisioner is ready. + content: + application/json: + schema: + $ref: '#/components/schemas/LabdReadinessResponse' + '503': + description: The provisioner is not ready or is draining. + content: + application/json: + schema: + $ref: '#/components/schemas/LabdReadinessResponse' + default: + $ref: '#/components/responses/Problem' + /v1/labs/{lab_id}: + parameters: + - $ref: '#/components/parameters/LabId' + put: + operationId: CreateLab + summary: Create a lab from a template and a variant seed. + description: |- + Idempotent by `lab_id`: + + - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with `state: provisioning`; the nodes are cloned and booted in the background; + - the same ID with the same payload answers 200 with the current state of that lab, including `deleted` or `failed`, and never creates a second one; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller retries with the same ID. + + Payloads are compared by a SHA-256 fingerprint of the decoded request. + An unknown template or template version, or a lifetime above the + configured maximum, answers 400 `validation_failed` with a pointer such + as `/template_id` or `/ttl_seconds`. + + The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also + when it is still provisioning. A lab that fails to provision or does not + answer within the provisioning timeout becomes `failed` and its + resources are deleted; its capacity returns when they are gone. + + A record of a deleted or failed lab is kept for a bounded retention time; + after it, the ID is unknown again and a CreateLab with it starts a new + lab. + tags: + - labs + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LabCreateRequest' + examples: + two_routers: + summary: A lab of a networking template for one attempt item + value: + template_id: mikrotik-ospf-pair + template_version: 1 + seed: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + ttl_seconds: 3600 + responses: + '200': + description: A lab with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + '202': + description: The lab was accepted and is provisioning. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + examples: + provisioning: + summary: A lab that is being cloned and booted + value: + lab_id: 2f1c7a52-0d3e-4b8e-9b61-3c7b1f2e9a40 + state: provisioning + template_id: mikrotik-ospf-pair + template_version: 1 + created_at: '2026-10-11T09:00:00Z' + expires_at: '2026-10-11T10:00:00Z' + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + '503': + $ref: '#/components/responses/LabPoolBusy' + default: + $ref: '#/components/responses/Problem' + get: + operationId: GetLab + summary: Read the state of a lab. + description: Answers 404 `not_found` for an ID the provisioner does not hold, including a lab whose `deleted` record outlived its retention time. The response never contains an address, a key, or an LXD object name. + tags: + - labs + responses: + '200': + description: The current state of the lab. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + default: + $ref: '#/components/responses/Problem' + delete: + operationId: DeleteLab + summary: Delete a lab before its timer. + description: 'Marks the lab for deletion and answers 202 with `state: deleting`; the provisioner removes its instances and bridges in the background and retries until LXD confirms that they are gone, also across its own restarts. Deleting a lab that is already `deleting` or `deleted` answers 200 with its state and changes nothing. An unknown ID answers 404 `not_found`.' + tags: + - labs + responses: + '200': + description: The lab was already being deleted or is deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + '202': + description: The lab is being deleted. + content: + application/json: + schema: + $ref: '#/components/schemas/LabStatus' + default: + $ref: '#/components/responses/Problem' + /v1/labs/{lab_id}/console-tokens: + parameters: + - $ref: '#/components/parameters/LabId' + post: + operationId: CreateLabConsoleToken + summary: Issue a short-lived console token for one node of a ready lab. + description: |- + The token lets the console gateway of the backend attach to the serial + console of one node. It is random, single-use, bound to the lab and the + node, and valid for at most 120 seconds; `labd` keeps only its SHA-256 + digest in memory, so a restart invalidates every unused token. The token + is never a node password or an SSH key, and the response carries no node + address. + + Attaching: the gateway opens a WebSocket to `attach_path` on the same + `labd` origin with the service bearer token and sends the console token + in the `X-Lab-Console-Token` header. The WebSocket attach is described + here as the planned interface; until it is implemented, `labd` answers + the attach path with 501 and issuing a token changes nothing else. + + A lab that is not `ready` answers 409 `state_conflict`; an unknown node + answers 400 `validation_failed` with the pointer `/node`. + tags: + - consoles + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ConsoleTokenRequest' + responses: + '201': + description: The token was issued. + headers: + Cache-Control: + description: The token must not be stored by any cache. + required: true + schema: + type: string + enum: + - no-store + content: + application/json: + schema: + $ref: '#/components/schemas/ConsoleToken' + default: + $ref: '#/components/responses/Problem' + /v1/labs/{lab_id}/check: + parameters: + - $ref: '#/components/parameters/LabId' + post: + operationId: CheckLab + summary: Run the checker of the template against the nodes of a ready lab. + description: |- + The checker of the template connects from the host side of the lab + management bridge to the nodes (SSH or the RouterOS API) and evaluates + the criteria of the variant that the seed selected. It only reads the + node state and never changes it, so a repeated call is harmless; the + result is not stored by `labd`. The call is synchronous and bounded by + the check timeout of the provisioner. + + The result is checker state for the backend only: the backend scores the + lab answer with it and never forwards it to the candidate. + + A lab that is not `ready` answers 409 `state_conflict`. When the + checker cannot reach a node or the template has no working checker, the + provisioner answers 503 `lab_unavailable`: nothing was evaluated, and the + outcome is never a failed check. + tags: + - checks + responses: + '200': + description: The checker evaluated every criterion. + content: + application/json: + schema: + $ref: '#/components/schemas/LabCheckResult' + default: + $ref: '#/components/responses/Problem' +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: 'Shared random service token sent as `Authorization: Bearer ` over TLS. `labd` compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.' + responses: + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + summary: The template is unknown + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: body + pointer: /template_id + code: invalid + message: The value does not match the contract. + state_conflict: + summary: The lab is not ready + value: + type: urn:lincodex:problem:state_conflict + title: State conflict + status: 409 + code: state_conflict + detail: The lab is not ready. + lab_unavailable: + summary: The checker could not reach a node + value: + type: urn:lincodex:problem:lab_unavailable + title: Lab unavailable + status: 503 + code: lab_unavailable + detail: The lab could not be evaluated. Nothing was checked. + LabPoolBusy: + description: The lab does not fit the memory budget or the lab limit of the provisioner, or the provisioner is draining; code lab_pool_busy. Nothing was stored and no capacity was reserved. Retry with the same lab ID after Retry-After. + headers: + Retry-After: + description: Number of seconds to wait before retrying the request. + required: true + schema: + type: integer + format: int32 + minimum: 0 + maximum: 3600 + example: 30 + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + lab_pool_busy: + summary: No capacity for another lab + value: + type: urn:lincodex:problem:lab_pool_busy + title: Lab pool busy + status: 503 + code: lab_pool_busy + detail: No capacity for another lab. Retry later with the same lab ID. + schemas: + ProblemCode: + type: string + description: |- + Stable error code of the lab provisioner API. 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 semantic rule, such as an unknown template or node; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the lab does not exist. + - method_not_allowed (405): the route does not support the method. + - state_conflict (409): the lab is not in a state that allows the operation, for example a console token or a check for a lab that is not ready. + - 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 lab ID was already used with a different payload. + - internal (500): unexpected server error. + - not_implemented (501): the route is described but not implemented yet, such as the console attach. + - lab_pool_busy (503): the lab does not fit the capacity or the provisioner is draining; see Retry-After. + - lab_unavailable (503): LXD or a node could not be reached, so nothing was done or evaluated. It is an infrastructure failure, never a failed check. + + The Problem shape is the api/core shape; only this enum is specific to the lab provisioner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - state_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - not_implemented + - lab_pool_busy + - lab_unavailable + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/ttl_seconds`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/lab_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the lab provisioner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' + LabdHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + LabdReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready + LabState: + type: string + description: |- + State of a lab. + + - provisioning: capacity is reserved and the nodes are being cloned, connected, and booted. + - ready: every node answers on its management port; console tokens and checks are allowed. + - deleting: the timer ended, DeleteLab was called, or provisioning failed; the instances and bridges are being removed. + - deleted: every instance and bridge of the lab is gone and its capacity is free. + - failed: provisioning failed or timed out, or the provisioner restarted while provisioning; `failure_reason` says which. Its resources are removed as for `deleting` and the capacity returns once they are gone; create a new lab with a new ID. + + Adding a value is a contract change. + enum: + - provisioning + - ready + - deleting + - deleted + - failed + TemplateId: + type: string + minLength: 1 + maxLength: 48 + pattern: ^[a-z0-9][a-z0-9-]{0,47}$ + description: Identifier of a lab template known to the provisioner, such as `mikrotik-ospf-pair`. Templates are part of the provisioner build; the request never carries node images, commands, or configuration. + LabFailureReason: + type: string + description: |- + Why a lab failed. None of the reasons depends on the person who uses the lab. + + - provisioning_failed: LXD refused or failed an operation of the provisioning. + - provisioning_timed_out: a node did not answer on its management port within the provisioning timeout. + - interrupted: the provisioner process stopped while the lab was provisioning. + enum: + - provisioning_failed + - provisioning_timed_out + - interrupted + NodeName: + type: string + minLength: 1 + maxLength: 15 + pattern: ^[a-z][a-z0-9-]{0,14}$ + description: Name of a node inside its template, such as `r1` or `srv`. It is the same in every lab of the template and is not an LXD instance name or a host name. + NodeKind: + type: string + description: |- + Guest system of a node. + + - mikrotik: a MikroTik Cloud Hosted Router VM; its console is RouterOS. + - ubuntu: a small Ubuntu VM; its console is a Linux login. + + Adding a value is a contract change. + enum: + - mikrotik + - ubuntu + LabNode: + type: object + description: A node of a lab by its template name and kind. It never carries an address, a MAC address, an instance name, or a credential. + additionalProperties: false + required: + - name + - kind + properties: + name: + $ref: '#/components/schemas/NodeName' + kind: + $ref: '#/components/schemas/NodeKind' + LabStatus: + type: object + description: State of a lab after one call. It never contains the seed, a node address, a key, a password, or an LXD object name. + additionalProperties: false + required: + - lab_id + - state + - template_id + - template_version + - created_at + - expires_at + - nodes + properties: + lab_id: + type: string + format: uuid + state: + $ref: '#/components/schemas/LabState' + template_id: + $ref: '#/components/schemas/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + created_at: + type: string + format: date-time + ready_at: + type: string + format: date-time + description: Time the lab became `ready`; absent before. + expires_at: + type: string + format: date-time + description: Time the provisioner deletes the lab. It never moves, also not across restarts of the provisioner. + deleted_at: + type: string + format: date-time + description: Time the last resource of the lab was removed; absent before. + failure_reason: + $ref: '#/components/schemas/LabFailureReason' + nodes: + type: array + minItems: 1 + maxItems: 8 + description: Nodes of the template in template order. + items: + $ref: '#/components/schemas/LabNode' + LabCreateRequest: + type: object + description: A lab of one template variant. It has no field for a candidate, account, attempt, task, or company. + additionalProperties: false + required: + - template_id + - template_version + - seed + - ttl_seconds + properties: + template_id: + $ref: '#/components/schemas/TemplateId' + template_version: + type: integer + format: int32 + minimum: 1 + maximum: 10000 + description: Version of the template. The provisioner refuses a version it does not hold, so a lab always matches the variant the backend served. + seed: + type: string + minLength: 64 + maxLength: 64 + pattern: ^[0-9a-f]{64}$ + description: 'Variant seed: 32 random bytes in lowercase hex chosen by the backend for the item instance. The template renders the variant configuration of every node and the checker criteria from it. It is never returned by the provisioner.' + ttl_seconds: + type: integer + format: int32 + minimum: 300 + maximum: 14400 + description: Lifetime of the lab from its creation. The provisioner refuses a value above its configured maximum. + ConsoleTokenRequest: + type: object + additionalProperties: false + required: + - node + properties: + node: + $ref: '#/components/schemas/NodeName' + ConsoleToken: + type: object + description: 'Single-use console token for one node. The token is a secret of the console gateway: it is never logged, stored by the backend, or passed to a browser.' + additionalProperties: false + required: + - token + - node + - expires_at + - attach_path + properties: + token: + type: string + minLength: 43 + maxLength: 43 + pattern: ^[A-Za-z0-9_-]{43}$ + description: 32 random bytes in unpadded base64url. + node: + $ref: '#/components/schemas/NodeName' + expires_at: + type: string + format: date-time + attach_path: + type: string + maxLength: 128 + pattern: ^/v1/labs/[0-9a-f-]{36}/console$ + description: Path of the WebSocket attach on the provisioner origin. + CriterionId: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque identifier of a checker criterion of the template. + CriterionResult: + type: object + additionalProperties: false + required: + - id + - passed + properties: + id: + $ref: '#/components/schemas/CriterionId' + passed: + type: boolean + LabCheckResult: + type: object + description: 'Result of one check: whether each criterion of the variant holds on the nodes. It carries no node output, address, or configuration text.' + additionalProperties: false + required: + - lab_id + - checked_at + - score + - max_score + - criteria + properties: + lab_id: + type: string + format: uuid + checked_at: + type: string + format: date-time + score: + type: integer + format: int32 + minimum: 0 + maximum: 50 + description: Number of passed criteria. + max_score: + type: integer + format: int32 + minimum: 1 + maximum: 50 + description: Number of criteria. + criteria: + type: array + minItems: 1 + maxItems: 50 + items: + $ref: '#/components/schemas/CriterionResult' + parameters: + LabId: + name: lab_id + in: path + required: true + description: Random UUID chosen by the backend for one lab. It is the idempotency key of CreateLab and must not encode a candidate, attempt, or task identifier. + schema: + type: string + format: uuid diff --git a/api/labd/openapi.yml b/api/labd/openapi.yml new file mode 100644 index 0000000..783ef51 --- /dev/null +++ b/api/labd/openapi.yml @@ -0,0 +1,67 @@ +openapi: 3.2.0 +info: + title: Lincodex Lab Provisioner API + version: 0.1.0 + description: |- + Internal API of the lab provisioner `labd`. Only the Go backend calls it; + it is never exposed to browsers or to the public network. `labd` is the + only component that talks to the LXD API on the app host: the backend + never receives the LXD socket, an LXD certificate, or a node address. + + Transport and authentication: `labd` listens on a private address of the + app host that only the backend network reaches and serves HTTPS (TLS + 1.3). Every operation except the health routes requires `Authorization: + Bearer `; the token is a shared random secret of at least 32 + characters that comes from the deployment secret store, never from this + repository. A missing or wrong token answers 401 `unauthenticated`. Plain + HTTP exists only behind an explicit development switch. + + Data minimization: a lab request carries only a template reference, a + variant seed, and a lifetime. It has no candidate, account, attempt, + task, or company identifier. The lab ID is a random UUID chosen by the + backend for idempotency. Responses never carry node addresses, MAC + addresses, bridge or instance names, keys, or passwords: the backend + reaches a node only through a console token and learns a lab's state + only through these operations. + + Lifecycle: CreateLab reserves capacity and answers immediately with the + lab in `provisioning`; `labd` clones the nodes of the template from + prepared snapshots, connects them with per-lab L2-only bridges, boots + them, and waits until their management ports answer. The caller polls + GetLab until `ready`. Every lab has a fixed `expires_at`; `labd` deletes + it at that time even after a restart of its own process, and DeleteLab + deletes it earlier. A deleted lab stays readable as `deleted` for a + bounded time, then answers 404. + + Capacity: the number of concurrent labs follows the host memory budget of + `labd`. A request that does not fit answers 503 `lab_pool_busy` with + Retry-After and stores nothing; it is a capacity signal, not an + infrastructure failure. `labd` does not queue labs. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + $ref: ./routes/healthz.yml + /readyz: + $ref: ./routes/readyz.yml + /v1/labs/{lab_id}: + $ref: ./routes/labs.yml + /v1/labs/{lab_id}/console-tokens: + $ref: ./routes/lab_console_tokens.yml + /v1/labs/{lab_id}/check: + $ref: ./routes/lab_check.yml +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: >- + Shared random service token sent as `Authorization: Bearer ` + over TLS. `labd` compares it in constant time and never logs it. + Rotation replaces the secret on both sides; there are no per-user + tokens. + responses: + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/labd/routes/healthz.yml b/api/labd/routes/healthz.yml new file mode 100644 index 0000000..1dbd779 --- /dev/null +++ b/api/labd/routes/healthz.yml @@ -0,0 +1,15 @@ +get: + operationId: GetLabdHealthz + summary: Check whether the lab provisioner process is responding. + security: [] + tags: + - health + responses: + "200": + description: The process is responding. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabdHealthResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/lab_check.yml b/api/labd/routes/lab_check.yml new file mode 100644 index 0000000..a38707d --- /dev/null +++ b/api/labd/routes/lab_check.yml @@ -0,0 +1,31 @@ +parameters: + - $ref: ../components/parameters.yml#/LabId +post: + operationId: CheckLab + summary: Run the checker of the template against the nodes of a ready lab. + description: |- + The checker of the template connects from the host side of the lab + management bridge to the nodes (SSH or the RouterOS API) and evaluates + the criteria of the variant that the seed selected. It only reads the + node state and never changes it, so a repeated call is harmless; the + result is not stored by `labd`. The call is synchronous and bounded by + the check timeout of the provisioner. + + The result is checker state for the backend only: the backend scores the + lab answer with it and never forwards it to the candidate. + + A lab that is not `ready` answers 409 `state_conflict`. When the + checker cannot reach a node or the template has no working checker, the + provisioner answers 503 `lab_unavailable`: nothing was evaluated, and the + outcome is never a failed check. + tags: + - checks + responses: + "200": + description: The checker evaluated every criterion. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabCheckResult + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/lab_console_tokens.yml b/api/labd/routes/lab_console_tokens.yml new file mode 100644 index 0000000..5141334 --- /dev/null +++ b/api/labd/routes/lab_console_tokens.yml @@ -0,0 +1,46 @@ +parameters: + - $ref: ../components/parameters.yml#/LabId +post: + operationId: CreateLabConsoleToken + summary: Issue a short-lived console token for one node of a ready lab. + description: |- + The token lets the console gateway of the backend attach to the serial + console of one node. It is random, single-use, bound to the lab and the + node, and valid for at most 120 seconds; `labd` keeps only its SHA-256 + digest in memory, so a restart invalidates every unused token. The token + is never a node password or an SSH key, and the response carries no node + address. + + Attaching: the gateway opens a WebSocket to `attach_path` on the same + `labd` origin with the service bearer token and sends the console token + in the `X-Lab-Console-Token` header. The WebSocket attach is described + here as the planned interface; until it is implemented, `labd` answers + the attach path with 501 and issuing a token changes nothing else. + + A lab that is not `ready` answers 409 `state_conflict`; an unknown node + answers 400 `validation_failed` with the pointer `/node`. + tags: + - consoles + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsoleTokenRequest + responses: + "201": + description: The token was issued. + headers: + Cache-Control: + description: The token must not be stored by any cache. + required: true + schema: + type: string + enum: + - no-store + content: + application/json: + schema: + $ref: ../components/schemas.yml#/ConsoleToken + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/labs.yml b/api/labd/routes/labs.yml new file mode 100644 index 0000000..d7f3eef --- /dev/null +++ b/api/labd/routes/labs.yml @@ -0,0 +1,119 @@ +parameters: + - $ref: ../components/parameters.yml#/LabId +put: + operationId: CreateLab + summary: Create a lab from a template and a variant seed. + description: |- + Idempotent by `lab_id`: + + - a new ID that fits the capacity reserves it, stores the lab, and answers 202 with `state: provisioning`; the nodes are cloned and booted in the background; + - the same ID with the same payload answers 200 with the current state of that lab, including `deleted` or `failed`, and never creates a second one; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID that does not fit the memory budget or the lab limit, or arrives while the provisioner is draining, answers 503 `lab_pool_busy` with Retry-After; nothing is stored, so the caller retries with the same ID. + + Payloads are compared by a SHA-256 fingerprint of the decoded request. + An unknown template or template version, or a lifetime above the + configured maximum, answers 400 `validation_failed` with a pointer such + as `/template_id` or `/ttl_seconds`. + + The lab is deleted at `expires_at` = creation time + `ttl_seconds`, also + when it is still provisioning. A lab that fails to provision or does not + answer within the provisioning timeout becomes `failed` and its + resources are deleted; its capacity returns when they are gone. + + A record of a deleted or failed lab is kept for a bounded retention time; + after it, the ID is unknown again and a CreateLab with it starts a new + lab. + tags: + - labs + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabCreateRequest + examples: + two_routers: + summary: A lab of a networking template for one attempt item + value: + template_id: mikrotik-ospf-pair + template_version: 1 + seed: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + ttl_seconds: 3600 + responses: + "200": + description: A lab with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + "202": + description: The lab was accepted and is provisioning. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + examples: + provisioning: + summary: A lab that is being cloned and booted + value: + lab_id: 2f1c7a52-0d3e-4b8e-9b61-3c7b1f2e9a40 + state: provisioning + template_id: mikrotik-ospf-pair + template_version: 1 + created_at: "2026-10-11T09:00:00Z" + expires_at: "2026-10-11T10:00:00Z" + nodes: + - name: r1 + kind: mikrotik + - name: r2 + kind: mikrotik + "503": + $ref: ../components/responses.yml#/LabPoolBusy + default: + $ref: ../components/responses.yml#/Problem +get: + operationId: GetLab + summary: Read the state of a lab. + description: >- + Answers 404 `not_found` for an ID the provisioner does not hold, + including a lab whose `deleted` record outlived its retention time. The + response never contains an address, a key, or an LXD object name. + tags: + - labs + responses: + "200": + description: The current state of the lab. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + default: + $ref: ../components/responses.yml#/Problem +delete: + operationId: DeleteLab + summary: Delete a lab before its timer. + description: >- + Marks the lab for deletion and answers 202 with `state: deleting`; the + provisioner removes its instances and bridges in the background and + retries until LXD confirms that they are gone, also across its own + restarts. Deleting a lab that is already `deleting` or `deleted` + answers 200 with its state and changes nothing. An unknown ID answers + 404 `not_found`. + tags: + - labs + responses: + "200": + description: The lab was already being deleted or is deleted. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + "202": + description: The lab is being deleted. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabStatus + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/labd/routes/readyz.yml b/api/labd/routes/readyz.yml new file mode 100644 index 0000000..afb53ad --- /dev/null +++ b/api/labd/routes/readyz.yml @@ -0,0 +1,26 @@ +get: + operationId: GetLabdReadyz + summary: Check whether the provisioner can create and delete labs. + description: >- + Ready means that the lab records were loaded, the startup reconciliation + with LXD finished, the LXD API answered the latest probe, and the process + is not draining. A provisioner without free capacity is still ready; + capacity is reported by CreateLab. + security: [] + tags: + - health + responses: + "200": + description: The provisioner is ready. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabdReadinessResponse + "503": + description: The provisioner is not ready or is draining. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/LabdReadinessResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/ml/components/responses.yml b/api/ml/components/responses.yml new file mode 100644 index 0000000..1e3361d --- /dev/null +++ b/api/ml/components/responses.yml @@ -0,0 +1,30 @@ +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. diff --git a/api/ml/components/schemas.yml b/api/ml/components/schemas.yml index b853c09..ec37885 100644 --- a/api/ml/components/schemas.yml +++ b/api/ml/components/schemas.yml @@ -1,3 +1,109 @@ +EmbeddingInputKind: + type: string + description: 'Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so callers never send model instructions. + + + - query: the side that searches, such as a hiring need or one requirement of it. The service prepends the retrieval instruction of the model. + + - document: the side that is searched, such as a candidate card or one item of it. The service adds no prompt.' + enum: + - query + - document +EmbeddingText: + type: string + minLength: 1 + maxLength: 8000 + description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead. +EmbeddingRequest: + type: object + description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same installation, device, precision, and thread count give the same vectors.' + additionalProperties: false + required: + - kind + - texts + properties: + model: + type: string + minLength: 1 + maxLength: 200 + pattern: ^[A-Za-z0-9._/-]+$ + description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`. + kind: + $ref: '#/EmbeddingInputKind' + texts: + type: array + minItems: 1 + maxItems: 32 + items: + $ref: '#/EmbeddingText' +EmbeddingModel: + type: object + description: The model that produced the vectors. A caller stores these values with every vector and never compares vectors of different models, revisions, or prompt versions. + additionalProperties: false + required: + - id + - revision + - dimension + - max_tokens + - prompt_version + properties: + id: + type: string + minLength: 1 + maxLength: 200 + pattern: ^[A-Za-z0-9._/-]+$ + description: Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826. + revision: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Pinned revision of the weights, a commit hash for a published model. + dimension: + type: integer + format: int32 + minimum: 1 + maximum: 4096 + description: Length of every vector. + max_tokens: + type: integer + format: int32 + minimum: 1 + maximum: 32768 + description: Token limit after which a text is truncated. + prompt_version: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9._-]+$ + description: Version of the prompt and pooling recipe of the service. A change of the query instruction or the pooling changes it. +EmbeddingVector: + type: array + description: L2-normalized vector of one text, in float32 precision. The cosine of two vectors of the same model is their dot product. + minItems: 1 + maxItems: 4096 + items: + type: number + format: float +EmbeddingResponse: + type: object + description: Vectors in the order of the request texts. + additionalProperties: false + required: + - model + - kind + - vectors + properties: + model: + $ref: '#/EmbeddingModel' + kind: + $ref: '#/EmbeddingInputKind' + vectors: + type: array + minItems: 1 + maxItems: 32 + items: + $ref: '#/EmbeddingVector' MLHealthResponse: type: object additionalProperties: false @@ -8,6 +114,153 @@ MLHealthResponse: type: string enum: - ok +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the ML service copy of the public api/core Problem schema; keep both copies identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + + - unauthenticated (401): no valid session or credentials. + + - forbidden (403): the caller is authenticated but not allowed. + + - not_found (404): the route or object does not exist or is not visible. + + - method_not_allowed (405): the route does not support the method. + + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + + - version_conflict (412): If-Match does not match the current version. + + - payload_too_large (413): the request body exceeds the limit. + + - unsupported_media_type (415): the request Content-Type is not accepted. + + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + + - precondition_required (428): the operation requires If-Match. + + - rate_limited (429): too many requests; see Retry-After. + + - internal (500): unexpected server error. + + - not_implemented (501): the operation is in the contract but not implemented yet. + + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later. + + + 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 + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + - service_unavailable +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie MLReadinessResponse: type: object additionalProperties: false diff --git a/api/ml/components/schemas/embedding_schemas.yml b/api/ml/components/schemas/embedding_schemas.yml new file mode 100644 index 0000000..2844fcb --- /dev/null +++ b/api/ml/components/schemas/embedding_schemas.yml @@ -0,0 +1,127 @@ +schemas: + EmbeddingInputKind: + type: string + description: |- + Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so callers never send model instructions. + + - query: the side that searches, such as a hiring need or one requirement of it. The service prepends the retrieval instruction of the model. + - document: the side that is searched, such as a candidate card or one item of it. The service adds no prompt. + enum: + - query + - document + EmbeddingText: + type: string + minLength: 1 + maxLength: 8000 + description: >- + One plain text to encode. It is untrusted data and never an instruction. + The service truncates it deterministically to the token limit of the + model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected + instead. + EmbeddingRequest: + type: object + description: >- + Texts to encode in one call. The service encodes them in a fixed, + deterministic way: texts are ordered by length with the request position + as the tie-breaker, encoded in micro-batches of the configured size, and + returned in request order. The same texts in the same request on the same + installation, device, precision, and thread count give the same vectors. + additionalProperties: false + required: + - kind + - texts + properties: + model: + type: string + minLength: 1 + maxLength: 200 + pattern: "^[A-Za-z0-9._/-]+$" + description: >- + Identifier of the model to use, as `EmbeddingModel.id` reports it. + Absent means the default model of the service, the first one it is + configured with. A service may load several models, for example the + members of an ensemble; a model it does not serve answers 400 + validation_failed with the pointer `/model`. + kind: + $ref: "#/schemas/EmbeddingInputKind" + texts: + type: array + minItems: 1 + maxItems: 32 + items: + $ref: "#/schemas/EmbeddingText" + EmbeddingModel: + type: object + description: >- + The model that produced the vectors. A caller stores these values with + every vector and never compares vectors of different models, revisions, + or prompt versions. + additionalProperties: false + required: + - id + - revision + - dimension + - max_tokens + - prompt_version + properties: + id: + type: string + minLength: 1 + maxLength: 200 + pattern: "^[A-Za-z0-9._/-]+$" + description: Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826. + revision: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[A-Za-z0-9._-]+$" + description: Pinned revision of the weights, a commit hash for a published model. + dimension: + type: integer + format: int32 + minimum: 1 + maximum: 4096 + description: Length of every vector. + max_tokens: + type: integer + format: int32 + minimum: 1 + maximum: 32768 + description: Token limit after which a text is truncated. + prompt_version: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z0-9._-]+$" + description: >- + Version of the prompt and pooling recipe of the service. A change of + the query instruction or the pooling changes it. + EmbeddingVector: + type: array + description: >- + L2-normalized vector of one text, in float32 precision. The cosine of two + vectors of the same model is their dot product. + minItems: 1 + maxItems: 4096 + items: + type: number + format: float + EmbeddingResponse: + type: object + description: Vectors in the order of the request texts. + additionalProperties: false + required: + - model + - kind + - vectors + properties: + model: + $ref: "#/schemas/EmbeddingModel" + kind: + $ref: "#/schemas/EmbeddingInputKind" + vectors: + type: array + minItems: 1 + maxItems: 32 + items: + $ref: "#/schemas/EmbeddingVector" diff --git a/api/ml/components/schemas/problem_schemas.yml b/api/ml/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..8c6b2a2 --- /dev/null +++ b/api/ml/components/schemas/problem_schemas.yml @@ -0,0 +1,157 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. This is the ML service copy of the + public api/core Problem schema; keep both copies identical except for + descriptions. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier of the call when the caller propagated one; it is + not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - unauthenticated (401): no valid session or credentials. + - forbidden (403): the caller is authenticated but not allowed. + - not_found (404): the route or object does not exist or is not visible. + - method_not_allowed (405): the route does not support the method. + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + - version_conflict (412): If-Match does not match the current version. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + - precondition_required (428): the operation requires If-Match. + - rate_limited (429): too many requests; see Retry-After. + - internal (500): unexpected server error. + - not_implemented (501): the operation is in the contract but not implemented yet. + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later. + + 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 + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + - service_unavailable + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/salary_from`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/ml/openapi.bundle.yml b/api/ml/openapi.bundle.yml index 300e18f..d87d7c6 100644 --- a/api/ml/openapi.bundle.yml +++ b/api/ml/openapi.bundle.yml @@ -2,8 +2,21 @@ openapi: 3.2.0 info: title: Lincodex ML Operational API version: 0.1.0 + description: |- + Internal API of the ML service. Only the Go backend calls it; it is never + exposed to browsers or to the public network. + + Authentication: every operation except the health routes requires + `Authorization: Bearer ` when the service has a token, and the + service refuses to listen on a non-loopback address without one. The + token is a shared random secret of at least 32 printable characters from + the deployment secret store, never from this repository. A missing or + wrong token answers 401 `unauthenticated`. A service without a token + answers only callers on its own loopback interface. servers: - url: / +security: + - bearerAuth: [] paths: /healthz: get: @@ -19,6 +32,8 @@ paths: application/json: schema: $ref: '#/components/schemas/MLHealthResponse' + default: + $ref: '#/components/responses/Problem' /readyz: get: operationId: GetMLReadyz @@ -39,8 +54,208 @@ paths: application/json: schema: $ref: '#/components/schemas/MLReadinessResponse' + default: + $ref: '#/components/responses/Problem' + /v1/embeddings: + post: + operationId: CreateMLEmbeddings + summary: Encode texts into normalized vectors with a pinned embedding model. + description: |- + Internal operation for the Go backend; it is not reachable from browsers and needs the service bearer token. The request carries only text that the caller is allowed to process, and the service never logs it. + + The service may load several pinned models, for example the members of an ensemble; `model` selects one, and the response names the model, revision, dimension, and prompt version that produced the vectors. The service answers 503 service_unavailable until every configured model is loaded and a warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports the same state. A request without a valid token answers 401, a request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400. + tags: + - inference + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmbeddingRequest' + responses: + '200': + description: One vector for each text, in request order. + content: + application/json: + schema: + $ref: '#/components/schemas/EmbeddingResponse' + '400': + $ref: '#/components/responses/Problem' + '401': + $ref: '#/components/responses/Problem' + '413': + $ref: '#/components/responses/Problem' + '503': + $ref: '#/components/responses/Problem' + default: + $ref: '#/components/responses/Problem' components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: 'Shared random service token sent as `Authorization: Bearer `. The service compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.' + responses: + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + summary: Request parameters do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: query + pointer: /limit + code: invalid + message: The value does not match the contract. + internal: + summary: Unexpected server error + value: + type: urn:lincodex:problem:internal + title: Internal server error + status: 500 + code: internal + detail: The server could not complete the request. schemas: + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - unauthenticated (401): no valid session or credentials. + - forbidden (403): the caller is authenticated but not allowed. + - not_found (404): the route or object does not exist or is not visible. + - method_not_allowed (405): the route does not support the method. + - idempotency_in_progress (409): a request with the same Idempotency-Key is still being processed. + - state_conflict (409): the operation conflicts with the current state of the resource, for example an invitation that was already accepted. + - version_conflict (412): If-Match does not match the current version. + - payload_too_large (413): the request body exceeds the limit. + - unsupported_media_type (415): the request Content-Type is not accepted. + - idempotency_key_reused (422): the Idempotency-Key was already used with a different request. + - precondition_required (428): the operation requires If-Match. + - rate_limited (429): too many requests; see Retry-After. + - internal (500): unexpected server error. + - not_implemented (501): the operation is in the contract but not implemented yet. + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later. + + 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 + - state_conflict + - version_conflict + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - precondition_required + - rate_limited + - internal + - not_implemented + - service_unavailable + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the ML service copy of the public api/core Problem schema; keep both copies identical except for descriptions. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' MLHealthResponse: type: object additionalProperties: false @@ -62,3 +277,108 @@ components: enum: - ready - not_ready + EmbeddingInputKind: + type: string + description: |- + Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so callers never send model instructions. + + - query: the side that searches, such as a hiring need or one requirement of it. The service prepends the retrieval instruction of the model. + - document: the side that is searched, such as a candidate card or one item of it. The service adds no prompt. + enum: + - query + - document + EmbeddingText: + type: string + minLength: 1 + maxLength: 8000 + description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead. + EmbeddingRequest: + type: object + description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same installation, device, precision, and thread count give the same vectors.' + additionalProperties: false + required: + - kind + - texts + properties: + model: + type: string + minLength: 1 + maxLength: 200 + pattern: ^[A-Za-z0-9._/-]+$ + description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`. + kind: + $ref: '#/components/schemas/EmbeddingInputKind' + texts: + type: array + minItems: 1 + maxItems: 32 + items: + $ref: '#/components/schemas/EmbeddingText' + EmbeddingModel: + type: object + description: The model that produced the vectors. A caller stores these values with every vector and never compares vectors of different models, revisions, or prompt versions. + additionalProperties: false + required: + - id + - revision + - dimension + - max_tokens + - prompt_version + properties: + id: + type: string + minLength: 1 + maxLength: 200 + pattern: ^[A-Za-z0-9._/-]+$ + description: Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826. + revision: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[A-Za-z0-9._-]+$ + description: Pinned revision of the weights, a commit hash for a published model. + dimension: + type: integer + format: int32 + minimum: 1 + maximum: 4096 + description: Length of every vector. + max_tokens: + type: integer + format: int32 + minimum: 1 + maximum: 32768 + description: Token limit after which a text is truncated. + prompt_version: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z0-9._-]+$ + description: Version of the prompt and pooling recipe of the service. A change of the query instruction or the pooling changes it. + EmbeddingVector: + type: array + description: L2-normalized vector of one text, in float32 precision. The cosine of two vectors of the same model is their dot product. + minItems: 1 + maxItems: 4096 + items: + type: number + format: float + EmbeddingResponse: + type: object + description: Vectors in the order of the request texts. + additionalProperties: false + required: + - model + - kind + - vectors + properties: + model: + $ref: '#/components/schemas/EmbeddingModel' + kind: + $ref: '#/components/schemas/EmbeddingInputKind' + vectors: + type: array + minItems: 1 + maxItems: 32 + items: + $ref: '#/components/schemas/EmbeddingVector' diff --git a/api/ml/openapi.yml b/api/ml/openapi.yml index f9bd5c8..2a75405 100644 --- a/api/ml/openapi.yml +++ b/api/ml/openapi.yml @@ -2,10 +2,37 @@ openapi: 3.2.0 info: title: Lincodex ML Operational API version: 0.1.0 + description: |- + Internal API of the ML service. Only the Go backend calls it; it is never + exposed to browsers or to the public network. + + Authentication: every operation except the health routes requires + `Authorization: Bearer ` when the service has a token, and the + service refuses to listen on a non-loopback address without one. The + token is a shared random secret of at least 32 printable characters from + the deployment secret store, never from this repository. A missing or + wrong token answers 401 `unauthenticated`. A service without a token + answers only callers on its own loopback interface. servers: - url: / +security: + - bearerAuth: [] paths: /healthz: $ref: ./routes/healthz.yml /readyz: $ref: ./routes/readyz.yml + /v1/embeddings: + $ref: ./routes/embeddings.yml +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: >- + Shared random service token sent as `Authorization: Bearer `. + The service compares it in constant time and never logs it. Rotation + replaces the secret on both sides; there are no per-user tokens. + responses: + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/ml/routes/embeddings.yml b/api/ml/routes/embeddings.yml new file mode 100644 index 0000000..2792947 --- /dev/null +++ b/api/ml/routes/embeddings.yml @@ -0,0 +1,32 @@ +post: + operationId: CreateMLEmbeddings + summary: Encode texts into normalized vectors with a pinned embedding model. + description: |- + Internal operation for the Go backend; it is not reachable from browsers and needs the service bearer token. The request carries only text that the caller is allowed to process, and the service never logs it. + + The service may load several pinned models, for example the members of an ensemble; `model` selects one, and the response names the model, revision, dimension, and prompt version that produced the vectors. The service answers 503 service_unavailable until every configured model is loaded and a warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports the same state. A request without a valid token answers 401, a request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400. + tags: + - inference + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmbeddingRequest + responses: + "200": + description: One vector for each text, in request order. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmbeddingResponse + "400": + $ref: ../components/responses.yml#/Problem + "401": + $ref: ../components/responses.yml#/Problem + "413": + $ref: ../components/responses.yml#/Problem + "503": + $ref: ../components/responses.yml#/Problem + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/ml/routes/healthz.yml b/api/ml/routes/healthz.yml index 77f1350..a262e03 100644 --- a/api/ml/routes/healthz.yml +++ b/api/ml/routes/healthz.yml @@ -11,3 +11,5 @@ get: application/json: schema: $ref: ../components/schemas.yml#/MLHealthResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/ml/routes/readyz.yml b/api/ml/routes/readyz.yml index deeccc7..fa2aa4b 100644 --- a/api/ml/routes/readyz.yml +++ b/api/ml/routes/readyz.yml @@ -17,3 +17,5 @@ get: application/json: schema: $ref: ../components/schemas.yml#/MLReadinessResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/redocly.yaml b/api/redocly.yaml index 485cbb6..0fac86f 100644 --- a/api/redocly.yaml +++ b/api/redocly.yaml @@ -3,3 +3,4 @@ extends: rules: info-license: off operation-4xx-response: off + no-invalid-media-type-examples: error diff --git a/api/runner/components/responses.yml b/api/runner/components/responses.yml new file mode 100644 index 0000000..55781d6 --- /dev/null +++ b/api/runner/components/responses.yml @@ -0,0 +1,57 @@ +Problem: + description: >- + Any error response. The body is a Problem whose `status` equals the HTTP + status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + validation_failed: + summary: Request fields do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: body + pointer: /groups/1/id + code: invalid + message: The value does not match the contract. + idempotency_key_reused: + summary: The run ID was used with a different payload + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Run ID reused with a different payload + status: 422 + code: idempotency_key_reused + detail: A run with this ID exists with a different payload. +RunnerBusy: + description: >- + Every sandbox slot is busy or the runner is draining; code runner_busy. + Nothing was stored. Retry with the same run ID after Retry-After. + headers: + Retry-After: + description: Number of seconds to wait before retrying the request. + required: true + schema: + type: integer + format: int32 + minimum: 0 + maximum: 3600 + example: 2 + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + runner_busy: + summary: No free sandbox slot + value: + type: urn:lincodex:problem:runner_busy + title: Runner busy + status: 503 + code: runner_busy + detail: Every sandbox slot is busy. Retry later with the same run ID. diff --git a/api/runner/components/schemas.yml b/api/runner/components/schemas.yml new file mode 100644 index 0000000..d4fb009 --- /dev/null +++ b/api/runner/components/schemas.yml @@ -0,0 +1,487 @@ +RunnerHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok +RunnerReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready +Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/ProblemFieldError' +ProblemCode: + type: string + description: 'Stable error code of the runner API. 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 semantic rule of SubmitRun; `errors` points at the fields. + + - unauthenticated (401): the bearer token is missing or wrong. + + - not_found (404): the route or the run does not exist. + + - method_not_allowed (405): the route does not support the method. + + - 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 run ID was already used with a different payload. + + - internal (500): unexpected server error. + + - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. + + + The Problem shape is the api/core shape; only this enum is specific to the runner.' + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - runner_busy +ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. +ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie +RunRequest: + type: object + description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records. + additionalProperties: false + required: + - language + - source + - limits + - groups + properties: + language: + $ref: '#/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 + description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it. + limits: + $ref: '#/RunLimits' + groups: + type: array + minItems: 1 + maxItems: 4 + description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run. + items: + $ref: '#/TestGroup' +RunLanguage: + type: string + description: Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. `go` compiles one `package main` file with the Go toolchain of the runner image against a prebuilt standard library (no modules, no cgo, no network) in a separate compile phase with its own limits; a compile or link error is compile_error and no test runs. + enum: + - python3 + - go +RunLimits: + type: object + description: Limits applied to every test of the run. + additionalProperties: false + required: + - time_limit_ms + - memory_limit_mb + - output_limit_kb + properties: + time_limit_ms: + type: integer + format: int32 + minimum: 100 + maximum: 10000 + description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance. + memory_limit_mb: + type: integer + format: int32 + minimum: 32 + maximum: 512 + description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process. + output_limit_kb: + type: integer + format: int32 + minimum: 1 + maximum: 1024 + description: Standard output per test in KiB. The test is stopped as soon as it writes more. +TestGroup: + type: object + additionalProperties: false + required: + - id + - visibility + - checker + - tests + properties: + id: + $ref: '#/TestKey' + visibility: + $ref: '#/TestVisibility' + checker: + $ref: '#/Checker' + tests: + type: array + minItems: 1 + maxItems: 50 + description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test. + items: + $ref: '#/TestCase' +TestKey: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier. +TestVisibility: + type: string + description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.' + enum: + - public + - hidden +Checker: + type: object + description: How the standard output of a test is compared with `expected_output`. `numbers` requires `abs_tolerance`, `rel_tolerance`, or both; `custom` requires `program`. Other kinds take no parameter. New kinds add a `kind` value and their own optional parameters. + additionalProperties: false + required: + - kind + properties: + kind: + $ref: '#/CheckerKind' + abs_tolerance: + type: number + format: double + minimum: 0 + maximum: 1000000000 + description: Largest accepted absolute difference of two numeric tokens. + rel_tolerance: + type: number + format: double + minimum: 0 + maximum: 1 + description: Largest accepted difference of two numeric tokens relative to the expected value. + program: + $ref: '#/CheckerProgram' +CheckerProgram: + type: object + description: 'Checker program of the task family. It runs in the sandbox with the same isolation as the solution and fixed limits of its own (5 s CPU, 256 MiB). Its arguments are the paths of three read-only files: the test input, the expected output, and the actual output. Exit status 0 accepts, 1 rejects, and anything else, a signal, or a limit is a checker failure, which makes the run infrastructure_failure. Its own output is discarded and never returned.' + additionalProperties: false + required: + - language + - source + properties: + language: + $ref: '#/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 +CheckerKind: + type: string + description: '- exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines. + + - tokens: both texts split on ASCII whitespace give the same sequence of tokens. + + - numbers: like tokens, but two finite numeric tokens are equal when their difference is within abs_tolerance or within rel_tolerance times the expected value; other tokens must be equal. + + - custom: the checker program of the task family decides in the sandbox.' + enum: + - exact + - tokens + - numbers + - custom +TestCase: + type: object + additionalProperties: false + required: + - id + - input + - expected_output + properties: + id: + $ref: '#/TestKey' + input: + type: string + maxLength: 262144 + description: UTF-8 text written to the standard input of the program. + expected_output: + type: string + maxLength: 262144 + description: UTF-8 text the checker compares with the standard output. +RunState: + type: string + description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.' + enum: + - running + - finished +RunStatus: + type: object + additionalProperties: false + required: + - run_id + - state + properties: + run_id: + type: string + format: uuid + state: + $ref: '#/RunState' + result: + $ref: '#/RunResult' +RunOutcome: + type: string + description: 'Outcome of a test, a group, a compile step, or a whole run. + + + - accepted: the program exited with status 0 within every limit and the checker accepted the output. + + - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output. + + - compile_error: the source was rejected before any test ran (for Python, a syntax error). + + - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. + + - memory_limit_exceeded: the cgroup memory limit stopped the program. + + - output_limit_exceeded: the program wrote more standard output than the limit. + + - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit. + + - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID. + + + A run''s outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group''s outcome is the outcome of its first failed test, otherwise accepted.' + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + - infrastructure_failure +TerminationLimit: + type: string + description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.' + enum: + - cpu_time + - wall_time + - memory + - output + - processes +RunResult: + type: object + additionalProperties: false + required: + - outcome + - groups + - duration_ms + properties: + outcome: + $ref: '#/RunOutcome' + compile: + $ref: '#/CompileResult' + groups: + type: array + maxItems: 4 + description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests. + items: + $ref: '#/GroupResult' + duration_ms: + type: integer + format: int64 + minimum: 0 + description: Wall-clock time of the whole run in the runner. +CompileResult: + type: object + additionalProperties: false + required: + - outcome + properties: + outcome: + $ref: '#/RunOutcome' + diagnostic: + type: string + maxLength: 4096 + description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data. +GroupResult: + type: object + additionalProperties: false + required: + - id + - visibility + - outcome + - passed_tests + - total_tests + - tests + properties: + id: + $ref: '#/TestKey' + visibility: + $ref: '#/TestVisibility' + outcome: + $ref: '#/RunOutcome' + passed_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + total_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + max_time_ms: + type: integer + format: int64 + minimum: 0 + description: Largest CPU time of an evaluated test of the group. + max_memory_kb: + type: integer + format: int64 + minimum: 0 + description: Largest peak memory of an evaluated test of the group. + tests: + type: array + maxItems: 50 + description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed. + items: + $ref: '#/TestResult' +TestResult: + type: object + additionalProperties: false + required: + - id + - outcome + - time_ms + - wall_time_ms + - memory_kb + properties: + id: + $ref: '#/TestKey' + outcome: + $ref: '#/RunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + description: CPU time of every process of the test. + wall_time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.' + exit_code: + type: integer + format: int32 + description: Exit status when the program exited normally. + signal: + type: integer + format: int32 + minimum: 1 + maximum: 64 + description: Signal number when the program was killed by a signal. + limit: + $ref: '#/TerminationLimit' + diagnostic: + type: string + maxLength: 2048 + description: Truncated standard error of a failed public test. Hidden tests never carry it. diff --git a/api/runner/components/schemas/health_schemas.yml b/api/runner/components/schemas/health_schemas.yml new file mode 100644 index 0000000..64672f2 --- /dev/null +++ b/api/runner/components/schemas/health_schemas.yml @@ -0,0 +1,22 @@ +schemas: + RunnerHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + RunnerReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready diff --git a/api/runner/components/schemas/problem_schemas.yml b/api/runner/components/schemas/problem_schemas.yml new file mode 100644 index 0000000..1dd5bfb --- /dev/null +++ b/api/runner/components/schemas/problem_schemas.yml @@ -0,0 +1,138 @@ +schemas: + Problem: + type: object + description: >- + Problem details (RFC 9457) returned with the application/problem+json + media type for every error response. This is the runner copy of the + public api/core Problem schema; keep both copies identical except for + descriptions and the ProblemCode enum. `code` is the stable, + machine-readable reason; clients branch on it rather than on `title`, + `detail`, or the HTTP status alone. The body never contains internal + error text, stack traces, SQL, file paths, credentials, contact data, or + echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: >- + URI that identifies the problem type. It has the form + `urn:lincodex:problem:` and is an identifier, not a link to + dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: >- + Short, fixed English summary of the problem type. It does not change + between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: >- + Safe English explanation of this occurrence. It never contains + internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: "^[A-Za-z0-9._-]+$" + description: >- + Request identifier of the call when the caller propagated one; it is + not a secret. + errors: + type: array + maxItems: 100 + description: >- + Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: "#/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable error code of the runner API. 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 semantic rule of SubmitRun; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the run does not exist. + - method_not_allowed (405): the route does not support the method. + - 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 run ID was already used with a different payload. + - internal (500): unexpected server error. + - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. + + The Problem shape is the api/core shape; only this enum is specific to the runner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - runner_busy + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: "^(/([^~/]|~[01])*)*$" + description: >- + JSON Pointer (RFC 6901). For `body` it points into the request body + document, for example `/limits/time_limit_ms`; an empty string means the whole + body. For a parameter it is `/` followed by the parameter name, for + example `/run_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: "^[a-z][a-z0-9_]*$" + description: >- + Stable field reason. Current values are `required` (missing value) + and `invalid` (malformed value or a value outside the schema). + Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie diff --git a/api/runner/components/schemas/run_schemas.yml b/api/runner/components/schemas/run_schemas.yml new file mode 100644 index 0000000..4c7ba73 --- /dev/null +++ b/api/runner/components/schemas/run_schemas.yml @@ -0,0 +1,394 @@ +schemas: + RunRequest: + type: object + description: >- + One source and its test groups. The request has no field for a + candidate, account, attempt, task, or company; the backend maps a run ID + to its own records. + additionalProperties: false + required: + - language + - source + - limits + - groups + properties: + language: + $ref: "#/schemas/RunLanguage" + source: + type: string + minLength: 1 + maxLength: 65536 + description: >- + Complete program text in UTF-8. The runner writes it to a read-only + file inside the sandbox and never logs it. + limits: + $ref: "#/schemas/RunLimits" + groups: + type: array + minItems: 1 + maxItems: 4 + description: >- + Test groups in evaluation order, for example one public group and + three hidden groups. Group IDs are unique in a run. + items: + $ref: "#/schemas/TestGroup" + RunLanguage: + type: string + description: >- + Language and runtime of the source. `python3` runs the Python 3 + interpreter of the runner image with isolated mode and no bytecode + writes; a syntax check runs first and fails with compile_error. `go` + compiles one `package main` file with the Go toolchain of the runner + image against a prebuilt standard library (no modules, no cgo, no + network) in a separate compile phase with its own limits; a compile + or link error is compile_error and no test runs. + enum: + - python3 + - go + RunLimits: + type: object + description: Limits applied to every test of the run. + additionalProperties: false + required: + - time_limit_ms + - memory_limit_mb + - output_limit_kb + properties: + time_limit_ms: + type: integer + format: int32 + minimum: 100 + maximum: 10000 + description: >- + CPU time per test, including interpreter startup, summed over every + process of the test. The wall-clock limit is twice this value plus + a fixed startup allowance. + memory_limit_mb: + type: integer + format: int32 + minimum: 32 + maximum: 512 + description: >- + Memory of the test's processes in MiB, enforced by a cgroup v2 + memory limit without swap. The limit also leaves a small fixed + allowance for the sandbox supervisor process. + output_limit_kb: + type: integer + format: int32 + minimum: 1 + maximum: 1024 + description: >- + Standard output per test in KiB. The test is stopped as soon as it + writes more. + TestGroup: + type: object + additionalProperties: false + required: + - id + - visibility + - checker + - tests + properties: + id: + $ref: "#/schemas/TestKey" + visibility: + $ref: "#/schemas/TestVisibility" + checker: + $ref: "#/schemas/Checker" + tests: + type: array + minItems: 1 + maxItems: 50 + description: >- + Tests in evaluation order. Test IDs are unique in a group. A group + stops at its first failed test. + items: + $ref: "#/schemas/TestCase" + TestKey: + type: string + minLength: 1 + maxLength: 32 + pattern: "^[a-z0-9][a-z0-9_-]{0,31}$" + description: >- + Opaque label chosen by the backend, for example `public` or `hidden-1`. + It is not a database identifier. + TestVisibility: + type: string + description: >- + `public` tests may be shown to the person who wrote the source; their + results may carry a diagnostic excerpt. `hidden` results never carry + program output or diagnostics. + enum: + - public + - hidden + Checker: + type: object + description: >- + How the standard output of a test is compared with `expected_output`. + `numbers` requires `abs_tolerance`, `rel_tolerance`, or both; `custom` + requires `program`. Other kinds take no parameter. New kinds add a + `kind` value and their own optional parameters. + additionalProperties: false + required: + - kind + properties: + kind: + $ref: "#/schemas/CheckerKind" + abs_tolerance: + type: number + format: double + minimum: 0 + maximum: 1000000000 + description: Largest accepted absolute difference of two numeric tokens. + rel_tolerance: + type: number + format: double + minimum: 0 + maximum: 1 + description: >- + Largest accepted difference of two numeric tokens relative to the + expected value. + program: + $ref: "#/schemas/CheckerProgram" + CheckerProgram: + type: object + description: >- + Checker program of the task family. It runs in the sandbox with the + same isolation as the solution and fixed limits of its own (5 s CPU, + 256 MiB). Its arguments are the paths of three read-only files: the + test input, the expected output, and the actual output. Exit status 0 + accepts, 1 rejects, and anything else, a signal, or a limit is a + checker failure, which makes the run infrastructure_failure. Its own + output is discarded and never returned. + additionalProperties: false + required: + - language + - source + properties: + language: + $ref: "#/schemas/RunLanguage" + source: + type: string + minLength: 1 + maxLength: 65536 + CheckerKind: + type: string + description: |- + - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines. + - tokens: both texts split on ASCII whitespace give the same sequence of tokens. + - numbers: like tokens, but two finite numeric tokens are equal when their difference is within abs_tolerance or within rel_tolerance times the expected value; other tokens must be equal. + - custom: the checker program of the task family decides in the sandbox. + enum: + - exact + - tokens + - numbers + - custom + TestCase: + type: object + additionalProperties: false + required: + - id + - input + - expected_output + properties: + id: + $ref: "#/schemas/TestKey" + input: + type: string + maxLength: 262144 + description: UTF-8 text written to the standard input of the program. + expected_output: + type: string + maxLength: 262144 + description: UTF-8 text the checker compares with the standard output. + RunState: + type: string + description: >- + `running` until every group was evaluated or the run failed; + `finished` when `result` is final. + enum: + - running + - finished + RunStatus: + type: object + additionalProperties: false + required: + - run_id + - state + properties: + run_id: + type: string + format: uuid + state: + $ref: "#/schemas/RunState" + result: + $ref: "#/schemas/RunResult" + RunOutcome: + type: string + description: |- + Outcome of a test, a group, a compile step, or a whole run. + + - accepted: the program exited with status 0 within every limit and the checker accepted the output. + - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output. + - compile_error: the source was rejected before any test ran (for Python, a syntax error). + - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. + - memory_limit_exceeded: the cgroup memory limit stopped the program. + - output_limit_exceeded: the program wrote more standard output than the limit. + - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit. + - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID. + + A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + - infrastructure_failure + TerminationLimit: + type: string + description: >- + The limit that stopped a test: CPU time, wall-clock time, memory, + standard output, or the number of processes and threads. + enum: + - cpu_time + - wall_time + - memory + - output + - processes + RunResult: + type: object + additionalProperties: false + required: + - outcome + - groups + - duration_ms + properties: + outcome: + $ref: "#/schemas/RunOutcome" + compile: + $ref: "#/schemas/CompileResult" + groups: + type: array + maxItems: 4 + description: >- + One result per requested group in request order. After + compile_error or infrastructure_failure every group has that + outcome and no tests. + items: + $ref: "#/schemas/GroupResult" + duration_ms: + type: integer + format: int64 + minimum: 0 + description: Wall-clock time of the whole run in the runner. + CompileResult: + type: object + additionalProperties: false + required: + - outcome + properties: + outcome: + $ref: "#/schemas/RunOutcome" + diagnostic: + type: string + maxLength: 4096 + description: >- + Compiler or syntax checker message for compile_error, truncated to + the limit. It can quote the source, never test data. + GroupResult: + type: object + additionalProperties: false + required: + - id + - visibility + - outcome + - passed_tests + - total_tests + - tests + properties: + id: + $ref: "#/schemas/TestKey" + visibility: + $ref: "#/schemas/TestVisibility" + outcome: + $ref: "#/schemas/RunOutcome" + passed_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + total_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + max_time_ms: + type: integer + format: int64 + minimum: 0 + description: Largest CPU time of an evaluated test of the group. + max_memory_kb: + type: integer + format: int64 + minimum: 0 + description: Largest peak memory of an evaluated test of the group. + tests: + type: array + maxItems: 50 + description: >- + Results of the evaluated tests in order. Tests after the first + failed one are not run and not listed. + items: + $ref: "#/schemas/TestResult" + TestResult: + type: object + additionalProperties: false + required: + - id + - outcome + - time_ms + - wall_time_ms + - memory_kb + properties: + id: + $ref: "#/schemas/TestKey" + outcome: + $ref: "#/schemas/RunOutcome" + time_ms: + type: integer + format: int64 + minimum: 0 + description: CPU time of every process of the test. + wall_time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + description: >- + Peak memory of the test in KiB: the cgroup high-water mark of every + process of the test, including the sandbox supervisor process and + file cache charged to the test. + exit_code: + type: integer + format: int32 + description: Exit status when the program exited normally. + signal: + type: integer + format: int32 + minimum: 1 + maximum: 64 + description: Signal number when the program was killed by a signal. + limit: + $ref: "#/schemas/TerminationLimit" + diagnostic: + type: string + maxLength: 2048 + description: >- + Truncated standard error of a failed public test. Hidden tests + never carry it. diff --git a/api/runner/openapi.bundle.yml b/api/runner/openapi.bundle.yml new file mode 100644 index 0000000..9f6653f --- /dev/null +++ b/api/runner/openapi.bundle.yml @@ -0,0 +1,668 @@ +openapi: 3.2.0 +info: + title: Lincodex Code Runner API + version: 0.1.0 + description: |- + Internal API of the own code runner. Only the Go backend calls it; it is + never exposed to browsers or to the public network. + + Transport and authentication: the runner listens on a private network + interface of its dedicated host and serves HTTPS (TLS 1.3). Every + operation except the health routes requires `Authorization: Bearer + `; the token is a shared random secret of at least 32 characters + that comes from the deployment secret store, never from this repository. + A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists + only behind an explicit development switch of the local Compose file. + + Data minimization: a run carries only the language, the source code, the + limits, and the test groups. It has no candidate, account, attempt, or + task identifiers, names, or contacts. The run ID is a random UUID chosen + by the backend for idempotency; the runner keeps it only in memory. + + Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free + and answers immediately; the caller polls GetRun until `state` is + `finished`. The runner does not queue runs: when every slot is busy it + answers 503 `runner_busy`, and the backend keeps the queue. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + get: + operationId: GetRunnerHealthz + summary: Check whether the runner process is responding. + security: [] + tags: + - health + responses: + '200': + description: The runner process is responding. + content: + application/json: + schema: + $ref: '#/components/schemas/RunnerHealthResponse' + default: + $ref: '#/components/responses/Problem' + /readyz: + get: + operationId: GetRunnerReadyz + summary: Check whether the sandbox is prepared to accept runs. + description: Ready means that the cgroup hierarchy, the work directory, and the sandbox binary were prepared at startup and the process is not draining. A busy runner is still ready; busy is reported by SubmitRun. + security: [] + tags: + - health + responses: + '200': + description: The sandbox is prepared. + content: + application/json: + schema: + $ref: '#/components/schemas/RunnerReadinessResponse' + '503': + description: The sandbox is not prepared or the process is draining. + content: + application/json: + schema: + $ref: '#/components/schemas/RunnerReadinessResponse' + default: + $ref: '#/components/responses/Problem' + /v1/runs/{run_id}: + parameters: + - name: run_id + in: path + required: true + description: Random UUID chosen by the backend for one logical run. It is the idempotency key of SubmitRun and must not encode a candidate, attempt, or task identifier. + schema: + type: string + format: uuid + put: + operationId: SubmitRun + summary: Start a sandboxed run of one source against its test groups. + description: |- + Idempotent by `run_id`: + + - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; + - the same ID with the same payload answers 200 with the current state of that run, including the finished result, without running it again; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy` with Retry-After; nothing is stored, so the caller retries with the same ID. + + Payloads are compared by a SHA-256 fingerprint of the decoded request. + The runner keeps runs only in memory for a bounded time after they + finish; an ID that was forgotten or lost in a restart starts a new run. + Requests above the configured body limit (8 MiB by default) answer 413 + `payload_too_large`. Semantic rules that the schema cannot express answer + 400 `validation_failed`: group IDs are unique in a run, test IDs are + unique in a group, the number of tests multiplied by + `limits.time_limit_ms` does not exceed 300000, a `numbers` checker has a + positive tolerance, a `custom` checker has a program, and no other kind + carries tolerances or a program. + tags: + - runs + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RunRequest' + responses: + '200': + description: A run with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: '#/components/schemas/RunStatus' + '202': + description: The run was accepted and started. + content: + application/json: + schema: + $ref: '#/components/schemas/RunStatus' + '503': + $ref: '#/components/responses/RunnerBusy' + default: + $ref: '#/components/responses/Problem' + get: + operationId: GetRun + summary: Read the state and, when finished, the per-group result of a run. + description: Answers 404 `not_found` for an ID the runner does not hold, including a run forgotten after its retention time or lost in a restart. + tags: + - runs + responses: + '200': + description: The current state of the run. + content: + application/json: + schema: + $ref: '#/components/schemas/RunStatus' + default: + $ref: '#/components/responses/Problem' +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: 'Shared random service token sent as `Authorization: Bearer ` over TLS. The runner compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.' + responses: + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + validation_failed: + summary: Request fields do not match the contract + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + errors: + - in: body + pointer: /groups/1/id + code: invalid + message: The value does not match the contract. + idempotency_key_reused: + summary: The run ID was used with a different payload + value: + type: urn:lincodex:problem:idempotency_key_reused + title: Run ID reused with a different payload + status: 422 + code: idempotency_key_reused + detail: A run with this ID exists with a different payload. + RunnerBusy: + description: Every sandbox slot is busy or the runner is draining; code runner_busy. Nothing was stored. Retry with the same run ID after Retry-After. + headers: + Retry-After: + description: Number of seconds to wait before retrying the request. + required: true + schema: + type: integer + format: int32 + minimum: 0 + maximum: 3600 + example: 2 + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + runner_busy: + summary: No free sandbox slot + value: + type: urn:lincodex:problem:runner_busy + title: Runner busy + status: 503 + code: runner_busy + detail: Every sandbox slot is busy. Retry later with the same run ID. + schemas: + ProblemCode: + type: string + description: |- + Stable error code of the runner API. 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 semantic rule of SubmitRun; `errors` points at the fields. + - unauthenticated (401): the bearer token is missing or wrong. + - not_found (404): the route or the run does not exist. + - method_not_allowed (405): the route does not support the method. + - 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 run ID was already used with a different payload. + - internal (500): unexpected server error. + - runner_busy (503): every sandbox slot is busy or the runner is draining; see Retry-After. + + The Problem shape is the api/core shape; only this enum is specific to the runner. + enum: + - validation_failed + - unauthenticated + - not_found + - method_not_allowed + - payload_too_large + - unsupported_media_type + - idempotency_key_reused + - internal + - runner_busy + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: '#/components/schemas/ProblemFieldLocation' + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/limits/time_limit_ms`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/run_id`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. This is the runner copy of the public api/core Problem schema; keep both copies identical except for descriptions and the ProblemCode enum. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: '#/components/schemas/ProblemCode' + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier of the call when the caller propagated one; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons for validation_failed. Other codes omit it. + items: + $ref: '#/components/schemas/ProblemFieldError' + RunnerHealthResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ok + RunnerReadinessResponse: + type: object + additionalProperties: false + required: + - status + properties: + status: + type: string + enum: + - ready + - not_ready + RunState: + type: string + description: '`running` until every group was evaluated or the run failed; `finished` when `result` is final.' + enum: + - running + - finished + RunOutcome: + type: string + description: |- + Outcome of a test, a group, a compile step, or a whole run. + + - accepted: the program exited with status 0 within every limit and the checker accepted the output. + - wrong_answer: the program exited with status 0 within every limit, but the checker rejected the output. + - compile_error: the source was rejected before any test ran (for Python, a syntax error). + - time_limit_exceeded: the CPU time limit or the wall-clock limit stopped the program. + - memory_limit_exceeded: the cgroup memory limit stopped the program. + - output_limit_exceeded: the program wrote more standard output than the limit. + - runtime_error: the program exited with a non-zero status, was killed by a signal, or reached the process limit. + - infrastructure_failure: the runner could not evaluate the source; the outcome says nothing about the program, and the caller may retry with a new run ID. + + A run's outcome is compile_error or infrastructure_failure when that happened, otherwise the outcome of the first failed test in request order, otherwise accepted. A group's outcome is the outcome of its first failed test, otherwise accepted. + enum: + - accepted + - wrong_answer + - compile_error + - time_limit_exceeded + - memory_limit_exceeded + - output_limit_exceeded + - runtime_error + - infrastructure_failure + CompileResult: + type: object + additionalProperties: false + required: + - outcome + properties: + outcome: + $ref: '#/components/schemas/RunOutcome' + diagnostic: + type: string + maxLength: 4096 + description: Compiler or syntax checker message for compile_error, truncated to the limit. It can quote the source, never test data. + TestKey: + type: string + minLength: 1 + maxLength: 32 + pattern: ^[a-z0-9][a-z0-9_-]{0,31}$ + description: Opaque label chosen by the backend, for example `public` or `hidden-1`. It is not a database identifier. + TestVisibility: + type: string + description: '`public` tests may be shown to the person who wrote the source; their results may carry a diagnostic excerpt. `hidden` results never carry program output or diagnostics.' + enum: + - public + - hidden + TerminationLimit: + type: string + description: 'The limit that stopped a test: CPU time, wall-clock time, memory, standard output, or the number of processes and threads.' + enum: + - cpu_time + - wall_time + - memory + - output + - processes + TestResult: + type: object + additionalProperties: false + required: + - id + - outcome + - time_ms + - wall_time_ms + - memory_kb + properties: + id: + $ref: '#/components/schemas/TestKey' + outcome: + $ref: '#/components/schemas/RunOutcome' + time_ms: + type: integer + format: int64 + minimum: 0 + description: CPU time of every process of the test. + wall_time_ms: + type: integer + format: int64 + minimum: 0 + memory_kb: + type: integer + format: int64 + minimum: 0 + description: 'Peak memory of the test in KiB: the cgroup high-water mark of every process of the test, including the sandbox supervisor process and file cache charged to the test.' + exit_code: + type: integer + format: int32 + description: Exit status when the program exited normally. + signal: + type: integer + format: int32 + minimum: 1 + maximum: 64 + description: Signal number when the program was killed by a signal. + limit: + $ref: '#/components/schemas/TerminationLimit' + diagnostic: + type: string + maxLength: 2048 + description: Truncated standard error of a failed public test. Hidden tests never carry it. + GroupResult: + type: object + additionalProperties: false + required: + - id + - visibility + - outcome + - passed_tests + - total_tests + - tests + properties: + id: + $ref: '#/components/schemas/TestKey' + visibility: + $ref: '#/components/schemas/TestVisibility' + outcome: + $ref: '#/components/schemas/RunOutcome' + passed_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + total_tests: + type: integer + format: int32 + minimum: 0 + maximum: 50 + max_time_ms: + type: integer + format: int64 + minimum: 0 + description: Largest CPU time of an evaluated test of the group. + max_memory_kb: + type: integer + format: int64 + minimum: 0 + description: Largest peak memory of an evaluated test of the group. + tests: + type: array + maxItems: 50 + description: Results of the evaluated tests in order. Tests after the first failed one are not run and not listed. + items: + $ref: '#/components/schemas/TestResult' + RunResult: + type: object + additionalProperties: false + required: + - outcome + - groups + - duration_ms + properties: + outcome: + $ref: '#/components/schemas/RunOutcome' + compile: + $ref: '#/components/schemas/CompileResult' + groups: + type: array + maxItems: 4 + description: One result per requested group in request order. After compile_error or infrastructure_failure every group has that outcome and no tests. + items: + $ref: '#/components/schemas/GroupResult' + duration_ms: + type: integer + format: int64 + minimum: 0 + description: Wall-clock time of the whole run in the runner. + RunStatus: + type: object + additionalProperties: false + required: + - run_id + - state + properties: + run_id: + type: string + format: uuid + state: + $ref: '#/components/schemas/RunState' + result: + $ref: '#/components/schemas/RunResult' + RunLanguage: + type: string + description: Language and runtime of the source. `python3` runs the Python 3 interpreter of the runner image with isolated mode and no bytecode writes; a syntax check runs first and fails with compile_error. `go` compiles one `package main` file with the Go toolchain of the runner image against a prebuilt standard library (no modules, no cgo, no network) in a separate compile phase with its own limits; a compile or link error is compile_error and no test runs. + enum: + - python3 + - go + RunLimits: + type: object + description: Limits applied to every test of the run. + additionalProperties: false + required: + - time_limit_ms + - memory_limit_mb + - output_limit_kb + properties: + time_limit_ms: + type: integer + format: int32 + minimum: 100 + maximum: 10000 + description: CPU time per test, including interpreter startup, summed over every process of the test. The wall-clock limit is twice this value plus a fixed startup allowance. + memory_limit_mb: + type: integer + format: int32 + minimum: 32 + maximum: 512 + description: Memory of the test's processes in MiB, enforced by a cgroup v2 memory limit without swap. The limit also leaves a small fixed allowance for the sandbox supervisor process. + output_limit_kb: + type: integer + format: int32 + minimum: 1 + maximum: 1024 + description: Standard output per test in KiB. The test is stopped as soon as it writes more. + CheckerKind: + type: string + description: |- + - exact: both texts are equal after replacing CRLF with LF, removing trailing spaces and tabs at the end of each line, and removing trailing empty lines. + - tokens: both texts split on ASCII whitespace give the same sequence of tokens. + - numbers: like tokens, but two finite numeric tokens are equal when their difference is within abs_tolerance or within rel_tolerance times the expected value; other tokens must be equal. + - custom: the checker program of the task family decides in the sandbox. + enum: + - exact + - tokens + - numbers + - custom + CheckerProgram: + type: object + description: 'Checker program of the task family. It runs in the sandbox with the same isolation as the solution and fixed limits of its own (5 s CPU, 256 MiB). Its arguments are the paths of three read-only files: the test input, the expected output, and the actual output. Exit status 0 accepts, 1 rejects, and anything else, a signal, or a limit is a checker failure, which makes the run infrastructure_failure. Its own output is discarded and never returned.' + additionalProperties: false + required: + - language + - source + properties: + language: + $ref: '#/components/schemas/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 + Checker: + type: object + description: How the standard output of a test is compared with `expected_output`. `numbers` requires `abs_tolerance`, `rel_tolerance`, or both; `custom` requires `program`. Other kinds take no parameter. New kinds add a `kind` value and their own optional parameters. + additionalProperties: false + required: + - kind + properties: + kind: + $ref: '#/components/schemas/CheckerKind' + abs_tolerance: + type: number + format: double + minimum: 0 + maximum: 1000000000 + description: Largest accepted absolute difference of two numeric tokens. + rel_tolerance: + type: number + format: double + minimum: 0 + maximum: 1 + description: Largest accepted difference of two numeric tokens relative to the expected value. + program: + $ref: '#/components/schemas/CheckerProgram' + TestCase: + type: object + additionalProperties: false + required: + - id + - input + - expected_output + properties: + id: + $ref: '#/components/schemas/TestKey' + input: + type: string + maxLength: 262144 + description: UTF-8 text written to the standard input of the program. + expected_output: + type: string + maxLength: 262144 + description: UTF-8 text the checker compares with the standard output. + TestGroup: + type: object + additionalProperties: false + required: + - id + - visibility + - checker + - tests + properties: + id: + $ref: '#/components/schemas/TestKey' + visibility: + $ref: '#/components/schemas/TestVisibility' + checker: + $ref: '#/components/schemas/Checker' + tests: + type: array + minItems: 1 + maxItems: 50 + description: Tests in evaluation order. Test IDs are unique in a group. A group stops at its first failed test. + items: + $ref: '#/components/schemas/TestCase' + RunRequest: + type: object + description: One source and its test groups. The request has no field for a candidate, account, attempt, task, or company; the backend maps a run ID to its own records. + additionalProperties: false + required: + - language + - source + - limits + - groups + properties: + language: + $ref: '#/components/schemas/RunLanguage' + source: + type: string + minLength: 1 + maxLength: 65536 + description: Complete program text in UTF-8. The runner writes it to a read-only file inside the sandbox and never logs it. + limits: + $ref: '#/components/schemas/RunLimits' + groups: + type: array + minItems: 1 + maxItems: 4 + description: Test groups in evaluation order, for example one public group and three hidden groups. Group IDs are unique in a run. + items: + $ref: '#/components/schemas/TestGroup' diff --git a/api/runner/openapi.yml b/api/runner/openapi.yml new file mode 100644 index 0000000..6d05863 --- /dev/null +++ b/api/runner/openapi.yml @@ -0,0 +1,49 @@ +openapi: 3.2.0 +info: + title: Lincodex Code Runner API + version: 0.1.0 + description: |- + Internal API of the own code runner. Only the Go backend calls it; it is + never exposed to browsers or to the public network. + + Transport and authentication: the runner listens on a private network + interface of its dedicated host and serves HTTPS (TLS 1.3). Every + operation except the health routes requires `Authorization: Bearer + `; the token is a shared random secret of at least 32 characters + that comes from the deployment secret store, never from this repository. + A missing or wrong token answers 401 `unauthenticated`. Plain HTTP exists + only behind an explicit development switch of the local Compose file. + + Data minimization: a run carries only the language, the source code, the + limits, and the test groups. It has no candidate, account, attempt, or + task identifiers, names, or contacts. The run ID is a random UUID chosen + by the backend for idempotency; the runner keeps it only in memory. + + Runs are asynchronous. SubmitRun accepts a run when a sandbox slot is free + and answers immediately; the caller polls GetRun until `state` is + `finished`. The runner does not queue runs: when every slot is busy it + answers 503 `runner_busy`, and the backend keeps the queue. +servers: + - url: / +security: + - bearerAuth: [] +paths: + /healthz: + $ref: ./routes/healthz.yml + /readyz: + $ref: ./routes/readyz.yml + /v1/runs/{run_id}: + $ref: ./routes/runs.yml +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + description: >- + Shared random service token sent as `Authorization: Bearer ` + over TLS. The runner compares it in constant time and never logs it. + Rotation replaces the secret on both sides; there are no per-user + tokens. + responses: + Problem: + $ref: ./components/responses.yml#/Problem diff --git a/api/runner/routes/healthz.yml b/api/runner/routes/healthz.yml new file mode 100644 index 0000000..7ad5685 --- /dev/null +++ b/api/runner/routes/healthz.yml @@ -0,0 +1,15 @@ +get: + operationId: GetRunnerHealthz + summary: Check whether the runner process is responding. + security: [] + tags: + - health + responses: + "200": + description: The runner process is responding. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunnerHealthResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/runner/routes/readyz.yml b/api/runner/routes/readyz.yml new file mode 100644 index 0000000..931d4ec --- /dev/null +++ b/api/runner/routes/readyz.yml @@ -0,0 +1,25 @@ +get: + operationId: GetRunnerReadyz + summary: Check whether the sandbox is prepared to accept runs. + description: >- + Ready means that the cgroup hierarchy, the work directory, and the sandbox + binary were prepared at startup and the process is not draining. A busy + runner is still ready; busy is reported by SubmitRun. + security: [] + tags: + - health + responses: + "200": + description: The sandbox is prepared. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunnerReadinessResponse + "503": + description: The sandbox is not prepared or the process is draining. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunnerReadinessResponse + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/runner/routes/runs.yml b/api/runner/routes/runs.yml new file mode 100644 index 0000000..ba28cda --- /dev/null +++ b/api/runner/routes/runs.yml @@ -0,0 +1,74 @@ +parameters: + - name: run_id + in: path + required: true + description: >- + Random UUID chosen by the backend for one logical run. It is the + idempotency key of SubmitRun and must not encode a candidate, attempt, + or task identifier. + schema: + type: string + format: uuid +put: + operationId: SubmitRun + summary: Start a sandboxed run of one source against its test groups. + description: |- + Idempotent by `run_id`: + + - a new ID with a free sandbox slot starts the run and answers 202 with `state: running`; + - the same ID with the same payload answers 200 with the current state of that run, including the finished result, without running it again; + - the same ID with a different payload answers 422 `idempotency_key_reused` and changes nothing; + - a new ID while every slot is busy, or while the runner is draining, answers 503 `runner_busy` with Retry-After; nothing is stored, so the caller retries with the same ID. + + Payloads are compared by a SHA-256 fingerprint of the decoded request. + The runner keeps runs only in memory for a bounded time after they + finish; an ID that was forgotten or lost in a restart starts a new run. + Requests above the configured body limit (8 MiB by default) answer 413 + `payload_too_large`. Semantic rules that the schema cannot express answer + 400 `validation_failed`: group IDs are unique in a run, test IDs are + unique in a group, the number of tests multiplied by + `limits.time_limit_ms` does not exceed 300000, a `numbers` checker has a + positive tolerance, a `custom` checker has a program, and no other kind + carries tolerances or a program. + tags: + - runs + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunRequest + responses: + "200": + description: A run with this ID and the same payload already exists. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunStatus + "202": + description: The run was accepted and started. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunStatus + "503": + $ref: ../components/responses.yml#/RunnerBusy + default: + $ref: ../components/responses.yml#/Problem +get: + operationId: GetRun + summary: Read the state and, when finished, the per-group result of a run. + description: >- + Answers 404 `not_found` for an ID the runner does not hold, including a + run forgotten after its retention time or lost in a restart. + tags: + - runs + responses: + "200": + description: The current state of the run. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/RunStatus + default: + $ref: ../components/responses.yml#/Problem diff --git a/api/testdata/openapi-3.2.0.yml b/api/testdata/openapi-3.2.0.yml index eb54a12..b00f460 100644 --- a/api/testdata/openapi-3.2.0.yml +++ b/api/testdata/openapi-3.2.0.yml @@ -2,6 +2,12 @@ openapi: 3.2.0 info: title: OpenAPI 3.2 compatibility fixture version: 0.1.0 + description: >- + Exercises the OpenAPI 3.2 subset and the api/core conventions (problem + details, cursor pagination, Idempotency-Key, If-Match, and ETag) through + the pinned generators. The operations are test fixtures, not product + endpoints. Component definitions shared with api/core are copies that must + stay identical to the api/core bundle. servers: - url: / paths: @@ -25,6 +31,8 @@ paths: application/json: schema: $ref: "#/components/schemas/NullablePayload" + default: + $ref: "#/components/responses/Problem" additionalOperations: PURGE: operationId: PurgeProbe @@ -33,6 +41,90 @@ paths: responses: "204": description: The compatibility fixture operation completed. + default: + $ref: "#/components/responses/Problem" + /probe/items: + get: + operationId: ListProbeItems + summary: Exercise bounded cursor pagination. + security: [] + parameters: + - $ref: "#/components/parameters/PageLimit" + - $ref: "#/components/parameters/PageCursor" + responses: + "200": + description: One page of fixture items. + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItemPage" + default: + $ref: "#/components/responses/Problem" + post: + operationId: CreateProbeItem + summary: Exercise an idempotent mutating command. + security: [] + parameters: + - $ref: "#/components/parameters/IdempotencyKey" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItemInput" + responses: + "201": + description: The fixture item was created or the stored response was replayed. + headers: + ETag: + $ref: "#/components/headers/ETag" + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItem" + "409": + $ref: "#/components/responses/IdempotencyInProgress" + "422": + $ref: "#/components/responses/UnprocessableContent" + default: + $ref: "#/components/responses/Problem" + /probe/items/{item_id}: + patch: + operationId: UpdateProbeItem + summary: Exercise optimistic concurrency with If-Match and ETag. + description: This operation requires If-Match; without it the fixture handler answers 428 precondition_required. + security: [] + parameters: + - name: item_id + in: path + required: true + schema: + type: string + format: uuid + - $ref: "#/components/parameters/IdempotencyKey" + - $ref: "#/components/parameters/IfMatch" + requestBody: + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItemInput" + responses: + "200": + description: The fixture item was updated. + headers: + ETag: + $ref: "#/components/headers/ETag" + content: + application/json: + schema: + $ref: "#/components/schemas/ProbeItem" + "412": + $ref: "#/components/responses/PreconditionFailed" + "428": + $ref: "#/components/responses/PreconditionRequired" + default: + $ref: "#/components/responses/Problem" components: schemas: NullablePayload: @@ -45,3 +137,302 @@ components: type: - string - "null" + ProbeItemInput: + type: object + additionalProperties: false + required: + - name + properties: + name: + type: string + minLength: 1 + maxLength: 100 + ProbeItem: + type: object + additionalProperties: false + required: + - id + - name + - updated_at + properties: + id: + type: string + format: uuid + name: + type: string + minLength: 1 + maxLength: 100 + updated_at: + $ref: "#/components/schemas/Timestamp" + ProbeItemPage: + type: object + additionalProperties: false + required: + - items + - page + properties: + items: + type: array + maxItems: 100 + items: + $ref: "#/components/schemas/ProbeItem" + page: + $ref: "#/components/schemas/PageInfo" + Problem: + type: object + description: Problem details (RFC 9457) returned with the application/problem+json media type for every error response. `code` is the stable, machine-readable reason; clients branch on it rather than on `title`, `detail`, or the HTTP status alone. The body never contains internal error text, stack traces, SQL, file paths, credentials, contact data, or echoed request values. + additionalProperties: false + required: + - type + - title + - status + - code + properties: + type: + type: string + format: uri-reference + maxLength: 256 + description: URI that identifies the problem type. It has the form `urn:lincodex:problem:` and is an identifier, not a link to dereference. + title: + type: string + minLength: 1 + maxLength: 200 + description: Short, fixed English summary of the problem type. It does not change between occurrences. + status: + type: integer + format: int32 + minimum: 400 + maximum: 599 + description: HTTP status code generated by the origin server. + code: + $ref: "#/components/schemas/ProblemCode" + detail: + type: string + maxLength: 1000 + description: Safe English explanation of this occurrence. It never contains internal error text or request values. + instance: + type: string + format: uri-reference + maxLength: 2048 + description: URI reference that identifies this occurrence, when one exists. + trace_id: + type: string + minLength: 1 + maxLength: 128 + pattern: ^[A-Za-z0-9._-]+$ + description: Request identifier, equal to the X-Request-ID response header. Quote it when reporting the problem; it is not a secret. + errors: + type: array + maxItems: 100 + description: Field-level reasons. validation_failed always carries them; state_conflict may carry one as a disambiguator when one code covers several conflicts (for example consent_required and limit_reached). Other codes omit it. A problem writer must not strip errors from a non-validation response. + items: + $ref: "#/components/schemas/ProblemFieldError" + ProblemCode: + type: string + description: |- + Stable public error code. Adding a code is a contract change; renaming or removing one is a breaking change. Clients must handle an unknown code by its HTTP status. + + - validation_failed (400): parameters or body do not match the contract, or a body violates a domain rule such as salary_from <= salary_to; `errors` points at the fields. + - 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, or an `expected_version` field in the request body, does not match the current version; nothing was changed. + - 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. + - service_unavailable (503): the service cannot serve the request now, for example while a model loads; retry later. + 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 + - service_unavailable + ProblemFieldError: + type: object + description: One reason why a request field or parameter is invalid. + additionalProperties: false + required: + - in + - pointer + - code + - message + properties: + in: + $ref: "#/components/schemas/ProblemFieldLocation" + pointer: + type: string + maxLength: 1024 + pattern: ^(/([^~/]|~[01])*)*$ + description: JSON Pointer (RFC 6901). For `body` it points into the request body document, for example `/salary_from`; an empty string means the whole body. For a parameter it is `/` followed by the parameter name, for example `/limit` or `/Idempotency-Key`. + code: + type: string + minLength: 1 + maxLength: 64 + pattern: ^[a-z][a-z0-9_]*$ + description: Stable field reason. Current values are `required` (missing value) and `invalid` (malformed value or a value outside the schema), and, on a state_conflict, `consent_required` (the operation needs a consent that is not active) and `limit_reached` (a per-account bound is reached). Clients must tolerate new values. + message: + type: string + minLength: 1 + maxLength: 500 + description: Fixed English message that never echoes the submitted value. + ProblemFieldLocation: + type: string + description: Part of the request that contains the invalid field. + enum: + - body + - query + - path + - header + - cookie + Timestamp: + type: string + format: date-time + description: UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema. + examples: + - "2026-10-05T09:30:00Z" + PageInfo: + type: object + description: Cursor pagination state of a list response. Lists are ordered by a stable server-defined key. To read the next page, repeat the request with the same filters and `cursor` set to `next_cursor`. + additionalProperties: false + required: + - has_more + - next_cursor + properties: + has_more: + type: boolean + description: Whether another page follows this one. + next_cursor: + type: + - string + - "null" + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + description: Opaque cursor of the next page, or null on the last page. Clients must not parse, build, or store it beyond the current listing. + parameters: + IdempotencyKey: + name: Idempotency-Key + in: header + required: true + description: + "Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value is sent without quotes. The server scopes the key by caller and operation and fingerprints the request by method, path, and body. + + + Stored for 24 hours after the first request and replayed with the same status, headers, and body: the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404 not_found or 409 state_conflict. A replay does not repeat the side effect. + + + Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428 precondition_required (nothing changed; read the resource again and retry), 422 idempotency_key_reused, 429, and every 5xx. + + + Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused before any other key check; a running request with the same fingerprint returns 409 idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that does the server check If-Match, so a retry of a completed change replays its outcome instead of failing on the version it has just changed. After 24 hours the key may be accepted as new." + schema: + type: string + minLength: 1 + maxLength: 255 + pattern: ^[A-Za-z0-9._:-]+$ + example: 5f0c6a8e-3b0e-4c47-9f4c-2a8f9e5d7c11 + IfMatch: + name: If-Match + in: header + required: false + description: + "Strong entity tag of the resource version the client last read, copied from the ETag response header. An operation that changes a versioned resource says in its own description that it requires If-Match. + + + On such an operation, a missing If-Match returns 428 precondition_required. An If-Match that does not equal the current ETag returns 412 version_conflict and changes nothing; read the resource again before retrying. Only one strong entity tag is accepted; weak tags, lists, and `*` fail validation with 400. The parameter is optional in the schema so that a missing header reaches the application, which answers 428." + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + PageLimit: + name: limit + in: query + required: false + description: Maximum number of items in the page. The server may return fewer items even when more remain; use `page.has_more` to detect the end. + schema: + type: integer + format: int32 + minimum: 1 + maximum: 100 + default: 20 + PageCursor: + name: cursor + in: query + required: false + description: Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the first page. A malformed or foreign cursor returns 400 with code validation_failed. + schema: + type: string + minLength: 1 + maxLength: 512 + pattern: ^[A-Za-z0-9_-]+$ + headers: + ETag: + description: Strong entity tag of the returned resource version. Send it back in If-Match to change this version. + required: true + schema: + type: string + minLength: 3 + maxLength: 130 + pattern: ^"[A-Za-z0-9._~-]{1,128}"$ + example: '"v7"' + responses: + IdempotencyInProgress: + description: A request with the same Idempotency-Key and the same fingerprint is still being processed; code idempotency_in_progress. Retry after the original request completes. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + UnprocessableContent: + description: The Idempotency-Key was already used with a different request within 24 hours; code idempotency_key_reused. Nothing was changed. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + PreconditionFailed: + description: If-Match does not match the current resource version; code version_conflict. Nothing was changed. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + PreconditionRequired: + description: The operation requires If-Match; code precondition_required. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" + Problem: + description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode. + content: + application/problem+json: + schema: + $ref: "#/components/schemas/Problem" diff --git a/backend/.golangci.yml b/backend/.golangci.yml index fe2e022..cfda3fd 100644 --- a/backend/.golangci.yml +++ b/backend/.golangci.yml @@ -13,6 +13,7 @@ linters: - bodyclose - contextcheck - copyloopvar + - depguard - durationcheck - embeddedstructfieldcheck - errname @@ -20,6 +21,7 @@ linters: - exhaustive - exptostd - fatcontext + - forbidigo - gocheckcompilerdirectives - gochecknoinits - gochecksumtype @@ -58,6 +60,25 @@ linters: - zerologlint settings: + depguard: + rules: + # The local Resend stand-in exists for tests of the delivery layer + # only; no production package may import it. + resend-fixture-tests-only: + list-mode: lax + files: + - "!$test" + # This command is compiled only by the local E2E mail image. + - "!**/cmd/mail-fixture/main.go" + deny: + - pkg: lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture + desc: the Resend fixture is for tests only + forbidigo: + forbid: + # It accepts a loopback endpoint instead of the fixed Resend one, so + # only tests may call it (see the exclusion for test files below). + - pattern: ^resend\.NewLoopbackSender$ + msg: resend.NewLoopbackSender is for tests only; production uses resend.NewSender gocyclo: min-complexity: 15 govet: @@ -104,6 +125,8 @@ linters: paths: - internal/adapter/primary/http/api/ - internal/adapter/secondary/ml/api/ + - internal/adapter/secondary/code_runner/api/ + - internal/adapter/secondary/lab_provisioner/api/ - internal/adapter/secondary/postgres/sqlc/ - internal/bootstrap/wire_gen\.go$ - (^|/)mocks/ @@ -122,6 +145,9 @@ linters: - gosec - errcheck - dupl + - path: _test\.go + linters: + - forbidigo - path: _test\.go text: net/http/httptest\.NewRequest must not be called linters: @@ -136,6 +162,8 @@ formatters: paths: - internal/adapter/primary/http/api/ - internal/adapter/secondary/ml/api/ + - internal/adapter/secondary/code_runner/api/ + - internal/adapter/secondary/lab_provisioner/api/ - internal/adapter/secondary/postgres/sqlc/ - internal/bootstrap/wire_gen\.go$ - (^|/)mocks/ diff --git a/backend/Dockerfile b/backend/Dockerfile index 581959e..ffcacbb 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,4 +1,13 @@ -FROM golang:1.26.8-alpine AS build +# Base images are build arguments so that make -C deploy release-build can pin +# each one to the digest it resolved; the defaults keep the agreed tags. +ARG GO_IMAGE=golang:1.26.9-alpine +ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot + +FROM ${GO_IMAGE} AS build + +# Never download another Go toolchain: a go.mod that asks for a newer Go +# fails the build instead of silently replacing 1.26.9. +ENV GOTOOLCHAIN=local WORKDIR /src/backend COPY go.mod go.sum ./ @@ -7,7 +16,7 @@ RUN go mod download COPY . ./ RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app -FROM gcr.io/distroless/static-debian12:nonroot +FROM ${RUNTIME_IMAGE} WORKDIR / COPY --from=build /out/app /app diff --git a/backend/Dockerfile.demo-seed b/backend/Dockerfile.demo-seed new file mode 100644 index 0000000..56760d2 --- /dev/null +++ b/backend/Dockerfile.demo-seed @@ -0,0 +1,26 @@ +# Image of the demo seed operator command. Only the isolated demo stand +# overlay (deploy/docker/docker-compose.demo.yml) builds it; the backend and +# release images never contain the command. +ARG GO_IMAGE=golang:1.26.9-alpine +ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot + +FROM ${GO_IMAGE} AS build + +ENV GOTOOLCHAIN=local + +WORKDIR /src/backend +COPY go.mod go.sum ./ +RUN go mod download + +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/demo-seed ./cmd/demo-seed + +FROM ${RUNTIME_IMAGE} + +LABEL org.opencontainers.image.title="Lincodex demo seed" \ + org.opencontainers.image.description="Operator command that seeds synthetic data on an isolated demo stand" + +WORKDIR / +COPY --from=build /out/demo-seed /demo-seed +USER nonroot:nonroot +ENTRYPOINT ["/demo-seed"] diff --git a/backend/Dockerfile.e2e b/backend/Dockerfile.e2e new file mode 100644 index 0000000..5d7efa1 --- /dev/null +++ b/backend/Dockerfile.e2e @@ -0,0 +1,34 @@ +# This image is for local browser E2E only. The release path uses +# Dockerfile and never enables the e2e Go build tag. +ARG GO_IMAGE=golang:1.26.9-alpine +ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot + +FROM ${GO_IMAGE} AS build + +ENV GOTOOLCHAIN=local + +WORKDIR /src/backend +COPY go.mod go.sum ./ +RUN go mod download + +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/app ./cmd/app +RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/consent-fixture ./cmd/consent-fixture +RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/company-fixture ./cmd/company-fixture +RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/questionnaire-fixture ./cmd/questionnaire-fixture +RUN CGO_ENABLED=0 GOOS=linux go build -buildvcs=false -trimpath -ldflags="-s -w" -o /out/assessment-category-attest ./cmd/assessment-category-attest + +FROM ${RUNTIME_IMAGE} + +LABEL org.opencontainers.image.title="Lincodex local E2E backend" \ + org.opencontainers.image.description="Local registration E2E image with a fixed internal mail fixture endpoint" + +WORKDIR / +COPY --from=build /out/app /app +COPY --from=build /out/consent-fixture /consent-fixture +COPY --from=build /out/company-fixture /company-fixture +COPY --from=build /out/questionnaire-fixture /questionnaire-fixture +COPY --from=build /out/assessment-category-attest /assessment-category-attest +EXPOSE 8080 9090 +USER nonroot:nonroot +ENTRYPOINT ["/app"] diff --git a/backend/Dockerfile.mail-fixture b/backend/Dockerfile.mail-fixture new file mode 100644 index 0000000..389f198 --- /dev/null +++ b/backend/Dockerfile.mail-fixture @@ -0,0 +1,26 @@ +# The fixture is built separately from the application and only by the local +# E2E Compose overlay. +ARG GO_IMAGE=golang:1.26.9-alpine +ARG RUNTIME_IMAGE=gcr.io/distroless/static-debian12:nonroot + +FROM ${GO_IMAGE} AS build + +ENV GOTOOLCHAIN=local + +WORKDIR /src/backend +COPY go.mod go.sum ./ +RUN go mod download + +COPY . ./ +RUN CGO_ENABLED=0 GOOS=linux go build -tags=e2e -buildvcs=false -trimpath -ldflags="-s -w" -o /out/mail-fixture ./cmd/mail-fixture + +FROM ${RUNTIME_IMAGE} + +LABEL org.opencontainers.image.title="Lincodex local E2E mail fixture" \ + org.opencontainers.image.description="Bounded in-memory Resend-compatible receiver for local browser tests" + +WORKDIR / +COPY --from=build /out/mail-fixture /mail-fixture +EXPOSE 8025 +USER nonroot:nonroot +ENTRYPOINT ["/mail-fixture"] diff --git a/backend/Makefile b/backend/Makefile index 4429afc..6062f1c 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -23,6 +23,79 @@ build: ## Build the application binary run: ## Run the application with the current environment $(GO) run ./cmd/app +.PHONY: migrate-status migrate-up migrate-down-one +migrate-status: ## Show embedded migration status for the database in DATABASE_URL + $(GO) run ./cmd/migrate status + +migrate-up: ## Apply pending embedded migrations to the database in DATABASE_URL + $(GO) run ./cmd/migrate up + +migrate-down-one: ## Roll back the latest applied migration in the database in DATABASE_URL + $(GO) run ./cmd/migrate down-one + +.PHONY: mail-retry mail-retry-build +mail-retry: ## Inspect or authorize an audited unknown mail retry (set ARGS) + $(GO) run ./cmd/mail-retry $(ARGS) + +mail-retry-build: ## Build the local mail retry operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/mail-retry ./cmd/mail-retry + +.PHONY: assessment-review assessment-review-build +assessment-review: ## Print the audited manual-review band of an attempt (set ARGS) + $(GO) run ./cmd/assessment-review $(ARGS) + +assessment-review-build: ## Build the local assessment review operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/assessment-review ./cmd/assessment-review + +.PHONY: bank-coverage bank-coverage-check +bank-coverage: ## Report planned assessment bank coverage from bundle files (set ARGS) + $(GO) run ./cmd/assessment-bank-coverage $(ARGS) + +bank-coverage-check: ## Fail when planned family keys, reviewer declarations, or implementation paths are missing + $(GO) run ./cmd/assessment-bank-coverage --strict $(ARGS) + +.PHONY: assessment-leak-trace assessment-leak-trace-build +assessment-leak-trace: ## Find the attempt behind a leaked task text; the search is audited (set ARGS) + $(GO) run ./cmd/assessment-leak-trace $(ARGS) + +assessment-leak-trace-build: ## Build the local leak trace operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/assessment-leak-trace ./cmd/assessment-leak-trace + +.PHONY: assessment-category-attest assessment-category-attest-build +assessment-category-attest: ## Attest a category opening for synthetic demonstration categories (set ARGS) + $(GO) run ./cmd/assessment-category-attest $(ARGS) + +assessment-category-attest-build: ## Build the local category attestation operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/assessment-category-attest ./cmd/assessment-category-attest + +.PHONY: policy-publish policy-publish-build +policy-publish: ## Add the demo matching or semantic matching section to the product policy (set ARGS) + $(GO) run ./cmd/policy-publish $(ARGS) + +policy-publish-build: ## Build the local policy publication operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/policy-publish ./cmd/policy-publish + +.PHONY: semantic-backfill semantic-backfill-build +semantic-backfill: ## Schedule vector jobs for existing candidates and needs (set ARGS) + $(GO) run ./cmd/semantic-backfill $(ARGS) + +semantic-backfill-build: ## Build the local semantic backfill operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/semantic-backfill ./cmd/semantic-backfill + +.PHONY: demo-seed demo-seed-build +demo-seed: ## Seed, check, or count the isolated demo stand; needs DEMO_MODE=isolated (set ARGS) + $(GO) run ./cmd/demo-seed $(ARGS) + +demo-seed-build: ## Build the local demo seed operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/demo-seed ./cmd/demo-seed + .PHONY: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download @@ -48,6 +121,8 @@ generate gen: ## Regenerate API, SQL, and dependency-injection code in dependenc @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi $(MAKE) --no-print-directory gen-openapi API_PREPARED=1 $(MAKE) --no-print-directory gen-ml API_PREPARED=1 + $(MAKE) --no-print-directory gen-code-runner API_PREPARED=1 + $(MAKE) --no-print-directory gen-lab-provisioner API_PREPARED=1 $(MAKE) --no-print-directory gen-sqlc $(MAKE) --no-print-directory gen-wire $(MAKE) --no-print-directory mocks @@ -62,8 +137,18 @@ gen-ml: ## Generate the internal ML service client @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi $(GO_TOOL) ogen -config codegen/ogen-ml.yml --target internal/adapter/secondary/ml/api --package api --clean ../api/ml/openapi.bundle.yml +.PHONY: gen-code-runner +gen-code-runner: ## Generate the internal code runner client + @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi + $(GO_TOOL) ogen -config codegen/ogen-code-runner.yml --target internal/adapter/secondary/code_runner/api --package api --clean ../api/runner/openapi.bundle.yml + +.PHONY: gen-lab-provisioner +gen-lab-provisioner: ## Generate the internal lab provisioner client + @if [ "$(API_PREPARED)" != "1" ]; then $(MAKE) -C "$(API_DIR)" bundle; fi + $(GO_TOOL) ogen -config codegen/ogen-labd.yml --target internal/adapter/secondary/lab_provisioner/api --package api --clean ../api/labd/openapi.bundle.yml + .PHONY: gen-sqlc -gen-sqlc: ## Generate PostgreSQL health query code +gen-sqlc: ## Generate PostgreSQL query code from migrations and queries $(GO_TOOL) sqlc generate -f codegen/sqlc.yml .PHONY: gen-wire @@ -79,7 +164,7 @@ mocks: ## Generate configured mocks when interfaces are selected fi .PHONY: check-ogen-compat -check-ogen-compat: ## Verify OpenAPI 3.2 nullable values, validation, and additionalOperations +check-ogen-compat: ## Verify OpenAPI 3.2 features and API error, pagination, and retry conventions with ogen @set -euo pipefail; mkdir -p bin; temporary_dir=$$(mktemp -d "$(CURDIR)/bin/ogen-compat.XXXXXX"); trap 'rm -rf "$$temporary_dir"' EXIT; \ $(GO_TOOL) ogen -config codegen/ogen-compat.yml --target "$$temporary_dir" --package compat --clean ../api/testdata/openapi-3.2.0.yml; \ cp testdata/ogen_compat_test.go "$$temporary_dir/ogen_compat_test.go"; \ @@ -146,6 +231,15 @@ test-scripts: ## Check integration shard coverage, selection, and failure propag test-int-compile: ## Compile infrastructure integration tests without starting containers $(GO) test -tags=integration -run '^$$' ./integration_test/... +.PHONY: test-code-runner-live +test-code-runner-live: ## Run fixed harmless programs on a real runner (set CODE_RUNNER_URL, CODE_RUNNER_TOKEN, CODE_RUNNER_CA_FILE) + @if [ -z "$$CODE_RUNNER_URL" ] || [ -z "$$CODE_RUNNER_TOKEN" ] || [ -z "$$CODE_RUNNER_CA_FILE" ]; then \ + echo 'set CODE_RUNNER_URL, CODE_RUNNER_TOKEN, and CODE_RUNNER_CA_FILE (optionally CODE_RUNNER_SERVER_NAME)' >&2; exit 2; \ + fi + CODE_RUNNER_LIVE_URL="$$CODE_RUNNER_URL" CODE_RUNNER_LIVE_TOKEN="$$CODE_RUNNER_TOKEN" \ + CODE_RUNNER_LIVE_CA_FILE="$$CODE_RUNNER_CA_FILE" CODE_RUNNER_LIVE_SERVER_NAME="$$CODE_RUNNER_SERVER_NAME" \ + $(GO) test -count=1 -v -run '^TestLiveRunner' ./internal/adapter/secondary/code_runner/ + .PHONY: verify check check: ## Run local formatting, build, unit, and lint checks in order $(MAKE) --no-print-directory fmt-check diff --git a/backend/README.en.md b/backend/README.en.md index 2a1a87d..c8e2218 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -1,15 +1,55 @@ -# Go backend +# Backend [Русский](README.md) | English -The main service uses Go, chi, and Clean Architecture. It currently provides health checks and PostgreSQL, Redis, and SeaweedFS adapters; hiring workflows are still to be implemented. +The core Go service handles accounts, profiles, skill assessments, organization needs, search, invitations, and notifications. chi and the generated ogen server serve HTTP. Background handlers run within the application process. -- `cmd/app/` is the entry point; `internal/bootstrap/` wires dependencies and manages startup. -- `internal/` contains domain types, use cases, ports, and primary/secondary adapters. -- `config/` holds application settings; `pkg/` is for shared helper packages. -- `db/` and `codegen/` hold SQL queries, migrations, and generator configuration. -- `integration_test/` checks real dependencies through Testcontainers. +## Structure -From the repository root, `make -C backend check` runs the main checks and `make -C backend test-int` runs integration tests with Docker. Use `make -C backend help` for all commands. +| Directory | Purpose | +| --- | --- | +| `cmd/app/` | Entry point calling `bootstrap.Run` | +| `config/` | Environment loading and validation | +| `internal/bootstrap/` | Dependency assembly, startup, and shutdown | +| `internal/domain/` | Domain types and rules | +| `internal/usecase/` | Application workflows | +| `internal/port/` | Inbound and outbound interfaces | +| `internal/adapter/primary/http/` | Router, middleware, `v1/` handlers, ogen output in `api/` | +| `internal/adapter/secondary/` | PostgreSQL, Redis, SeaweedFS, Kafka, mail, and external services | +| `internal/worker/` | Outbox, events, jobs, and mail delivery | +| `db/` | Migrations and SQL queries | +| `codegen/` | ogen, sqlc, wire, and mockery | +| `pkg/` | Reusable libraries | +| `integration_test/` | Tests against real infrastructure | -See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md). +## Development + +[go.mod](go.mod) declares the Go version. From the repository root: + +```sh +make -C backend deps +make -C backend build +make -C backend test-fast +make -C backend check +``` + +Use `make generate` to regenerate all dependent components. Backend targets include `gen-openapi`, `gen-ml`, `gen-code-runner`, `gen-lab-provisioner`, `gen-sqlc`, `gen-wire`, and `mocks`. Do not edit generated files by hand. + +`make -C backend run` reads process environment variables and does not load `.env` automatically. Use [Compose](../docs/en/DEPLOYMENT.md) to run with its dependencies. Migrations run before HTTP starts by default; separate commands are `migrate-status`, `migrate-up`, and `migrate-down-one`. + +## Operational routes + +- `GET /healthz`: the process is alive. +- `GET /readyz`: PostgreSQL, Redis, and SeaweedFS are available; Kafka is not checked here. +- `GET /api/v1/healthz`: health through the public API. +- `GET /metrics`: a separate `METRICS_ADDR` listener, default `:9090`. + +Mail supports `disabled` and `resend`. SMTP configuration exists, but selecting `smtp` currently stops startup because its transport is not implemented. ML and runner require separately configured services. The labd client is generated but not yet wired into bootstrap. + +## Checks + +`make -C backend test` runs unit tests with the race detector. `test-int` uses Testcontainers and requires Docker; `test-int-compile` only compiles integration tests. [TESTING.md](../docs/en/TESTING.md) covers shards and the shared bootstrap. + +List commands with `make -C backend help`. See [DEVELOPMENT.md](../docs/en/DEVELOPMENT.md) and [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md) for layer boundaries and change rules. + +Report planned assessment bank coverage with `make -C backend bank-coverage`. The command matches valid families from JSON bundles against the manifest and checks for Go/Python paths for Backend families. Report mode shows incomplete coverage without failing; `make -C backend bank-coverage-check` enables strict checks. File presence does not confirm implementation equivalence, reviewer independence, or calibration; those remain separate external checks. diff --git a/backend/README.md b/backend/README.md index 96a0592..4da00df 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,15 +1,55 @@ -# Go backend +# Backend Русский | [English](README.en.md) -Основной сервис на Go и chi с Clean Architecture. Сейчас реализованы проверки состояния, адаптеры PostgreSQL, Redis и SeaweedFS; продуктовые сценарии найма еще предстоит добавить. +Основной Go-сервис: аккаунты, профили, оценка навыков, потребности организаций, поиск, приглашения и уведомления. HTTP обслуживают chi и сгенерированный ogen-сервер. Фоновые обработчики запускаются вместе с приложением. -- `cmd/app/` - точка входа; `internal/bootstrap/` собирает зависимости и управляет запуском. -- `internal/` - доменные типы, use case, порты и primary/secondary адаптеры. -- `config/` - настройки приложения; `pkg/` - общие вспомогательные пакеты. -- `db/` и `codegen/` - SQL-запросы, миграции и настройки генераторов. -- `integration_test/` - проверки с настоящими зависимостями через Testcontainers. +## Структура -Из корня: `make -C backend check` запускает основные проверки, `make -C backend test-int` - интеграционные тесты с Docker. Все команды доступны через `make -C backend help`. +| Каталог | Назначение | +| --- | --- | +| `cmd/app/` | Точка входа, вызывает `bootstrap.Run` | +| `config/` | Чтение и проверка окружения | +| `internal/bootstrap/` | Сборка зависимостей, запуск и остановка | +| `internal/domain/` | Предметные типы и правила | +| `internal/usecase/` | Прикладные сценарии | +| `internal/port/` | Входные и выходные интерфейсы | +| `internal/adapter/primary/http/` | Роутер, middleware, обработчики `v1/`, ogen-код `api/` | +| `internal/adapter/secondary/` | PostgreSQL, Redis, SeaweedFS, Kafka, почта и внешние сервисы | +| `internal/worker/` | Outbox, события, задания и отправка писем | +| `db/` | Миграции и SQL-запросы | +| `codegen/` | ogen, sqlc, wire и mockery | +| `pkg/` | Повторно используемые библиотеки | +| `integration_test/` | Проверки с реальной инфраструктурой | -Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md). +## Работа + +Нужная версия Go указана в [go.mod](go.mod). Из корня репозитория: + +```sh +make -C backend deps +make -C backend build +make -C backend test-fast +make -C backend check +``` + +Для генерации всех зависимых частей используйте `make generate`. Отдельные цели backend: `gen-openapi`, `gen-ml`, `gen-code-runner`, `gen-lab-provisioner`, `gen-sqlc`, `gen-wire`, `mocks`. Сгенерированные файлы вручную не исправляются. + +`make -C backend run` читает переменные процесса и не загружает `.env` автоматически. Для запуска со всеми зависимостями используйте [Compose](../docs/ru/DEPLOYMENT.md). Миграции по умолчанию применяются до открытия HTTP-порта; отдельные команды - `migrate-status`, `migrate-up`, `migrate-down-one`. + +## Служебные маршруты + +- `GET /healthz` - процесс работает. +- `GET /readyz` - доступны PostgreSQL, Redis и SeaweedFS; Kafka в эту проверку не входит. +- `GET /api/v1/healthz` - health через публичный API. +- `GET /metrics` - отдельный listener `METRICS_ADDR`, по умолчанию `:9090`. + +Почта поддерживает `disabled` и `resend`. Конфигурация SMTP предусмотрена, но выбор `smtp` пока останавливает запуск: транспорта нет. ML и runner требуют отдельных настроенных сервисов. Клиент labd сгенерирован, но в bootstrap еще не подключен. + +## Проверки + +`make -C backend test` запускает unit-тесты с race detector. `test-int` запускает Testcontainers и требует Docker; `test-int-compile` только компилирует интеграционные тесты. Шарды и общий bootstrap описаны в [TESTING.md](../docs/ru/TESTING.md). + +Полный список команд: `make -C backend help`. Границы слоев и правила изменений: [DEVELOPMENT.md](../docs/ru/DEVELOPMENT.md) и [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md). + +Отчет о покрытии запланированных семейств банка оценки: `make -C backend bank-coverage`. Команда сопоставляет валидные семейства из JSON-бандлов с манифестом и проверяет наличие путей Go/Python для backend-семейств. Отчетный режим показывает неполноту без ошибки; `make -C backend bank-coverage-check` включает строгую проверку. Наличие файла не подтверждает эквивалентность реализации, независимость рецензента или калибровку; эти требования остаются отдельными внешними проверками. diff --git a/backend/cmd/assessment-bank-coverage/main.go b/backend/cmd/assessment-bank-coverage/main.go new file mode 100644 index 0000000..b7b8720 --- /dev/null +++ b/backend/cmd/assessment-bank-coverage/main.go @@ -0,0 +1,16 @@ +// Command assessment-bank-coverage reports assessment bank inventory coverage. +package main + +import ( + "fmt" + "os" + + "lincodex/backend/internal/adapter/primary/cli/bankcoverage" +) + +func main() { + if err := bankcoverage.Run(os.Args[1:], os.Stdout, os.Stderr); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "assessment-bank-coverage: %v\n", err) + os.Exit(1) + } +} diff --git a/backend/cmd/assessment-category-attest/main.go b/backend/cmd/assessment-category-attest/main.go new file mode 100644 index 0000000..0a459d9 --- /dev/null +++ b/backend/cmd/assessment-category-attest/main.go @@ -0,0 +1,28 @@ +// Command assessment-category-attest attests the current opening of one +// assessment category as a source of synthetic demonstration categories. It +// is for isolated synthetic stands only and changes nothing else. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + + "lincodex/backend/internal/adapter/primary/cli/categoryattest" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := categoryattest.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "assessment-category-attest: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/assessment-leak-trace/main.go b/backend/cmd/assessment-leak-trace/main.go new file mode 100644 index 0000000..5c6fed3 --- /dev/null +++ b/backend/cmd/assessment-leak-trace/main.go @@ -0,0 +1,29 @@ +// Command assessment-leak-trace searches for the assessment attempt behind a +// leaked task text. It reads text, never an image: a screenshot must be read +// by an OCR tool first. It records every search in an audit table and changes +// nothing else. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + + "lincodex/backend/internal/adapter/primary/cli/leaktrace" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := leaktrace.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdin, os.Stdout); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "assessment-leak-trace: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/assessment-review/main.go b/backend/cmd/assessment-review/main.go new file mode 100644 index 0000000..ef019e2 --- /dev/null +++ b/backend/cmd/assessment-review/main.go @@ -0,0 +1,28 @@ +// Command assessment-review prints the stored manual-review band of one +// assessment attempt for an operator and records the read in an audit table. +// It changes nothing else. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + + "lincodex/backend/internal/adapter/primary/cli/assessmentreview" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := assessmentreview.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "assessment-review: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/company-fixture/main.go b/backend/cmd/company-fixture/main.go new file mode 100644 index 0000000..c0f25fd --- /dev/null +++ b/backend/cmd/company-fixture/main.go @@ -0,0 +1,296 @@ +//go:build e2e + +package main + +import ( + "context" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io" + "log" + "log/slog" + "mime" + "net/http" + "os" + "strings" + "sync/atomic" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/port/outbound" +) + +const ( + fixtureEnabledName = "E2E_COMPANY_FIXTURE" + fixtureAuthEnvName = "E2E_COMPANY_FIXTURE_TOKEN" + fixtureListenAddr = ":8081" + fixtureEndpoint = "/company/memberships/revoke" + fixtureHealthPath = "/healthcheck" + maxRequestBody = 1024 + maxFixtureRequests = 32 + requestTimeout = 5 * time.Second + readHeaderTimeout = 3 * time.Second + readTimeout = 5 * time.Second + writeTimeout = 5 * time.Second + idleTimeout = 15 * time.Second +) + +type membershipRevoker func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error + +type fixtureHandler struct { + token string + revoke membershipRevoker + notices *noticeFixture + requests atomic.Uint32 +} + +type revokeMembershipRequest struct { + OrganizationID string `json:"organization_id"` + UserID string `json:"user_id"` + SuccessorUserID string `json:"successor_user_id"` +} + +func main() { + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + if err := checkHealth(); err != nil { + os.Exit(1) + } + return + } + if err := serve(); err != nil { + _, _ = io.WriteString(os.Stderr, "Company fixture could not start.\n") + os.Exit(1) + } +} + +func serve() error { + if os.Getenv(fixtureEnabledName) != "1" { + return errors.New("company fixture requires the isolated e2e environment") + } + token := os.Getenv(fixtureAuthEnvName) + if !hasFixtureTokenStrength(token) { + return errors.New("company fixture token must contain at least 32 random bytes") + } + databaseURL := os.Getenv("DATABASE_URL") + if databaseURL == "" { + return errors.New("company fixture database is not configured") + } + + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + pool, err := postgres.NewSizedPool(ctx, databaseURL, 4) + if err != nil { + return errors.New("company fixture could not open its database") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("company fixture database is unavailable") + } + + server := &http.Server{ + Addr: fixtureListenAddr, + Handler: &fixtureHandler{ + token: token, + revoke: func(ctx context.Context, organizationID, userID, successorUserID uuid.UUID) error { + return postgres.RevokeCompanyFixtureMembership(ctx, pool, organizationID, userID, successorUserID) + }, + notices: newNoticeFixture( + postgres.NewTransactor(pool), + postgres.NewEventConsumerStore(pool, requestTimeout), + func(ctx context.Context, recipientID, organizationID uuid.UUID) error { + return postgres.CheckNotificationFixtureScope(ctx, pool, recipientID, organizationID) + }, + func(ctx context.Context, eventID uuid.UUID) (outbound.ConsumedEvent, error) { + return postgres.NotificationFixtureEvent(ctx, pool, eventID) + }, + func(ctx context.Context, recipientID, organizationID uuid.UUID) error { + return postgres.HideNotificationFixtureOrganization(ctx, pool, recipientID, organizationID) + }, + slog.New(slog.DiscardHandler), + ), + }, + ReadHeaderTimeout: readHeaderTimeout, + ReadTimeout: readTimeout, + WriteTimeout: writeTimeout, + IdleTimeout: idleTimeout, + MaxHeaderBytes: 4096, + ErrorLog: log.New(io.Discard, "", 0), + } + return server.ListenAndServe() +} + +func checkHealth() error { + client := http.Client{Timeout: time.Second} + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8081"+fixtureHealthPath, nil) + if err != nil { + return errors.New("company fixture is not healthy") + } + response, err := client.Do(request) + if err != nil { + return errors.New("company fixture is not healthy") + } + defer func() { _ = response.Body.Close() }() + if response.StatusCode != http.StatusNoContent { + return errors.New("company fixture is not healthy") + } + return nil +} + +func hasFixtureTokenStrength(token string) bool { + if decoded, err := hex.DecodeString(token); err == nil && len(decoded) >= 32 { + return true + } + decoded, err := base64.RawURLEncoding.Strict().DecodeString(token) + return err == nil && len(decoded) >= 32 +} + +func (handler *fixtureHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case fixtureHealthPath: + handler.serveHealthcheck(w, r) + case fixtureEndpoint: + handler.serveMembershipRevocation(w, r) + case noticeEndpoint, noticeReplayEndpoint, noticeHideEndpoint: + handler.serveNotice(w, r) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func (handler *fixtureHandler) serveHealthcheck(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.Header().Set("Allow", http.MethodGet) + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + w.WriteHeader(http.StatusNoContent) +} + +func (handler *fixtureHandler) serveMembershipRevocation(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if handler.requests.Add(1) > maxFixtureRequests { + w.WriteHeader(http.StatusTooManyRequests) + return + } + if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) { + w.WriteHeader(http.StatusUnauthorized) + return + } + if !isJSONRequest(r) { + w.WriteHeader(http.StatusUnsupportedMediaType) + return + } + + request, status := decodeRevokeMembershipRequest(w, r) + if status != 0 { + w.WriteHeader(status) + return + } + if handler.revoke == nil { + w.WriteHeader(http.StatusInternalServerError) + return + } + ctx, cancel := context.WithTimeout(r.Context(), requestTimeout) + defer cancel() + if err := handler.revoke(ctx, request.organizationID, request.userID, request.successorUserID); err != nil { + w.WriteHeader(statusForFixtureError(err)) + return + } + w.WriteHeader(http.StatusNoContent) +} + +type parsedRevokeMembershipRequest struct { + organizationID uuid.UUID + userID uuid.UUID + successorUserID uuid.UUID +} + +func decodeRevokeMembershipRequest(w http.ResponseWriter, r *http.Request) (parsedRevokeMembershipRequest, int) { + request, status := decodeRevokeRequest(w, r) + if status != 0 { + return parsedRevokeMembershipRequest{}, status + } + organizationID, err := uuid.Parse(request.OrganizationID) + if err != nil || organizationID == uuid.Nil { + return parsedRevokeMembershipRequest{}, http.StatusBadRequest + } + userID, err := uuid.Parse(request.UserID) + if err != nil || userID == uuid.Nil { + return parsedRevokeMembershipRequest{}, http.StatusBadRequest + } + successorUserID, err := uuid.Parse(request.SuccessorUserID) + if err != nil || successorUserID == uuid.Nil || successorUserID == userID { + return parsedRevokeMembershipRequest{}, http.StatusBadRequest + } + return parsedRevokeMembershipRequest{ + organizationID: organizationID, + userID: userID, + successorUserID: successorUserID, + }, 0 +} + +func isJSONRequest(r *http.Request) bool { + mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + return err == nil && strings.EqualFold(mediaType, "application/json") +} + +func decodeRevokeRequest(w http.ResponseWriter, r *http.Request) (revokeMembershipRequest, int) { + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody)) + decoder.DisallowUnknownFields() + var request revokeMembershipRequest + if err := decoder.Decode(&request); err != nil { + return revokeMembershipRequest{}, statusForDecodeError(err) + } + var trailing any + if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) { + return revokeMembershipRequest{}, statusForDecodeError(err) + } + if request.OrganizationID == "" || request.UserID == "" { + return revokeMembershipRequest{}, http.StatusBadRequest + } + return request, 0 +} + +func statusForDecodeError(err error) int { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + return http.StatusRequestEntityTooLarge + } + return http.StatusBadRequest +} + +func statusForFixtureError(err error) int { + switch { + case errors.Is(err, postgres.ErrCompanyFixtureScope), + errors.Is(err, outbound.ErrUserNotFound), + errors.Is(err, outbound.ErrMembershipNotFound), + errors.Is(err, outbound.ErrOrganizationNotFound): + return http.StatusNotFound + case errors.Is(err, outbound.ErrTransactionConflict): + return http.StatusConflict + default: + return http.StatusInternalServerError + } +} + +func hasFixtureBearerToken(header, token string) bool { + prefix, supplied, ok := strings.Cut(header, " ") + if !ok || prefix != "Bearer" || supplied == "" { + return false + } + expectedDigest := sha256.Sum256([]byte(token)) + suppliedDigest := sha256.Sum256([]byte(supplied)) + return subtle.ConstantTimeCompare(expectedDigest[:], suppliedDigest[:]) == 1 +} diff --git a/backend/cmd/company-fixture/main_test.go b/backend/cmd/company-fixture/main_test.go new file mode 100644 index 0000000..6fcf440 --- /dev/null +++ b/backend/cmd/company-fixture/main_test.go @@ -0,0 +1,177 @@ +//go:build e2e + +package main + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/hex" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/port/outbound" +) + +func TestFixtureHandlerRevokesOnlyWithConfiguredBearer(t *testing.T) { + organizationID := uuid.New() + userID := uuid.New() + successorUserID := uuid.New() + called := false + handler := &fixtureHandler{ + token: strings.Repeat("ab", 32), + revoke: func(_ context.Context, gotOrganizationID, gotUserID, gotSuccessorUserID uuid.UUID) error { + called = true + if gotOrganizationID != organizationID || gotUserID != userID || gotSuccessorUserID != successorUserID { + t.Fatalf("revoke IDs = %s/%s/%s, want %s/%s/%s", gotOrganizationID, gotUserID, gotSuccessorUserID, organizationID, userID, successorUserID) + } + return nil + }, + } + body := `{"organization_id":"` + organizationID.String() + `","user_id":"` + userID.String() + `","successor_user_id":"` + successorUserID.String() + `"}` + + unauthorized := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json") + if unauthorized.Code != http.StatusUnauthorized || called { + t.Fatalf("unauthorized response = %d, revoke called = %t", unauthorized.Code, called) + } + if len(unauthorized.Body.Bytes()) != 0 { + t.Fatalf("unauthorized response exposed a body: %q", unauthorized.Body.String()) + } + + response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json; charset=utf-8") + if response.Code != http.StatusNoContent || !called { + t.Fatalf("authorized response = %d, revoke called = %t", response.Code, called) + } + if len(response.Body.Bytes()) != 0 { + t.Fatalf("success response exposed a body: %q", response.Body.String()) + } +} + +func TestFixtureHandlerRejectsInvalidRequestsWithoutCallingRevoker(t *testing.T) { + called := false + handler := &fixtureHandler{ + token: strings.Repeat("ab", 32), + revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error { + called = true + return nil + }, + } + validBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}` + userID := uuid.NewString() + sameUserBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + userID + `","successor_user_id":"` + userID + `"}` + largeBody := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `","padding":"` + strings.Repeat("x", maxRequestBody) + `"}` + tests := []struct { + name string + method string + path string + body string + authority string + contentType string + wantStatus int + }{ + {name: "unknown path", method: http.MethodPost, path: "/other", wantStatus: http.StatusNotFound}, + {name: "wrong method", method: http.MethodGet, path: fixtureEndpoint, wantStatus: http.StatusMethodNotAllowed}, + {name: "wrong content type", method: http.MethodPost, path: fixtureEndpoint, body: validBody, authority: "Bearer " + handler.token, contentType: "text/plain", wantStatus: http.StatusUnsupportedMediaType}, + {name: "unknown field", method: http.MethodPost, path: fixtureEndpoint, body: strings.TrimSuffix(validBody, "}") + `,"extra":"value"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, + {name: "malformed UUID", method: http.MethodPost, path: fixtureEndpoint, body: `{"organization_id":"bad","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, + {name: "same owner and successor", method: http.MethodPost, path: fixtureEndpoint, body: sameUserBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, + {name: "trailing JSON", method: http.MethodPost, path: fixtureEndpoint, body: validBody + `{}`, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusBadRequest}, + {name: "oversized body", method: http.MethodPost, path: fixtureEndpoint, body: largeBody, authority: "Bearer " + handler.token, contentType: "application/json", wantStatus: http.StatusRequestEntityTooLarge}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + response := fixtureRequest(handler, test.method, test.path, test.body, test.authority, test.contentType) + if response.Code != test.wantStatus { + t.Fatalf("response status = %d, want %d", response.Code, test.wantStatus) + } + if len(response.Body.Bytes()) != 0 { + t.Fatalf("response exposed a body: %q", response.Body.String()) + } + }) + } + if called { + t.Fatal("revoker was called for an invalid request") + } +} + +func TestFixtureHandlerBoundsControlRequests(t *testing.T) { + handler := &fixtureHandler{token: strings.Repeat("ab", 32)} + for range maxFixtureRequests { + response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json") + if response.Code != http.StatusUnauthorized { + t.Fatalf("request before limit status = %d, want %d", response.Code, http.StatusUnauthorized) + } + } + response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, "", "", "application/json") + if response.Code != http.StatusTooManyRequests { + t.Fatalf("request after limit status = %d, want %d", response.Code, http.StatusTooManyRequests) + } +} + +func TestFixtureHandlerMapsStorageErrorsToEmptyResponses(t *testing.T) { + handler := &fixtureHandler{ + token: strings.Repeat("ab", 32), + revoke: func(context.Context, uuid.UUID, uuid.UUID, uuid.UUID) error { + return errors.Join(errors.New("private database detail"), outbound.ErrTransactionConflict) + }, + } + body := `{"organization_id":"` + uuid.NewString() + `","user_id":"` + uuid.NewString() + `","successor_user_id":"` + uuid.NewString() + `"}` + response := fixtureRequest(handler, http.MethodPost, fixtureEndpoint, body, "Bearer "+handler.token, "application/json") + if response.Code != http.StatusConflict { + t.Fatalf("response status = %d, want %d", response.Code, http.StatusConflict) + } + if len(response.Body.Bytes()) != 0 { + t.Fatalf("response exposed internal error: %q", response.Body.String()) + } + if got := statusForFixtureError(postgres.ErrCompanyFixtureScope); got != http.StatusNotFound { + t.Fatalf("fixture scope status = %d, want %d", got, http.StatusNotFound) + } +} + +func TestFixtureHealthIsMinimal(t *testing.T) { + handler := &fixtureHandler{} + response := fixtureRequest(handler, http.MethodGet, fixtureHealthPath, "", "", "") + if response.Code != http.StatusNoContent || len(response.Body.Bytes()) != 0 { + t.Fatalf("health response = %d %q, want empty %d", response.Code, response.Body.String(), http.StatusNoContent) + } + wrongMethod := fixtureRequest(handler, http.MethodPost, fixtureHealthPath, "", "", "") + if wrongMethod.Code != http.StatusMethodNotAllowed || wrongMethod.Header().Get("Allow") != http.MethodGet { + t.Fatalf("health wrong-method response = %d, Allow = %q", wrongMethod.Code, wrongMethod.Header().Get("Allow")) + } +} + +func TestFixtureTokenStrengthAcceptsOnlyAtLeast32Bytes(t *testing.T) { + bytes32 := bytes.Repeat([]byte{0x4a}, 32) + for name, token := range map[string]string{ + "hex": hex.EncodeToString(bytes32), + "base64": base64.RawURLEncoding.EncodeToString(bytes32), + "too short": hex.EncodeToString(bytes32[:31]), + "invalid": "not-a-token", + } { + t.Run(name, func(t *testing.T) { + want := name == "hex" || name == "base64" + if got := hasFixtureTokenStrength(token); got != want { + t.Fatalf("hasFixtureTokenStrength() = %t, want %t", got, want) + } + }) + } +} + +func fixtureRequest(handler http.Handler, method, path, body, authorization, contentType string) *httptest.ResponseRecorder { + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if authorization != "" { + request.Header.Set("Authorization", authorization) + } + if contentType != "" { + request.Header.Set("Content-Type", contentType) + } + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + return response +} diff --git a/backend/cmd/company-fixture/notifications.go b/backend/cmd/company-fixture/notifications.go new file mode 100644 index 0000000..126d89c --- /dev/null +++ b/backend/cmd/company-fixture/notifications.go @@ -0,0 +1,232 @@ +//go:build e2e + +package main + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +// The notification endpoints share the process, the bearer token, and the +// isolated database of the membership fixture. They let the browser suite +// put a synthetic event into the real outbox, so the relay, the event bus, +// and the inbox consumer deliver it, and then replay it the way an +// at-least-once bus does. +const ( + noticeEndpoint = "/notifications/synthetic" + noticeReplayEndpoint = "/notifications/synthetic/replay" + noticeHideEndpoint = "/notifications/synthetic/hide-organization" + renamedInboxConsumer = "notification_inbox_replayed" + noticeConsumerTimeout = requestTimeout +) + +// noticeFixture is the data access of the notification endpoints. +type noticeFixture struct { + // publish appends one synthetic event to the outbox and returns its ID. + publish func(ctx context.Context, recipientID, organizationID uuid.UUID) (uuid.UUID, error) + // replay delivers the event again to the inbox consumer and to a consumer + // of another name. It reports whether each delivery stored a new row + // claim, which is false for a duplicate. + replay func(ctx context.Context, eventID uuid.UUID) (noticeReplayResult, error) + // hide records that the recipient hides the organization. + hide func(ctx context.Context, recipientID, organizationID uuid.UUID) error +} + +type noticeReplayResult struct { + // PrimaryApplied is true when the inbox consumer had not processed the + // event yet. The browser suite waits for the real consumer first, so it + // expects false. + PrimaryApplied bool `json:"primary_applied"` + // RenamedApplied is true for a consumer without a marker for the event; + // the inbox key must still keep one row. + RenamedApplied bool `json:"renamed_applied"` +} + +type noticeRequest struct { + RecipientUserID string `json:"recipient_user_id"` + OrganizationID string `json:"organization_id"` + EventID string `json:"event_id"` +} + +func newNoticeFixture( + transactor outbound.Transactor, + store outbound.EventConsumerStore, + check func(ctx context.Context, recipientID, organizationID uuid.UUID) error, + readEvent func(ctx context.Context, eventID uuid.UUID) (outbound.ConsumedEvent, error), + hide func(ctx context.Context, recipientID, organizationID uuid.UUID) error, + logger *slog.Logger, +) *noticeFixture { + inbox := notification.NewInboxHandler(logger, true) + return ¬iceFixture{ + publish: func(ctx context.Context, recipientID, organizationID uuid.UUID) (uuid.UUID, error) { + if err := check(ctx, recipientID, organizationID); err != nil { + return uuid.Nil, err + } + payload, err := notification.SyntheticNoticeEventPayload(recipientID, organizationID) + if err != nil { + return uuid.Nil, err + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1, + AggregateType: notification.SyntheticNoticeAggregateType, AggregateID: uuid.New(), + AggregateVersion: notification.SyntheticNoticeAggregateVersion, Payload: payload, + }) + if err != nil { + return uuid.Nil, err + } + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, event) + }) + return event.EventID(), err + }, + replay: func(ctx context.Context, eventID uuid.UUID) (noticeReplayResult, error) { + event, err := readEvent(ctx, eventID) + if err != nil { + return noticeReplayResult{}, err + } + apply := func(ctx context.Context, unit outbound.UnitOfWork) error { + return inbox.Handle(ctx, unit, event) + } + var result noticeReplayResult + if result.PrimaryApplied, err = store.ApplyOnce(ctx, notification.InboxConsumerName, event.EventID, apply); err != nil { + return noticeReplayResult{}, err + } + if result.RenamedApplied, err = store.ApplyOnce(ctx, renamedInboxConsumer, event.EventID, apply); err != nil { + return noticeReplayResult{}, err + } + return result, nil + }, + hide: hide, + } +} + +func (handler *fixtureHandler) serveNotice(w http.ResponseWriter, r *http.Request) { + if handler.notices == nil { + w.WriteHeader(http.StatusNotFound) + return + } + if !handler.admit(w, r) { + return + } + request, status := decodeNoticeRequest(w, r) + if status != 0 { + w.WriteHeader(status) + return + } + ctx, cancel := context.WithTimeout(r.Context(), noticeConsumerTimeout) + defer cancel() + switch r.URL.Path { + case noticeEndpoint: + recipientID, organizationID, ok := noticeIdentities(request) + if !ok { + w.WriteHeader(http.StatusBadRequest) + return + } + eventID, err := handler.notices.publish(ctx, recipientID, organizationID) + if err != nil { + w.WriteHeader(statusForNoticeError(err)) + return + } + writeNoticeJSON(w, http.StatusCreated, map[string]string{"event_id": eventID.String()}) + case noticeReplayEndpoint: + eventID, err := uuid.Parse(request.EventID) + if err != nil || eventID == uuid.Nil { + w.WriteHeader(http.StatusBadRequest) + return + } + result, err := handler.notices.replay(ctx, eventID) + if err != nil { + w.WriteHeader(statusForNoticeError(err)) + return + } + writeNoticeJSON(w, http.StatusOK, result) + case noticeHideEndpoint: + recipientID, organizationID, ok := noticeIdentities(request) + if !ok { + w.WriteHeader(http.StatusBadRequest) + return + } + if err := handler.notices.hide(ctx, recipientID, organizationID); err != nil { + w.WriteHeader(statusForNoticeError(err)) + return + } + w.WriteHeader(http.StatusNoContent) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +// admit applies the checks that every mutating fixture request passes: the +// method, the request budget, the bearer token, and the JSON media type. +func (handler *fixtureHandler) admit(w http.ResponseWriter, r *http.Request) bool { + if r.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + w.WriteHeader(http.StatusMethodNotAllowed) + return false + } + if handler.requests.Add(1) > maxFixtureRequests { + w.WriteHeader(http.StatusTooManyRequests) + return false + } + if !hasFixtureBearerToken(r.Header.Get("Authorization"), handler.token) { + w.WriteHeader(http.StatusUnauthorized) + return false + } + if !isJSONRequest(r) { + w.WriteHeader(http.StatusUnsupportedMediaType) + return false + } + return true +} + +func decodeNoticeRequest(w http.ResponseWriter, r *http.Request) (noticeRequest, int) { + decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxRequestBody)) + decoder.DisallowUnknownFields() + var request noticeRequest + if err := decoder.Decode(&request); err != nil { + return noticeRequest{}, statusForDecodeError(err) + } + var trailing any + if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) { + return noticeRequest{}, statusForDecodeError(err) + } + return request, 0 +} + +func noticeIdentities(request noticeRequest) (recipientID, organizationID uuid.UUID, ok bool) { + recipientID, recipientErr := uuid.Parse(request.RecipientUserID) + organizationID, organizationErr := uuid.Parse(request.OrganizationID) + return recipientID, organizationID, recipientErr == nil && organizationErr == nil && + recipientID != uuid.Nil && organizationID != uuid.Nil +} + +func statusForNoticeError(err error) int { + switch { + case errors.Is(err, postgres.ErrCompanyFixtureScope), + errors.Is(err, outbound.ErrUserNotFound), + errors.Is(err, outbound.ErrOrganizationNotFound), + errors.Is(err, outbound.ErrNotificationInboxEntryNotFound): + return http.StatusNotFound + case errors.Is(err, outbound.ErrTransactionConflict): + return http.StatusConflict + default: + return http.StatusInternalServerError + } +} + +func writeNoticeJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(body) +} diff --git a/backend/cmd/company-fixture/notifications_test.go b/backend/cmd/company-fixture/notifications_test.go new file mode 100644 index 0000000..7011c39 --- /dev/null +++ b/backend/cmd/company-fixture/notifications_test.go @@ -0,0 +1,86 @@ +//go:build e2e + +package main + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/port/outbound" +) + +func TestNoticeEndpointsNeedTheBearerAndDecodeStrictly(t *testing.T) { + recipientID, organizationID, eventID := uuid.New(), uuid.New(), uuid.New() + var published, hidden int + handler := &fixtureHandler{ + token: strings.Repeat("ab", 32), + notices: ¬iceFixture{ + publish: func(_ context.Context, gotRecipient, gotOrganization uuid.UUID) (uuid.UUID, error) { + published++ + if gotRecipient != recipientID || gotOrganization != organizationID { + t.Fatalf("publish IDs = %s/%s, want %s/%s", gotRecipient, gotOrganization, recipientID, organizationID) + } + return eventID, nil + }, + replay: func(_ context.Context, got uuid.UUID) (noticeReplayResult, error) { + if got != eventID { + t.Fatalf("replay event = %s, want %s", got, eventID) + } + return noticeReplayResult{RenamedApplied: true}, nil + }, + hide: func(context.Context, uuid.UUID, uuid.UUID) error { + hidden++ + return postgres.ErrCompanyFixtureScope + }, + }, + } + bearer := "Bearer " + handler.token + body := `{"recipient_user_id":"` + recipientID.String() + `","organization_id":"` + organizationID.String() + `"}` + + if response := fixtureRequest(handler, http.MethodPost, noticeEndpoint, body, "Bearer "+strings.Repeat("cd", 32), "application/json"); response.Code != http.StatusUnauthorized || published != 0 { + t.Fatalf("unauthorized publish = %d, published %d", response.Code, published) + } + response := fixtureRequest(handler, http.MethodPost, noticeEndpoint, body, bearer, "application/json") + var created struct { + EventID uuid.UUID `json:"event_id"` + } + if response.Code != http.StatusCreated || json.Unmarshal(response.Body.Bytes(), &created) != nil || created.EventID != eventID { + t.Fatalf("publish = %d %s, want 201 with the event ID", response.Code, response.Body.String()) + } + replay := fixtureRequest(handler, http.MethodPost, noticeReplayEndpoint, `{"event_id":"`+eventID.String()+`"}`, bearer, "application/json") + var result noticeReplayResult + if replay.Code != http.StatusOK || json.Unmarshal(replay.Body.Bytes(), &result) != nil || result.PrimaryApplied || !result.RenamedApplied { + t.Fatalf("replay = %d %s, want 200 with a duplicate for the primary consumer", replay.Code, replay.Body.String()) + } + if hide := fixtureRequest(handler, http.MethodPost, noticeHideEndpoint, body, bearer, "application/json"); hide.Code != http.StatusNotFound || hidden != 1 { + t.Fatalf("hide outside the fixture scope = %d, want 404", hide.Code) + } + for name, test := range map[string]struct { + path, body string + want int + }{ + "unknown field": {noticeEndpoint, `{"recipient_user_id":"` + recipientID.String() + `","organization_id":"` + organizationID.String() + `","email":"x"}`, http.StatusBadRequest}, + "bad recipient": {noticeEndpoint, `{"recipient_user_id":"x","organization_id":"` + organizationID.String() + `"}`, http.StatusBadRequest}, + "nil event": {noticeReplayEndpoint, `{"event_id":"` + uuid.Nil.String() + `"}`, http.StatusBadRequest}, + "trailing content": {noticeEndpoint, body + " {}", http.StatusBadRequest}, + } { + if got := fixtureRequest(handler, http.MethodPost, test.path, test.body, bearer, "application/json"); got.Code != test.want { + t.Errorf("%s = %d, want %d", name, got.Code, test.want) + } + } + if got := fixtureRequest(handler, http.MethodGet, noticeEndpoint, "", bearer, ""); got.Code != http.StatusMethodNotAllowed { + t.Errorf("GET = %d, want 405", got.Code) + } + if statusForNoticeError(outbound.ErrOrganizationNotFound) != http.StatusNotFound { + t.Error("an unknown organization must answer 404") + } + if got := fixtureRequest(&fixtureHandler{token: handler.token}, http.MethodPost, noticeEndpoint, body, bearer, "application/json"); got.Code != http.StatusNotFound { + t.Errorf("a handler without notices = %d, want 404", got.Code) + } +} diff --git a/backend/cmd/consent-fixture/main.go b/backend/cmd/consent-fixture/main.go new file mode 100644 index 0000000..01552dc --- /dev/null +++ b/backend/cmd/consent-fixture/main.go @@ -0,0 +1,403 @@ +//go:build e2e + +package main + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "fmt" + "os" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/argon2id" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" +) + +const ( + fixtureGuardName = "E2E_CONSENT_FIXTURE" + fixtureEmail = "consent-browser@example.test" + fixturePassword = "browser consent fixture 2026" + firstOwnerEmail = "consent-owner-one@example.test" + secondOwnerEmail = "consent-owner-two@example.test" + + // The privacy candidate has its own organizations so that the privacy and + // consent browser suites can run side by side without sharing any state. + privacyEmail = "privacy-browser@example.test" + privacyPassword = "browser privacy fixture 2026" + privacyFirstOwnerMail = "privacy-owner-one@example.test" + privacySecondOwnerMail = "privacy-owner-two@example.test" + fixtureTimeout = 90 * time.Second +) + +func main() { + if err := run(); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + if _, err := fmt.Fprintln(os.Stdout, "Consent browser fixture seeded."); err != nil { + os.Exit(1) + } +} + +func run() error { + if os.Getenv(fixtureGuardName) != "1" { + return errors.New("consent fixture requires the isolated e2e environment") + } + if len(os.Args) != 1 { + return errors.New("consent fixture accepts no arguments") + } + databaseURL := os.Getenv("DATABASE_URL") + if databaseURL == "" { + return errors.New("consent fixture database is not configured") + } + + ctx, cancel := context.WithTimeout(context.Background(), fixtureTimeout) + defer cancel() + + pool, err := postgres.NewSizedPool(ctx, databaseURL, 4) + if err != nil { + return errors.New("consent fixture could not open its database") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("consent fixture database is unavailable") + } + + hasher, err := argon2id.NewHasher(1) + if err != nil { + return errors.New("consent fixture password service is unavailable") + } + now := time.Now().UTC().Truncate(time.Microsecond) + users, err := newFixtureUsers(ctx, hasher, now) + if err != nil { + return errors.New("consent fixture accounts could not be prepared") + } + + transactor := postgres.NewTransactor(pool) + service := consent.NewService(transactor, func() time.Time { return now }) + if err := seedFixture(ctx, transactor, service, users, now); err != nil { + if errors.Is(err, outbound.ErrEmailTaken) { + return errors.New("consent fixture addresses already exist; the database must be fresh") + } + return errors.New("consent fixture could not be seeded") + } + return nil +} + +type fixtureUsers struct { + candidate domain.User + firstOwner domain.User + secondOwner domain.User + + privacyCandidate domain.User + privacyFirstOwner domain.User + privacySecondOwner domain.User +} + +func newFixtureUsers( + ctx context.Context, + hasher *argon2id.Hasher, + registeredAt time.Time, +) (fixtureUsers, error) { + candidate, err := newFixtureUser(ctx, hasher, fixtureEmail, fixturePassword, domain.ScenarioCandidate, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + firstOwner, err := newFixtureOwner(ctx, hasher, firstOwnerEmail, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + secondOwner, err := newFixtureOwner(ctx, hasher, secondOwnerEmail, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + privacyCandidate, err := newFixtureUser(ctx, hasher, privacyEmail, privacyPassword, domain.ScenarioCandidate, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + privacyFirstOwner, err := newFixtureOwner(ctx, hasher, privacyFirstOwnerMail, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + privacySecondOwner, err := newFixtureOwner(ctx, hasher, privacySecondOwnerMail, registeredAt) + if err != nil { + return fixtureUsers{}, err + } + return fixtureUsers{ + candidate: candidate, firstOwner: firstOwner, secondOwner: secondOwner, + privacyCandidate: privacyCandidate, privacyFirstOwner: privacyFirstOwner, privacySecondOwner: privacySecondOwner, + }, nil +} + +func newFixtureOwner( + ctx context.Context, + hasher *argon2id.Hasher, + email string, + registeredAt time.Time, +) (domain.User, error) { + passwordBytes := make([]byte, 24) + if _, err := rand.Read(passwordBytes); err != nil { + return domain.User{}, errors.New("could not generate an isolated owner password") + } + rawPassword := base64.RawURLEncoding.EncodeToString(passwordBytes) + return newFixtureUser(ctx, hasher, email, rawPassword, domain.ScenarioEmployer, registeredAt) +} + +func newFixtureUser( + ctx context.Context, + hasher *argon2id.Hasher, + emailValue string, + passwordValue string, + scenario domain.Scenario, + registeredAt time.Time, +) (domain.User, error) { + email, err := domain.NewEmailAddress(emailValue) + if err != nil { + return domain.User{}, errors.New("fixture account email is invalid") + } + password, err := domain.NewPassword(passwordValue) + if err != nil { + return domain.User{}, errors.New("fixture account password is invalid") + } + passwordHash, err := hasher.Hash(ctx, password) + if err != nil { + return domain.User{}, errors.New("fixture account password could not be hashed") + } + user, err := domain.NewUser(domain.Registration{ + Email: email, + PasswordHash: passwordHash, + Scenario: scenario, + RegisteredAt: registeredAt, + }) + if err != nil { + return domain.User{}, errors.New("fixture account could not be built") + } + return user, nil +} + +func seedFixture( + ctx context.Context, + transactor outbound.Transactor, + service *consent.Service, + users fixtureUsers, + now time.Time, +) error { + return transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + for _, user := range []domain.User{ + users.candidate, users.firstOwner, users.secondOwner, + users.privacyCandidate, users.privacyFirstOwner, users.privacySecondOwner, + } { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + if _, err := unit.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now); err != nil { + return err + } + } + + firstOrganization, err := createOrganization( + ctx, + unit, + users.firstOwner.ID, + "Первая тестовая компания", + now, + ) + if err != nil { + return err + } + secondOrganization, err := createOrganization( + ctx, + unit, + users.secondOwner.ID, + "Вторая тестовая компания", + now, + ) + if err != nil { + return err + } + + c1Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, now) + if err != nil { + return err + } + if _, err := service.GrantAtRegistration( + ctx, + unit, + users.candidate.ID, + users.candidate.RegistrationVersion, + c1Text.Version(), + ); err != nil { + return err + } + + c2Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePublication, now) + if err != nil { + return err + } + if _, err := service.GrantInSettings(ctx, unit, consent.SettingsGrantInput{ + SubjectID: users.candidate.ID, + Purpose: domain.ConsentPurposePublication, + TextVersion: c2Text.Version(), + }); err != nil { + return err + } + + c4Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, now) + if err != nil { + return err + } + if err := grantFixtureContactConsent(ctx, service, unit, users.candidate.ID, firstOrganization, c4Text.Version(), domain.ContactFieldEmail); err != nil { + return err + } + if err := grantFixtureContactConsent(ctx, service, unit, users.candidate.ID, secondOrganization, c4Text.Version(), domain.ContactFieldPhone); err != nil { + return err + } + return seedPrivacyCandidate(ctx, unit, service, users, now) + }) +} + +// seedPrivacyCandidate gives the privacy browser suite a candidate whose +// publication consent is active, with one company that holds a contact consent +// and read the card and one company that only read the card. The reads are +// recorded the way an authorized organization read leaves them, because the +// organization read path needs search results that do not exist yet. +func seedPrivacyCandidate( + ctx context.Context, + unit outbound.UnitOfWork, + service *consent.Service, + users fixtureUsers, + now time.Time, +) error { + firstOrganization, err := createOrganization(ctx, unit, users.privacyFirstOwner.ID, "Приватная компания А", now) + if err != nil { + return err + } + secondOrganization, err := createOrganization(ctx, unit, users.privacySecondOwner.ID, "Приватная компания Б", now) + if err != nil { + return err + } + + c1Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, now) + if err != nil { + return err + } + if _, err := service.GrantAtRegistration( + ctx, unit, users.privacyCandidate.ID, users.privacyCandidate.RegistrationVersion, c1Text.Version(), + ); err != nil { + return err + } + c2Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposePublication, now) + if err != nil { + return err + } + if _, err := service.GrantInSettings(ctx, unit, consent.SettingsGrantInput{ + SubjectID: users.privacyCandidate.ID, + Purpose: domain.ConsentPurposePublication, + TextVersion: c2Text.Version(), + }); err != nil { + return err + } + c4Text, err := unit.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, now) + if err != nil { + return err + } + if err := grantFixtureContactConsent( + ctx, service, unit, users.privacyCandidate.ID, firstOrganization, c4Text.Version(), domain.ContactFieldEmail, + ); err != nil { + return err + } + + reads := []domain.CandidateCardAccessInput{ + { + CandidateID: users.privacyCandidate.ID, OrganizationID: firstOrganization.ID(), ActorID: users.privacyFirstOwner.ID, + Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories}, + OccurredAt: now.Add(-3 * time.Hour), + }, + { + CandidateID: users.privacyCandidate.ID, OrganizationID: firstOrganization.ID(), ActorID: users.privacyFirstOwner.ID, + Kind: domain.CandidateCardAccessContactRead, ContactFields: []domain.ContactField{domain.ContactFieldEmail}, + OccurredAt: now.Add(-2 * time.Hour), + }, + { + CandidateID: users.privacyCandidate.ID, OrganizationID: secondOrganization.ID(), ActorID: users.privacySecondOwner.ID, + Kind: domain.CandidateCardAccessCardViewed, ProjectionFields: []domain.CardField{domain.CardFieldCategories}, + OccurredAt: now.Add(-1 * time.Hour), + }, + } + for _, input := range reads { + access, err := domain.NewCandidateCardAccess(input) + if err != nil { + return err + } + if err := unit.PrivacyView().RecordCandidateCardAccess(ctx, access); err != nil { + return err + } + } + return nil +} + +func createOrganization( + ctx context.Context, + unit outbound.UnitOfWork, + ownerID uuid.UUID, + name string, + now time.Time, +) (domain.Organization, error) { + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: name}) + if err != nil { + return domain.Organization{}, err + } + organization, err := domain.NewOrganization(profile, now) + if err != nil { + return domain.Organization{}, err + } + owner, err := domain.NewOwnerMembership(organization.ID(), ownerID, now) + if err != nil { + return domain.Organization{}, err + } + if err := unit.Organizations().CreateWithOwner(ctx, organization, owner); err != nil { + return domain.Organization{}, err + } + return organization, nil +} + +func grantFixtureContactConsent( + ctx context.Context, + service *consent.Service, + unit outbound.UnitOfWork, + subjectID uuid.UUID, + organization domain.Organization, + textVersion domain.ConsentTextVersion, + field domain.ContactField, +) error { + fields, err := domain.NewContactFieldSet(field) + if err != nil { + return err + } + invitationID, err := uuid.NewV7() + if err != nil { + return err + } + // These synthetic invitation IDs exercise consent history and scoped revocation only. + // They are not evidence of the real invitation acceptance flow. + _, err = service.GrantContact(ctx, unit, consent.ContactGrantInput{ + SubjectID: subjectID, + OrganizationID: organization.ID(), + OrganizationName: organization.Profile().Name(), + Fields: fields, + InvitationID: invitationID, + InvitationTermsVersion: 1, + TextVersion: textVersion, + }) + if err != nil { + return err + } + return nil +} diff --git a/backend/cmd/demo-seed/main.go b/backend/cmd/demo-seed/main.go new file mode 100644 index 0000000..991ba92 --- /dev/null +++ b/backend/cmd/demo-seed/main.go @@ -0,0 +1,29 @@ +// Command demo-seed seeds the synthetic demonstration world of an isolated +// demo stand, checks whether a reset may discard the stand's database, and +// prints an inventory of counts. It requires DEMO_MODE=isolated. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/internal/adapter/primary/cli/demoseed" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := demoseed.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "demo-seed: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/mail-fixture/main.go b/backend/cmd/mail-fixture/main.go new file mode 100644 index 0000000..7158905 --- /dev/null +++ b/backend/cmd/mail-fixture/main.go @@ -0,0 +1,84 @@ +//go:build e2e + +package main + +import ( + "context" + "errors" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" +) + +const listenAddress = ":8025" + +func main() { + if len(os.Args) == 2 && os.Args[1] == "healthcheck" { + if err := healthcheck(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run() error { + fixture := resendfixture.NewService() + server := &http.Server{ + Addr: listenAddress, + Handler: fixture.Handler(), + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 10 * time.Second, + WriteTimeout: 10 * time.Second, + IdleTimeout: 30 * time.Second, + MaxHeaderBytes: 16 << 10, + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + serverErrors := make(chan error, 1) + go func() { + if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + serverErrors <- errors.New("main.run - mail fixture server stopped unexpectedly") + } + }() + + select { + case <-ctx.Done(): + shutdownCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := server.Shutdown(shutdownCtx); err != nil { + return errors.New("main.run - mail fixture shutdown failed") + } + return nil + case err := <-serverErrors: + return err + } +} + +func healthcheck() error { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://127.0.0.1:8025/healthz", nil) + if err != nil { + return errors.New("main.healthcheck - could not build request") + } + response, err := http.DefaultClient.Do(request) + if err != nil { + return errors.New("main.healthcheck - mail fixture is not ready") + } + defer func() { _ = response.Body.Close() }() + if response.StatusCode != http.StatusNoContent { + return errors.New("main.healthcheck - mail fixture is not ready") + } + return nil +} diff --git a/backend/cmd/mail-retry/main.go b/backend/cmd/mail-retry/main.go new file mode 100644 index 0000000..2ce44e6 --- /dev/null +++ b/backend/cmd/mail-retry/main.go @@ -0,0 +1,27 @@ +// Command mail-retry inspects and schedules an audited retry of an unknown +// mail delivery. It never sends mail itself. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + + "lincodex/backend/internal/adapter/primary/cli/mailretry" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := mailretry.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "mail-retry: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/migrate/main.go b/backend/cmd/migrate/main.go new file mode 100644 index 0000000..31a16f6 --- /dev/null +++ b/backend/cmd/migrate/main.go @@ -0,0 +1,116 @@ +// Command migrate applies, inspects, or rolls back the embedded schema +// migrations against DATABASE_URL with the same runner and advisory lock that +// the backend uses at startup. It is intended for local development. +package main + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/config" + "lincodex/backend/db" + "lincodex/backend/internal/adapter/secondary/postgres" +) + +const usage = "usage: migrate status|up|down-one" + +func main() { + if err := run(os.Args[1:], os.Stdout); err != nil { + _, _ = fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string, output io.Writer) (runErr error) { + if len(args) != 1 { + return errors.New("main.run - " + usage) + } + command := args[0] + databaseURL := config.DatabaseURLFromEnv(os.LookupEnv) + if databaseURL == "" { + return errors.New("main.run - DATABASE_URL is not set") + } + migrations, err := db.Migrations() + if err != nil { + return fmt.Errorf("main.run - load migrations: %w", err) + } + migrator, err := postgres.NewMigrator(databaseURL, migrations) + if err != nil { + return fmt.Errorf("main.run - create migrator: %w", err) + } + defer func() { + if err := migrator.Close(); err != nil { + runErr = errors.Join(runErr, fmt.Errorf("main.run - close migrator: %w", err)) + } + }() + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + switch command { + case "status": + return printStatus(ctx, migrator, output) + case "up": + return applyUp(ctx, migrator, output) + case "down-one": + return rollBackOne(ctx, migrator, output) + default: + return errors.New("main.run - " + usage) + } +} + +func printStatus(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + statuses, err := migrator.Status(ctx) + if err != nil { + return fmt.Errorf("main.printStatus - read status: %w", err) + } + for _, status := range statuses { + appliedAt := "pending" + if status.Applied { + appliedAt = status.AppliedAt.UTC().Format(time.RFC3339) + } + if _, err := fmt.Fprintf(output, "%-20s %s\n", appliedAt, status.Name); err != nil { + return fmt.Errorf("main.printStatus - write status: %w", err) + } + } + return nil +} + +func applyUp(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + applied, err := migrator.Up(ctx) + if err != nil { + return fmt.Errorf("main.applyUp - apply migrations: %w", err) + } + for _, migration := range applied { + if _, err := fmt.Fprintf(output, "applied %s (%s)\n", migration.Name, migration.Duration); err != nil { + return fmt.Errorf("main.applyUp - write result: %w", err) + } + } + if _, err := fmt.Fprintf(output, "%d migration(s) applied\n", len(applied)); err != nil { + return fmt.Errorf("main.applyUp - write summary: %w", err) + } + return nil +} + +func rollBackOne(ctx context.Context, migrator *postgres.Migrator, output io.Writer) error { + migration, err := migrator.DownOne(ctx) + if errors.Is(err, postgres.ErrNoMigrationToRollBack) { + _, writeErr := fmt.Fprintln(output, "no applied migration to roll back") + if writeErr != nil { + return fmt.Errorf("main.rollBackOne - write result: %w", writeErr) + } + return nil + } + if err != nil { + return fmt.Errorf("main.rollBackOne - roll back migration: %w", err) + } + if _, err := fmt.Fprintf(output, "rolled back %s (%s)\n", migration.Name, migration.Duration); err != nil { + return fmt.Errorf("main.rollBackOne - write result: %w", err) + } + return nil +} diff --git a/backend/cmd/policy-publish/main.go b/backend/cmd/policy-publish/main.go new file mode 100644 index 0000000..81dd3d6 --- /dev/null +++ b/backend/cmd/policy-publish/main.go @@ -0,0 +1,29 @@ +// Command policy-publish adds the demo matching section or the semantic +// matching section to the product policy of a stand. It publishes a new immutable version and changes nothing +// else. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/internal/adapter/primary/cli/policypublish" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := policypublish.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "policy-publish: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/cmd/questionnaire-fixture/main.go b/backend/cmd/questionnaire-fixture/main.go new file mode 100644 index 0000000..1e3000a --- /dev/null +++ b/backend/cmd/questionnaire-fixture/main.go @@ -0,0 +1,402 @@ +//go:build e2e + +package main + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/policy" +) + +const ( + fixtureEnabledName = "E2E_QUESTIONNAIRE_FIXTURE" + fixtureTimeout = 90 * time.Second + maxFixtureFamilies = 200 + + fixtureBundleName = "e2e-questionnaire-bank" + fixtureAuthor = "operator:questionnaire-fixture-author" + fixtureReviewer = "operator:questionnaire-fixture-reviewer" + fixturePublisher = domain.AssessmentOperator("operator:questionnaire-fixture-publisher") + fixtureOpener = domain.AssessmentOperator("operator:questionnaire-fixture-opener") + fixtureFamilyStem = "e2e-questionnaire-family-" + fixtureCategory = domain.AssessmentCategory("backend") + trainingFamilyStem = "e2e-express-family-" + trainingCategory = "e2e-express" +) + +func main() { + if err := run(context.Background(), os.Args[1:], os.LookupEnv); err != nil { + if _, writeErr := fmt.Fprintln(os.Stderr, err); writeErr != nil { + os.Exit(1) + } + os.Exit(1) + } + if _, err := fmt.Fprintln(os.Stdout, "Questionnaire bank fixture is ready."); err != nil { + os.Exit(1) + } +} + +func run( + parent context.Context, + args []string, + lookupEnv func(string) (string, bool), +) error { + if len(args) != 0 { + return errors.New("questionnaire fixture accepts no arguments") + } + enabled, _ := lookupEnv(fixtureEnabledName) + if enabled != "1" { + return errors.New("questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1") + } + databaseURL, _ := lookupEnv("DATABASE_URL") + if databaseURL == "" { + return errors.New("questionnaire fixture database is not configured") + } + + ctx, cancel := context.WithTimeout(parent, fixtureTimeout) + defer cancel() + pool, err := postgres.NewSizedPool(ctx, databaseURL, 4) + if err != nil { + return errors.New("questionnaire fixture could not open its database") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("questionnaire fixture database is unavailable") + } + if err := seedQuestionnaireBank(ctx, pool); err != nil { + return err + } + return nil +} + +func seedQuestionnaireBank(ctx context.Context, pool *pgxpool.Pool) error { + const location = "questionnaire fixture" + occupied, err := backendQuestionnaireBankOccupied(ctx, pool) + if err != nil { + return errors.New(location + " could not inspect backend bank state") + } + if occupied { + return errors.New(location + " refuses existing backend openings or published families") + } + trainingOccupied, err := questionnaireTrainingBankOccupied(ctx, pool) + if err != nil { + return errors.New(location + " could not inspect training bank state") + } + if trainingOccupied { + return errors.New(location + " refuses an existing training binding or published families") + } + + transactor := postgres.NewTransactor(pool) + currentPolicy, err := publishFixturePolicy(ctx, transactor) + if err != nil { + if errors.Is(err, outbound.ErrPolicyVersionNotFound) { + return errors.New(location + " requires a current product assessment policy") + } + return errors.New(location + " could not read the current product policy") + } + required, err := domain.RequiredPublishedAssessmentFamilies(currentPolicy.Policy()) + if err != nil || required < 1 || required > maxFixtureFamilies { + return errors.New(location + " current policy has an unsupported family threshold") + } + bundle, err := reviewedQuestionnaireBundle(int(required)) + if err != nil { + return errors.New(location + " reviewed family fixture is invalid") + } + + bank := assessment.NewBank(transactor) + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + return errors.New(location + " could not import reviewed families") + } + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + return errors.New(location + " could not publish reviewed families") + } + } + metadata, err := questionnaireCatalogMetadata() + if err != nil { + return errors.New(location + " public catalog mapping is invalid") + } + if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: fixtureCategory, GradingPolicyID: currentPolicy.ID(), OpenedBy: fixtureOpener, + CatalogMetadata: &metadata, + }); err != nil { + return errors.New(location + " could not open the reviewed catalog mapping") + } + if err := seedQuestionnaireTrainingBank(ctx, pool, bank, currentPolicy); err != nil { + return errors.New(location + " could not seed the reviewed express training bank") + } + return nil +} + +func questionnaireTrainingBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) { + var occupied bool + err := pool.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 FROM assessment_training_bank_bindings WHERE category = $1 + ) OR EXISTS ( + SELECT 1 FROM assessment_families + WHERE category = $1 AND family_key LIKE $2 + )`, trainingCategory, trainingFamilyStem+"%").Scan(&occupied) + return occupied, err +} + +func seedQuestionnaireTrainingBank( + ctx context.Context, + pool *pgxpool.Pool, + bank *assessment.Bank, + productPolicy domain.PolicyVersion, +) error { + trainingPolicy := productPolicy.Policy().Assessment.Training + if trainingPolicy == nil { + return errors.New("current product policy has no explicit training mode") + } + count := int(trainingPolicy.DemoExpressItemCount) + if count < 1 || count > maxFixtureFamilies { + return errors.New("training item count is outside the fixture limit") + } + bundle, err := reviewedTrainingBundle(count) + if err != nil { + return errors.New("reviewed training family fixture is invalid") + } + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + return errors.New("could not import reviewed training families") + } + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + return errors.New("could not publish reviewed training family") + } + } + return seedQuestionnaireTrainingBinding(ctx, pool, productPolicy.ID().UUID(), bundle.Category, count) +} + +func reviewedTrainingBundle(count int) (assessment.Bundle, error) { + bundle, err := reviewedQuestionnaireBundle(count) + if err != nil { + return assessment.Bundle{}, err + } + bundle.Name = "e2e-express-training-bank" + bundle.Category = trainingCategory + for index := range bundle.Families { + bundle.Families[index].Key = fmt.Sprintf("%s%02d", trainingFamilyStem, index+1) + bundle.Families[index].Specialization = "rate-limiting" + } + if _, err := bundle.Drafts(); err != nil { + return assessment.Bundle{}, err + } + return bundle, nil +} + +func seedQuestionnaireTrainingBinding( + ctx context.Context, + pool *pgxpool.Pool, + policyID uuid.UUID, + category string, + itemCount int, +) error { + type manifestEntry struct { + FamilyKey string `json:"family_key"` + Version int32 `json:"version"` + ContentSHA256 string `json:"content_sha256"` + } + type familyRecord struct { + ID uuid.UUID + Entry manifestEntry + Hash []byte + } + rows, err := pool.Query(ctx, ` + SELECT id, family_key, version, content_sha256 + FROM assessment_families + WHERE category=$1 AND lifecycle='published' + ORDER BY family_key, version`, category) + if err != nil { + return errors.New("could not read published training families") + } + var families []familyRecord + for rows.Next() { + var family familyRecord + if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil { + rows.Close() + return errors.New("could not read a published training family") + } + family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash) + families = append(families, family) + } + if err := rows.Err(); err != nil { + rows.Close() + return errors.New("could not finish reading training families") + } + rows.Close() + if len(families) != itemCount { + return errors.New("published training family count does not match policy") + } + entries := make([]manifestEntry, len(families)) + canonical := []byte("lincodex.assessment.category-manifest.v1\x00") + for index, family := range families { + if len(family.Entry.FamilyKey) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size { + return errors.New("training family manifest entry is outside the supported range") + } + entries[index] = family.Entry + key := []byte(family.Entry.FamilyKey) + canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key))) + canonical = append(canonical, key...) + canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version)) + canonical = append(canonical, family.Hash...) + } + manifest, err := json.Marshal(entries) + if err != nil { + return errors.New("could not encode training family manifest") + } + manifestHash := sha256.Sum256(canonical) + transaction, err := pool.Begin(ctx) + if err != nil { + return errors.New("could not begin training binding transaction") + } + defer transaction.Rollback(ctx) + bindingID := uuid.New() + if _, err := transaction.Exec(ctx, ` + INSERT INTO assessment_training_bank_bindings ( + id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at + ) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`, + bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil { + return errors.New("could not insert the training binding") + } + for index, family := range families { + if _, err := transaction.Exec(ctx, ` + INSERT INTO assessment_training_bank_binding_families ( + binding_id, ordinal, family_id, family_key, family_version, content_sha256 + ) VALUES ($1,$2,$3,$4,$5,$6)`, + bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil { + return errors.New("could not add a training binding family") + } + } + if err := transaction.Commit(ctx); err != nil { + return errors.New("could not commit the training binding") + } + return nil +} + +func questionnaireCatalogMetadata() (domain.AssessmentCategoryCatalogMetadata, error) { + return domain.NewAssessmentCategoryCatalogMetadata( + domain.SpecializationBackend, + domain.GradeJunior, + []domain.TaskLanguageCode{domain.TaskLanguageGo, domain.TaskLanguagePython}, + ) +} + +func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) (bool, error) { + var occupied bool + err := pool.QueryRow(ctx, ` + SELECT + EXISTS (SELECT 1 FROM assessment_category_openings WHERE category = $1) + OR EXISTS ( + SELECT 1 FROM assessment_families + WHERE category = $1 AND lifecycle = 'published' + ) + OR EXISTS ( + SELECT 1 FROM assessment_families + WHERE category = $1 AND family_key LIKE $2 + )`, string(fixtureCategory), fixtureFamilyStem+"%").Scan(&occupied) + return occupied, err +} + +// The isolated browser fixture opts into the extended demo policy explicitly, +// including the manual-review band thresholds and the matching coefficients. +// Normal startup still seeds V1, and an operator's policy must never be +// replaced. +func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) (domain.PolicyVersion, error) { + initial, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + return domain.PolicyVersion{}, err + } + var version domain.PolicyVersion + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return err + } + current, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, databaseTime) + if err != nil { + return err + } + latest, err := unit.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil { + return err + } + if current.Kind() != domain.PolicyKindDemo || current.DocumentHash() != initial.DocumentHash() || + current.Version() != 1 || current.ID() != latest.ID() { + return errors.New("questionnaire fixture refuses an operator-owned product policy") + } + version, err = policy.NewPublisher(unit.Policies(), func() time.Time { return databaseTime }).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV4(), + }) + return err + }) + return version, err +} + +func reviewedQuestionnaireBundle(count int) (assessment.Bundle, error) { + if count < 1 || count > maxFixtureFamilies { + return assessment.Bundle{}, errors.New("questionnaire fixture family count is outside the supported range") + } + bundle := assessment.Bundle{ + Name: fixtureBundleName, Category: string(fixtureCategory), Author: fixtureAuthor, + Review: assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer}, + Families: make([]assessment.BundleFamily, 0, count), + } + requestsMinimum := int32(12) + for index := range count { + familyNumber := index + 1 + family := assessment.BundleFamily{ + Key: fmt.Sprintf("%s%03d", fixtureFamilyStem, familyNumber), Version: 1, + Specialization: "rate-limiting", Title: fmt.Sprintf("Sliding-window fixture case %03d", familyNumber), + SeedGenerator: domain.AssessmentSeedGenerator{ + Algorithm: "rate_limit_window.v1", + Parameters: map[string]domain.AssessmentParameterRange{ + "requests": {Min: requestsMinimum, Max: requestsMinimum + 8}, + "window": {Min: 3, Max: 15}, + "limit": {Min: 2, Max: 6}, + "max_gap": {Min: 1, Max: 5}, + }, + StatementTemplate: "A gateway applies a sliding-window limiter. A request at second t is accepted only when fewer than {{.limit}} previously accepted requests arrived in (t - {{.window}}, t]. Rejected requests are not remembered. The gateway receives {{.requests}} requests at these non-decreasing arrival times: {{.timestamps}}. How many requests are rejected?", + }, + AnswerKey: domain.AssessmentAnswerKey{ + AnswerFormat: domain.AnswerFormatInteger, + ReferenceSolution: "Keep accepted arrival times in order. Before each request at t, remove accepted times at or before t - window. Accept and append t when fewer than limit times remain; otherwise count a rejection without appending it. Each request enters and leaves the queue at most once.", + }, + Rubric: domain.AssessmentRubric{ + Principle: "The answer is the exact number of rejected requests for the generated arrival sequence. The rubric has criteria but no points or pass mark.", + Criteria: []domain.AssessmentRubricCriterion{ + {ID: "correct_answer", Description: "The submitted integer equals the generated reference answer."}, + {ID: "window_boundary", Description: "A request exactly window seconds old is outside the half-open interval."}, + {ID: "rejected_not_counted", Description: "Rejected requests do not occupy capacity in later windows."}, + {ID: "queue_approach", Description: "The approach processes each arrival at most once when entering and once when leaving the queue."}, + }, + }, + } + bundle.Families = append(bundle.Families, family) + requestsMinimum++ + } + if _, err := bundle.Drafts(); err != nil { + return assessment.Bundle{}, err + } + return bundle, nil +} diff --git a/backend/cmd/questionnaire-fixture/main_test.go b/backend/cmd/questionnaire-fixture/main_test.go new file mode 100644 index 0000000..e336536 --- /dev/null +++ b/backend/cmd/questionnaire-fixture/main_test.go @@ -0,0 +1,87 @@ +//go:build e2e + +package main + +import ( + "context" + "testing" + + "lincodex/backend/internal/domain" +) + +func TestRunRequiresExactE2EGuardBeforeDatabase(t *testing.T) { + lookup := func(name string) (string, bool) { + if name == "DATABASE_URL" { + return "postgres://fixture.invalid/test", true + } + return "true", true + } + err := run(context.Background(), nil, lookup) + if err == nil || err.Error() != "questionnaire fixture requires E2E_QUESTIONNAIRE_FIXTURE=1" { + t.Fatalf("run(disabled) error = %v, want exact E2E guard refusal", err) + } +} + +func TestRunRejectsArgumentsAndMissingDatabase(t *testing.T) { + enabled := func(name string) (string, bool) { + if name == fixtureEnabledName { + return "1", true + } + return "", false + } + if err := run(context.Background(), []string{"seed"}, enabled); err == nil || err.Error() != "questionnaire fixture accepts no arguments" { + t.Fatalf("run(with argument) error = %v, want argument refusal", err) + } + if err := run(context.Background(), nil, enabled); err == nil || err.Error() != "questionnaire fixture database is not configured" { + t.Fatalf("run(without database) error = %v, want missing database refusal", err) + } +} + +func TestReviewedQuestionnaireBundleValidatesIndependentFamilies(t *testing.T) { + const count = 13 + bundle, err := reviewedQuestionnaireBundle(count) + if err != nil { + t.Fatalf("reviewedQuestionnaireBundle(%d) error = %v", count, err) + } + if bundle.Category != string(fixtureCategory) || bundle.Review.Status != string(domain.AssessmentReviewApproved) || + bundle.Author == bundle.Review.Reviewer || len(bundle.Families) != count { + t.Fatalf("reviewed fixture bundle metadata = category %q, review %q by %q, author %q, families %d", + bundle.Category, bundle.Review.Status, bundle.Review.Reviewer, bundle.Author, len(bundle.Families)) + } + drafts, err := bundle.Drafts() + if err != nil || len(drafts) != count { + t.Fatalf("Bundle.Drafts() = %d, %v; want %d valid reviewed families", len(drafts), err, count) + } + seen := make(map[domain.AssessmentFamilyKey]struct{}, count) + for _, draft := range drafts { + core := draft.Core() + if core.Category != fixtureCategory || core.Reviewer == "" || string(core.Reviewer) == string(core.Author) { + t.Fatalf("draft review identity/category is not independent: category %q reviewer %q author %q", core.Category, core.Reviewer, core.Author) + } + if _, exists := seen[core.Key]; exists { + t.Fatalf("duplicate synthetic family key %q", core.Key) + } + seen[core.Key] = struct{}{} + } +} + +func TestReviewedQuestionnaireBundleRejectsUnsupportedThreshold(t *testing.T) { + for _, count := range []int{0, maxFixtureFamilies + 1} { + if _, err := reviewedQuestionnaireBundle(count); err == nil { + t.Fatalf("reviewedQuestionnaireBundle(%d) error = %v; want a fixture threshold error", count, err) + } + } +} + +func TestQuestionnaireCatalogMetadataUsesTheReviewedE2EProjection(t *testing.T) { + metadata, err := questionnaireCatalogMetadata() + if err != nil { + t.Fatalf("questionnaireCatalogMetadata() error = %v", err) + } + if metadata.Specialization() != domain.SpecializationBackend || metadata.Grade() != domain.GradeJunior || + len(metadata.TaskLanguages()) != 2 || metadata.TaskLanguages()[0] != domain.TaskLanguageGo || + metadata.TaskLanguages()[1] != domain.TaskLanguagePython { + t.Fatalf("questionnaire catalog metadata = %s/%s/%v; want Backend/Junior/Go+Python", + metadata.Specialization(), metadata.Grade(), metadata.TaskLanguages()) + } +} diff --git a/backend/cmd/semantic-backfill/main.go b/backend/cmd/semantic-backfill/main.go new file mode 100644 index 0000000..1de2ccc --- /dev/null +++ b/backend/cmd/semantic-backfill/main.go @@ -0,0 +1,28 @@ +// Command semantic-backfill schedules vector jobs for the existing published +// candidates and needs of a stand. It changes no product data. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + "time" + + "lincodex/backend/internal/adapter/primary/cli/semanticbackfill" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := semanticbackfill.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, time.Now); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "semantic-backfill: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/codegen/ogen-code-runner.yml b/backend/codegen/ogen-code-runner.yml new file mode 100644 index 0000000..b2e7216 --- /dev/null +++ b/backend/codegen/ogen-code-runner.yml @@ -0,0 +1,5 @@ +generator: + features: + disable: + - paths/server + - webhooks/server diff --git a/backend/codegen/ogen-labd.yml b/backend/codegen/ogen-labd.yml new file mode 100644 index 0000000..b2e7216 --- /dev/null +++ b/backend/codegen/ogen-labd.yml @@ -0,0 +1,5 @@ +generator: + features: + disable: + - paths/server + - webhooks/server diff --git a/backend/config/assessment.go b/backend/config/assessment.go new file mode 100644 index 0000000..561e650 --- /dev/null +++ b/backend/config/assessment.go @@ -0,0 +1,12 @@ +package config + +// loadAssessment reads narrowly scoped assessment feature gates. All gates +// default off so configuration cannot silently grant synthetic provenance. +func (config *Config) loadAssessment(lookup LookupEnv) error { + enabled, err := boolOrDefault(lookup, "ASSESSMENT_DEMO_CATEGORIES_ENABLED", false) + if err != nil { + return err + } + config.AssessmentDemoCategoriesEnabled = enabled + return nil +} diff --git a/backend/config/assessment_test.go b/backend/config/assessment_test.go new file mode 100644 index 0000000..f2bd81a --- /dev/null +++ b/backend/config/assessment_test.go @@ -0,0 +1,37 @@ +package config + +import ( + "strings" + "testing" +) + +func TestLoadFromEnvAssessmentDemoCategoriesDefaultsOff(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.AssessmentDemoCategoriesEnabled { + t.Fatal("AssessmentDemoCategoriesEnabled = true, want default false") + } +} + +func TestLoadFromEnvAssessmentDemoCategoriesReadsExplicitValue(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "ASSESSMENT_DEMO_CATEGORIES_ENABLED": " TRUE ", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !settings.AssessmentDemoCategoriesEnabled { + t.Fatal("AssessmentDemoCategoriesEnabled = false, want explicit true") + } +} + +func TestLoadFromEnvAssessmentDemoCategoriesRejectsAmbiguousValue(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{ + "ASSESSMENT_DEMO_CATEGORIES_ENABLED": "yes", + })) + if err == nil || !strings.HasPrefix(err.Error(), "config.boolOrDefault - ASSESSMENT_DEMO_CATEGORIES_ENABLED") { + t.Fatalf("LoadFromEnv() error = %v, want a strict boolean setting error", err) + } +} diff --git a/backend/config/code_runner.go b/backend/config/code_runner.go new file mode 100644 index 0000000..a60b21d --- /dev/null +++ b/backend/config/code_runner.go @@ -0,0 +1,189 @@ +package config + +import ( + "encoding/pem" + "errors" + "fmt" + "log/slog" + "net/url" + "strings" + "time" +) + +const ( + defaultCodeRunnerRequestTimeout = 10 * time.Second + // One request submits or reads a run; the runner answers at once and runs + // asynchronously. A minute is far above any healthy answer and keeps a + // hung runner from holding a worker. + minCodeRunnerRequestTimeout = time.Second + maxCodeRunnerRequestTimeout = time.Minute + // The runner requires a token of at least 32 characters; the run key + // follows the same bound. + minCodeRunnerSecretLength = 32 + maxCodeRunnerSecretLength = 256 + redactedCodeRunnerSetting = "[redacted code runner settings]" +) + +// CodeRunnerSettings configure the client of the own code runner (api/runner). +// The runner is off unless CODE_RUNNER_URL is set: there is no default URL, +// because untrusted code must only ever go to a host the operator named. +// +// String, GoString, Format, and LogValue redact everything, because the +// token, the run key, and the CA are secrets of the deployment. +type CodeRunnerSettings struct { + // URL is the runner origin, for example https://10.80.0.2:8443. Only https + // is accepted; empty means the runner is disabled. + URL string + // Token is the shared service token (Authorization: Bearer). + Token string + // RunKey keys the HMAC that derives opaque run IDs from submissions, so + // the runner never sees attempt or submission identifiers. It is a secret + // that differs from Token. + RunKey string + // CAFile is the path of the PEM file with the CA that signed the runner + // certificate. Exactly one of CAFile and CAPEM is set when enabled. + CAFile string + // CAPEM is the same CA as inline PEM text, for deployments without a + // file mount. + CAPEM string + // ServerName is the optional name to verify the runner certificate + // against, for a runner addressed by an IP the certificate does not list. + ServerName string + // RequestTimeout bounds one request to the runner. + RequestTimeout time.Duration +} + +// Enabled reports whether a runner is configured. +func (settings CodeRunnerSettings) Enabled() bool { return settings.URL != "" } + +func (settings CodeRunnerSettings) String() string { return redactedCodeRunnerSetting } + +func (settings CodeRunnerSettings) GoString() string { return redactedCodeRunnerSetting } + +// Format redacts every verb; without it %+v would print the secrets. +func (settings CodeRunnerSettings) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedCodeRunnerSetting)) +} + +func (settings CodeRunnerSettings) LogValue() slog.Value { + return slog.StringValue(redactedCodeRunnerSetting) +} + +// LoadCodeRunnerSettings reads the code runner settings. An empty variable +// counts as unset, as Compose passes an unset variable as an empty string. +func LoadCodeRunnerSettings(lookup LookupEnv) (CodeRunnerSettings, error) { + text := func(key string) string { return strings.TrimSpace(valueOrDefault(lookup, key, "")) } + settings := CodeRunnerSettings{ + URL: text("CODE_RUNNER_URL"), + Token: text("CODE_RUNNER_TOKEN"), + RunKey: text("CODE_RUNNER_RUN_KEY"), + CAFile: text("CODE_RUNNER_CA_FILE"), + CAPEM: normalizePEM(text("CODE_RUNNER_CA_PEM")), + ServerName: text("CODE_RUNNER_SERVER_NAME"), + RequestTimeout: defaultCodeRunnerRequestTimeout, + } + if timeout := text("CODE_RUNNER_REQUEST_TIMEOUT"); timeout != "" { + parsed, err := time.ParseDuration(timeout) + if err != nil { + return CodeRunnerSettings{}, errors.New("config.LoadCodeRunnerSettings - CODE_RUNNER_REQUEST_TIMEOUT must be a duration such as 10s") + } + settings.RequestTimeout = parsed + } + return settings, settings.Validate() +} + +// normalizePEM accepts a PEM written on one line with literal \n sequences, +// which env files without multi-line values need. +func normalizePEM(value string) string { + if !strings.Contains(value, "\n") { + value = strings.ReplaceAll(value, `\n`, "\n") + } + return value +} + +// Validate checks the settings. A disabled runner must have no other runner +// setting, so a secret is never silently ignored. Errors name the setting and +// never print its value. +func (settings CodeRunnerSettings) Validate() error { + const location = "CodeRunnerSettings.Validate" + if !settings.Enabled() { + if settings.Token != "" || settings.RunKey != "" || settings.CAFile != "" || settings.CAPEM != "" || settings.ServerName != "" || + (settings.RequestTimeout != 0 && settings.RequestTimeout != defaultCodeRunnerRequestTimeout) { + return errors.New(location + " - CODE_RUNNER_URL must be set when any other CODE_RUNNER_* setting is set") + } + return nil + } + if err := settings.validateURL(); err != nil { + return err + } + if err := settings.validateSecrets(); err != nil { + return err + } + if err := settings.validateCA(); err != nil { + return err + } + if settings.ServerName != "" && !validHostOrIP(settings.ServerName) { + return errors.New(location + " - CODE_RUNNER_SERVER_NAME must be a hostname or IP address") + } + return settings.validateTimeout() +} + +func (settings CodeRunnerSettings) validateURL() error { + const location = "CodeRunnerSettings.Validate" + origin, err := url.Parse(settings.URL) + if err != nil || origin.Scheme != "https" || origin.Hostname() == "" || !validHostOrIP(origin.Hostname()) { + return errors.New(location + " - CODE_RUNNER_URL must be an https URL with a valid host; the runner is never called over plain HTTP") + } + if !isBareOrigin(origin, settings.URL) { + return errors.New(location + " - CODE_RUNNER_URL must be an origin without credentials, a path, query, or fragment") + } + if !validEndpointPort(origin) { + return errors.New(location + " - CODE_RUNNER_URL must have a valid nonzero port") + } + return nil +} + +func (settings CodeRunnerSettings) validateSecrets() error { + const location = "CodeRunnerSettings.Validate" + for _, secret := range []struct{ name, value string }{ + {"CODE_RUNNER_TOKEN", settings.Token}, {"CODE_RUNNER_RUN_KEY", settings.RunKey}, + } { + if len(secret.value) < minCodeRunnerSecretLength || len(secret.value) > maxCodeRunnerSecretLength || + !isPrintableASCII(secret.value) || strings.Contains(secret.value, " ") { + return fmt.Errorf("%s - %s must have %d to %d printable ASCII characters without spaces when CODE_RUNNER_URL is set", + location, secret.name, minCodeRunnerSecretLength, maxCodeRunnerSecretLength) + } + if strings.HasPrefix(strings.ToLower(secret.value), "replace-this") { + return fmt.Errorf("%s - %s still has its placeholder value", location, secret.name) + } + } + // The runner knows the token; if it were also the run key, the runner + // could recompute run IDs and link them to submissions. + if settings.Token == settings.RunKey { + return errors.New(location + " - CODE_RUNNER_RUN_KEY must differ from CODE_RUNNER_TOKEN") + } + return nil +} + +func (settings CodeRunnerSettings) validateCA() error { + const location = "CodeRunnerSettings.Validate" + switch { + case settings.CAFile == "" && settings.CAPEM == "": + return errors.New(location + " - CODE_RUNNER_CA_FILE or CODE_RUNNER_CA_PEM must be set when CODE_RUNNER_URL is set") + case settings.CAFile != "" && settings.CAPEM != "": + return errors.New(location + " - set only one of CODE_RUNNER_CA_FILE and CODE_RUNNER_CA_PEM") + case settings.CAPEM != "": + if block, _ := pem.Decode([]byte(settings.CAPEM)); block == nil || block.Type != "CERTIFICATE" { + return errors.New(location + " - CODE_RUNNER_CA_PEM must start with a PEM CERTIFICATE block") + } + } + return nil +} + +func (settings CodeRunnerSettings) validateTimeout() error { + if settings.RequestTimeout < minCodeRunnerRequestTimeout || settings.RequestTimeout > maxCodeRunnerRequestTimeout { + return fmt.Errorf("CodeRunnerSettings.Validate - CODE_RUNNER_REQUEST_TIMEOUT must be between %s and %s", + minCodeRunnerRequestTimeout, maxCodeRunnerRequestTimeout) + } + return nil +} diff --git a/backend/config/code_runner_test.go b/backend/config/code_runner_test.go new file mode 100644 index 0000000..1434599 --- /dev/null +++ b/backend/config/code_runner_test.go @@ -0,0 +1,193 @@ +package config + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "log/slog" + "math/big" + "strings" + "testing" + "time" +) + +const ( + testRunnerToken = "runner-token-0123456789abcdef0123456789" + testRunnerRunKey = "runner-run-key-0123456789abcdef012345678" +) + +// testRunnerCAPEM is a real, self-signed CA certificate made once per test run. +var testRunnerCAPEM = func() string { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + panic(err) + } + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "config test CA"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + panic(err) + } + return string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) +}() + +func codeRunnerLookup(values map[string]string) LookupEnv { + return func(key string) (string, bool) { + value, ok := values[key] + return value, ok + } +} + +func enabledRunnerEnv() map[string]string { + return map[string]string{ + "CODE_RUNNER_URL": "https://10.80.0.2:8443", + "CODE_RUNNER_TOKEN": testRunnerToken, + "CODE_RUNNER_RUN_KEY": testRunnerRunKey, + "CODE_RUNNER_CA_FILE": "/run/secrets/runner-ca.pem", + } +} + +func TestCodeRunnerSettingsAreDisabledByDefault(t *testing.T) { + for name, values := range map[string]map[string]string{ + "unset": nil, + "empty values as Compose passes them": { + "CODE_RUNNER_URL": "", "CODE_RUNNER_TOKEN": "", "CODE_RUNNER_RUN_KEY": "", "CODE_RUNNER_CA_FILE": "", + "CODE_RUNNER_CA_PEM": "", "CODE_RUNNER_SERVER_NAME": "", "CODE_RUNNER_REQUEST_TIMEOUT": "", + }, + } { + settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values)) + if err != nil || settings.Enabled() { + t.Fatalf("%s: settings = %v, %v, want a disabled runner", name, settings.Enabled(), err) + } + } +} + +func TestCodeRunnerSettingsLoadAnEnabledRunner(t *testing.T) { + values := enabledRunnerEnv() + values["CODE_RUNNER_SERVER_NAME"] = "runner.internal" + values["CODE_RUNNER_REQUEST_TIMEOUT"] = "20s" + + settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values)) + + if err != nil || !settings.Enabled() { + t.Fatalf("LoadCodeRunnerSettings() = %v, %v, want an enabled runner", settings.Enabled(), err) + } + if settings.URL != "https://10.80.0.2:8443" || settings.CAFile != "/run/secrets/runner-ca.pem" || + settings.ServerName != "runner.internal" || settings.RequestTimeout != 20*time.Second { + t.Fatalf("settings were not read as set") + } +} + +func TestCodeRunnerSettingsAcceptAnInlineCAWithEscapedNewlines(t *testing.T) { + values := enabledRunnerEnv() + delete(values, "CODE_RUNNER_CA_FILE") + values["CODE_RUNNER_CA_PEM"] = strings.ReplaceAll(strings.TrimSpace(testRunnerCAPEM), "\n", `\n`) + + settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values)) + + if err != nil || !strings.HasPrefix(settings.CAPEM, "-----BEGIN CERTIFICATE-----\n") { + t.Fatalf("LoadCodeRunnerSettings() CAPEM = %q, %v, want the PEM with real newlines", settings.CAPEM, err) + } +} + +func TestCodeRunnerSettingsRejectInvalidValuesWithoutEchoingThem(t *testing.T) { + tests := []struct { + name string + change func(map[string]string) + }{ + {"plain http", func(v map[string]string) { v["CODE_RUNNER_URL"] = "http://10.80.0.2:8443" }}, + {"path", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://10.80.0.2:8443/api" }}, + {"credentials", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://user:password-value@10.80.0.2" }}, + {"query", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://10.80.0.2:8443?x=1" }}, + {"port zero", func(v map[string]string) { v["CODE_RUNNER_URL"] = "https://10.80.0.2:0" }}, + {"short token", func(v map[string]string) { v["CODE_RUNNER_TOKEN"] = "short-token-value" }}, + {"token with space", func(v map[string]string) { v["CODE_RUNNER_TOKEN"] = testRunnerToken + " x" }}, + {"missing token", func(v map[string]string) { delete(v, "CODE_RUNNER_TOKEN") }}, + {"short run key", func(v map[string]string) { v["CODE_RUNNER_RUN_KEY"] = "short-run-key-value" }}, + {"placeholder run key", func(v map[string]string) { v["CODE_RUNNER_RUN_KEY"] = "replace-this-run-key-0123456789abcdef0123" }}, + {"run key equals token", func(v map[string]string) { v["CODE_RUNNER_RUN_KEY"] = testRunnerToken }}, + {"no CA", func(v map[string]string) { delete(v, "CODE_RUNNER_CA_FILE") }}, + {"both CAs", func(v map[string]string) { v["CODE_RUNNER_CA_PEM"] = testRunnerCAPEM }}, + {"CA that is not PEM", func(v map[string]string) { + delete(v, "CODE_RUNNER_CA_FILE") + v["CODE_RUNNER_CA_PEM"] = "not-a-certificate-value" + }}, + {"bad server name", func(v map[string]string) { v["CODE_RUNNER_SERVER_NAME"] = "bad name!" }}, + {"timeout that is not a duration", func(v map[string]string) { v["CODE_RUNNER_REQUEST_TIMEOUT"] = "soon" }}, + {"timeout too short", func(v map[string]string) { v["CODE_RUNNER_REQUEST_TIMEOUT"] = "100ms" }}, + {"timeout too long", func(v map[string]string) { v["CODE_RUNNER_REQUEST_TIMEOUT"] = "5m" }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + values := enabledRunnerEnv() + test.change(values) + + _, err := LoadCodeRunnerSettings(codeRunnerLookup(values)) + + if err == nil { + t.Fatal("LoadCodeRunnerSettings() accepted invalid settings") + } + for _, secret := range []string{testRunnerToken, testRunnerRunKey, "password-value", "not-a-certificate-value"} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("error echoes a value: %v", err) + } + } + }) + } +} + +func TestCodeRunnerSettingsRefuseSecretsWithoutAURL(t *testing.T) { + for _, key := range []string{ + "CODE_RUNNER_TOKEN", "CODE_RUNNER_RUN_KEY", "CODE_RUNNER_CA_FILE", "CODE_RUNNER_CA_PEM", + "CODE_RUNNER_SERVER_NAME", "CODE_RUNNER_REQUEST_TIMEOUT", + } { + value := testRunnerToken + if key == "CODE_RUNNER_REQUEST_TIMEOUT" { + value = "5s" + } + _, err := LoadCodeRunnerSettings(codeRunnerLookup(map[string]string{key: value})) + if err == nil { + t.Errorf("%s without CODE_RUNNER_URL was silently ignored", key) + } + } +} + +func TestCodeRunnerSettingsAreRedactedInEveryRendering(t *testing.T) { + values := enabledRunnerEnv() + settings, err := LoadCodeRunnerSettings(codeRunnerLookup(values)) + if err != nil { + t.Fatalf("LoadCodeRunnerSettings() error = %v", err) + } + for _, rendered := range []string{ + settings.String(), settings.GoString(), settings.LogValue().String(), + fmt.Sprintf("%v", settings), fmt.Sprintf("%+v", settings), fmt.Sprintf("%#v", settings), + slog.Group("runner", slog.Any("settings", settings)).Value.String(), + } { + if strings.Contains(rendered, testRunnerToken) || strings.Contains(rendered, testRunnerRunKey) { + t.Fatalf("rendering exposes a secret: %q", rendered) + } + } +} + +func TestConfigLoadsAndValidatesTheCodeRunner(t *testing.T) { + base := map[string]string{} + config, err := LoadFromEnv(testEnvironment(base)) + if err != nil || config.CodeRunner.Enabled() { + t.Fatalf("LoadFromEnv() runner enabled = %v, error = %v, want a disabled runner by default", config.CodeRunner.Enabled(), err) + } + + for key, value := range enabledRunnerEnv() { + base[key] = value + } + config, err = LoadFromEnv(testEnvironment(base)) + if err != nil || !config.CodeRunner.Enabled() { + t.Fatalf("LoadFromEnv() runner enabled = %v, error = %v, want an enabled runner", config.CodeRunner.Enabled(), err) + } +} diff --git a/backend/config/config.go b/backend/config/config.go index 949db5e..44daea9 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "net" + "net/netip" "os" "strconv" "strings" @@ -18,26 +19,156 @@ const ( defaultRedisTimeout = time.Second defaultReadinessTimeout = time.Second defaultShutdownTimeout = 10 * time.Second - maxPortNumber = 65535 + // Startup migrations are on by default so a deployed binary never serves + // with a schema older than the one it was built for. + defaultDatabaseMigrateOnStart = true + maxPortNumber = 65535 ) type Config struct { - HTTPAddr string - MetricsAddr string - DatabaseURL string - RedisAddr string - RedisPassword string - RedisDB int - RedisTimeout time.Duration - SeaweedFSEndpoint string - SeaweedFSAccessKey string - SeaweedFSSecretKey string - SeaweedFSBucket string - SeaweedFSRegion string - SeaweedFSTimeout time.Duration - LogLevel string - ReadinessTimeout time.Duration - ShutdownTimeout time.Duration + HTTPAddr string + MetricsAddr string + DatabaseURL string + // DatabaseMigrateOnStart applies embedded migrations before serving. + DatabaseMigrateOnStart bool + RedisAddr string + RedisPassword string + RedisDB int + RedisTimeout time.Duration + SeaweedFSEndpoint string + SeaweedFSAccessKey string + SeaweedFSSecretKey string + SeaweedFSBucket string + SeaweedFSRegion string + SeaweedFSTimeout time.Duration + KafkaBrokers []string + // KafkaEventsTopic receives every published domain event. + KafkaEventsTopic string + KafkaEventsTopicPartitions int32 + // KafkaEventsTopicReplicationFactor is -1 for the broker default. + KafkaEventsTopicReplicationFactor int16 + // KafkaEventsTopicMinInsyncReplicas is 0 for the broker default. + KafkaEventsTopicMinInsyncReplicas int16 + // KafkaProvisionTopics lets the relay create a missing events topic. + KafkaProvisionTopics bool + // RelayEnabled runs the outbox relay next to the HTTP servers. + RelayEnabled bool + RelayBatchSize int + RelayPollInterval time.Duration + RelayProduceTimeout time.Duration + // RelayStatementTimeout bounds each SQL statement of a relay pass. + RelayStatementTimeout time.Duration + RelayBackoffInitial time.Duration + RelayBackoffMax time.Duration + // ConsumerEnabled runs the registered event consumers next to the HTTP + // servers. + ConsumerEnabled bool + // NotificationSyntheticEnabled lets the inbox consume and render the + // synthetic notification event. Off by default; a development or browser + // test stand turns it on. + NotificationSyntheticEnabled bool + // ConsumerGroupPrefix and a consumer name form the consumer group ID. + ConsumerGroupPrefix string + ConsumerMaxAttempts int + ConsumerBackoffInitial time.Duration + ConsumerBackoffMax time.Duration + // ConsumerHandlerTimeout bounds one consumer transaction. + ConsumerHandlerTimeout time.Duration + ConsumerMaxPollRecords int + ConsumerCommitTimeout time.Duration + // ConsumerShutdownGrace bounds the record in progress after shutdown + // begins. + ConsumerShutdownGrace time.Duration + // ConsumerRebalanceTimeout is the Kafka rebalance timeout of every + // consumer group member. + ConsumerRebalanceTimeout time.Duration + // JobsEnabled runs the scheduled job worker next to the HTTP servers + // when a job handler is registered. + JobsEnabled bool + JobsPollInterval time.Duration + JobsBatchSize int + JobsLeaseDuration time.Duration + // JobsMaxAttempts applies to jobs scheduled without their own limit. + JobsMaxAttempts int + JobsBackoffInitial time.Duration + JobsBackoffMax time.Duration + // JobsShutdownGrace bounds the job in progress after shutdown begins. + JobsShutdownGrace time.Duration + // EmailProvider selects the only active mail transport. Settings of the + // other transports are not loaded. + EmailProvider EmailProvider + // EmailFrom is the sender mailbox for every outgoing message. + EmailFrom string + // EmailAccount labels the provider account that new deliveries are + // pinned to. It is configuration identity, never a credential. + EmailAccount string + EmailTimeout time.Duration + // EmailQuotaDaily and EmailQuotaMonthly limit the recipients sent + // through the configured provider account per UTC day and UTC month. + EmailQuotaDaily int + EmailQuotaMonthly int + // EmailServiceReserveDaily and EmailServiceReserveMonthly keep recipients + // of the daily and monthly quota free for service mail: product + // notifications are admitted only while the windows stay above them. + EmailServiceReserveDaily int + EmailServiceReserveMonthly int + // AppPublicURL is the public origin without a trailing slash, for links + // in mail. + AppPublicURL string + ResendAPIKey string + SMTPHost string + SMTPPort int + SMTPUsername string + SMTPPassword string + SMTPTLSMode SMTPTLSMode + LogLevel string + ReadinessTimeout time.Duration + ShutdownTimeout time.Duration + + // PasswordHashConcurrency is the number of password hash derivations + // that may run at once; further logins and registrations wait. + PasswordHashConcurrency int + + // IdentityKeySecret seeds domain-separated HMAC keys for idempotency + // scopes, rate limit buckets, and session CSRF tokens. Empty means a random + // secret for the life of the process. + IdentityKeySecret string + // IdentityAllowEphemeralKey lets a development stand run without + // IDENTITY_KEY_SECRET, with a random secret per process. + IdentityAllowEphemeralKey bool + // VerificationMailMinInterval and VerificationMailDailyLimit bound the + // verification messages to one address: the registration and every + // resend count against both. + VerificationMailMinInterval time.Duration + VerificationMailDailyLimit int + // IdentityClientHourlyLimit bounds the registrations and resends of one + // client network address per hour. + IdentityClientHourlyLimit int + // IdentityLoginEmailHourlyLimit bounds login attempts for one normalized + // email address per hour. + IdentityLoginEmailHourlyLimit int + // IdentitySessionIdleTimeout ends a session after this much inactivity. + IdentitySessionIdleTimeout time.Duration + // IdentitySessionAbsoluteLifetime is the maximum lifetime of a session, + // even when it remains active. + IdentitySessionAbsoluteLifetime time.Duration + // AssessmentDemoCategoriesEnabled explicitly enables synthetic demo category + // assignment. Reviewed source provenance is required separately. + AssessmentDemoCategoriesEnabled bool + + // Semantic configures semantic matching and repository checks. + Semantic SemanticSettings + + // CodeRunner configures the client of the own code runner. It is disabled + // unless CODE_RUNNER_URL is set. + CodeRunner CodeRunnerSettings + // Practice configures the debug run limits and the practice queue worker. + Practice PracticeSettings + + // TrustedProxyCIDRs are the reverse proxies in front of the API. The + // client address is taken from X-Forwarded-For only through them (see + // middleware.ClientIP). Empty trusts no proxy. + TrustedProxyCIDRs []netip.Prefix } type LookupEnv func(string) (string, bool) @@ -50,7 +181,7 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { config := Config{ HTTPAddr: valueOrDefault(lookup, "HTTP_ADDR", defaultHTTPAddr), MetricsAddr: valueOrDefault(lookup, "METRICS_ADDR", defaultMetricsAddr), - DatabaseURL: strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")), + DatabaseURL: DatabaseURLFromEnv(lookup), RedisAddr: strings.TrimSpace(valueOrDefault(lookup, "REDIS_ADDR", defaultRedisAddr)), RedisPassword: valueOrDefault(lookup, "REDIS_PASSWORD", ""), RedisTimeout: defaultRedisTimeout, @@ -60,6 +191,7 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { SeaweedFSBucket: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_BUCKET", defaultSeaweedFSBucket)), SeaweedFSRegion: strings.TrimSpace(valueOrDefault(lookup, "SEAWEEDFS_REGION", defaultSeaweedFSRegion)), SeaweedFSTimeout: defaultSeaweedFSTimeout, + KafkaBrokers: parseKafkaBrokers(valueOrDefault(lookup, "KAFKA_BROKERS", defaultKafkaBrokers)), LogLevel: strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "LOG_LEVEL", defaultLogLevel))), ReadinessTimeout: defaultReadinessTimeout, ShutdownTimeout: defaultShutdownTimeout, @@ -68,8 +200,37 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadRedis(lookup); err != nil { return Config{}, err } + if err := config.loadKafkaTopics(lookup); err != nil { + return Config{}, err + } + if err := config.loadRelay(lookup); err != nil { + return Config{}, err + } + if err := config.loadConsumer(lookup); err != nil { + return Config{}, err + } + if err := config.loadNotification(lookup); err != nil { + return Config{}, err + } + if err := config.loadJobs(lookup); err != nil { + return Config{}, err + } + if err := config.loadMail(lookup); err != nil { + return Config{}, err + } + if err := config.loadPasswordHash(lookup); err != nil { + return Config{}, err + } + if err := config.loadIdentityAndProxySettings(lookup); err != nil { + return Config{}, err + } var err error + config.DatabaseMigrateOnStart, err = boolOrDefault(lookup, "DATABASE_MIGRATE_ON_START", defaultDatabaseMigrateOnStart) + if err != nil { + return Config{}, err + } + config.SeaweedFSTimeout, err = durationOrDefault(lookup, "SEAWEEDFS_TIMEOUT", config.SeaweedFSTimeout) if err != nil { return Config{}, err @@ -91,6 +252,31 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { return config, nil } +func (config *Config) loadIdentityAndProxySettings(lookup LookupEnv) error { + if err := config.loadIdentity(lookup); err != nil { + return err + } + if err := config.loadAssessment(lookup); err != nil { + return err + } + semantic, err := LoadSemanticSettings(lookup) + if err != nil { + return err + } + config.Semantic = semantic + codeRunner, err := LoadCodeRunnerSettings(lookup) + if err != nil { + return err + } + config.CodeRunner = codeRunner + practice, err := LoadPracticeSettings(lookup, codeRunner.RequestTimeout) + if err != nil { + return err + } + config.Practice = practice + return config.loadTrustedProxies(lookup) +} + func (config Config) Validate() error { if err := config.ValidateSeaweedFS(); err != nil { return err @@ -98,6 +284,21 @@ func (config Config) Validate() error { if err := config.ValidateRedis(); err != nil { return err } + if err := config.ValidateKafka(); err != nil { + return err + } + if err := config.ValidateRelay(); err != nil { + return err + } + if err := config.ValidateMail(); err != nil { + return err + } + if err := config.ValidatePasswordHash(); err != nil { + return err + } + if err := config.ValidateIdentity(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } @@ -110,6 +311,14 @@ func (config Config) Validate() error { if config.ShutdownTimeout <= 0 { return errors.New("Config.Validate - SHUTDOWN_TIMEOUT must be positive") } + // The consumer and job shutdown graces are checked against + // SHUTDOWN_TIMEOUT, so they follow that check. + if err := config.ValidateConsumer(); err != nil { + return err + } + if err := config.ValidateJobs(); err != nil { + return err + } switch config.LogLevel { case "debug", "info", "warn", "error": default: @@ -125,6 +334,44 @@ func valueOrDefault(lookup LookupEnv, key, fallback string) string { return fallback } +// DatabaseURLFromEnv reads DATABASE_URL for commands that need only the +// database, such as the migration command. +func DatabaseURLFromEnv(lookup LookupEnv) string { + return strings.TrimSpace(valueOrDefault(lookup, "DATABASE_URL", "")) +} + +// boolOrDefault accepts only "true" or "false", ignoring case and surrounding +// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands, +// which are easy to mistype in deployment files. +func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) { + value, ok := lookup(key) + if !ok { + return fallback, nil + } + switch strings.ToLower(strings.TrimSpace(value)) { + case "true": + return true, nil + case "false": + return false, nil + default: + return false, fmt.Errorf("config.boolOrDefault - %s must be true or false", key) + } +} + +// intOrDefault parses a decimal integer, ignoring surrounding spaces. An empty +// value is an error rather than the default. +func intOrDefault(lookup LookupEnv, key string, fallback int) (int, error) { + value, ok := lookup(key) + if !ok { + return fallback, nil + } + number, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return 0, fmt.Errorf("config.intOrDefault - %s must be an integer", key) + } + return number, nil +} + func durationOrDefault(lookup LookupEnv, key string, fallback time.Duration) (time.Duration, error) { value, ok := lookup(key) if !ok { diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 4a0a349..5a0ef45 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -1,6 +1,7 @@ package config import ( + "slices" "strings" "testing" "time" @@ -20,26 +21,33 @@ func TestLoadFromEnvUsesOperationalDefaults(t *testing.T) { if config.DatabaseURL != "" { t.Fatalf("DatabaseURL = %q, want empty", config.DatabaseURL) } + if !config.DatabaseMigrateOnStart { + t.Fatal("DatabaseMigrateOnStart = false, want startup migrations enabled by default") + } if config.RedisAddr != "localhost:6379" || config.RedisDB != 0 || config.RedisTimeout != time.Second || config.RedisPassword != "" { t.Fatalf("unexpected Redis defaults") } if config.LogLevel != "info" { t.Fatalf("LogLevel = %q, want info", config.LogLevel) } + if !slices.Equal(config.KafkaBrokers, []string{"localhost:9092"}) { + t.Fatalf("KafkaBrokers = %q, want the localhost default", config.KafkaBrokers) + } } func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { values := map[string]string{ - "HTTP_ADDR": "127.0.0.1:18080", - "REDIS_ADDR": "cache:6379", - "REDIS_PASSWORD": " local-secret ", - "REDIS_DB": "2", - "REDIS_TIMEOUT": "500ms", - "METRICS_ADDR": "127.0.0.1:19090", - "DATABASE_URL": " postgres://app:secret@db/app ", - "LOG_LEVEL": " DEBUG ", - "READINESS_TIMEOUT": "2s", - "SHUTDOWN_TIMEOUT": "15s", + "HTTP_ADDR": "127.0.0.1:18080", + "REDIS_ADDR": "cache:6379", + "REDIS_PASSWORD": " local-secret ", + "REDIS_DB": "2", + "REDIS_TIMEOUT": "500ms", + "METRICS_ADDR": "127.0.0.1:19090", + "DATABASE_URL": " postgres://app:secret@db/app ", + "DATABASE_MIGRATE_ON_START": " FALSE ", + "LOG_LEVEL": " DEBUG ", + "READINESS_TIMEOUT": "2s", + "SHUTDOWN_TIMEOUT": "15s", } config, err := LoadFromEnv(testEnvironment(values)) if err != nil { @@ -54,6 +62,9 @@ func TestLoadFromEnvReadsAddressesAndTimeouts(t *testing.T) { if config.DatabaseURL != "postgres://app:secret@db/app" { t.Fatalf("DatabaseURL was not trimmed: %q", config.DatabaseURL) } + if config.DatabaseMigrateOnStart { + t.Fatal("DatabaseMigrateOnStart = true, want the explicit false value") + } if config.LogLevel != "debug" { t.Fatalf("LogLevel was not normalized: %q", config.LogLevel) } @@ -80,6 +91,10 @@ func TestLoadFromEnvRejectsInvalidSettings(t *testing.T) { {name: "negative Redis database", values: map[string]string{"REDIS_DB": "-1"}, want: "Config.ValidateRedis - REDIS_DB"}, {name: "invalid Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse REDIS_TIMEOUT"}, {name: "zero Redis timeout", values: map[string]string{"REDIS_TIMEOUT": "0s"}, want: "Config.ValidateRedis - REDIS_TIMEOUT"}, + {name: "invalid migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "sometimes"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "numeric migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "1"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "short migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": "t"}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, + {name: "empty migrate on start", values: map[string]string{"DATABASE_MIGRATE_ON_START": ""}, want: "config.boolOrDefault - DATABASE_MIGRATE_ON_START"}, {name: "invalid log level", values: map[string]string{"LOG_LEVEL": "trace"}, want: "Config.Validate - LOG_LEVEL"}, } for _, test := range tests { @@ -97,16 +112,30 @@ func testEnvironment(values map[string]string) LookupEnv { if value, ok := values[key]; ok { return value, true } + if key == "IDENTITY_KEY_SECRET" { + return "config-test-identity-key-secret-0123456789", true + } if key == "SEAWEEDFS_ACCESS_KEY" { return "test-access", true } if key == "SEAWEEDFS_SECRET_KEY" { return "test-secret", true } + if value, ok := mailFixture[key]; ok { + return value, true + } return "", false } } +// mailFixture is the smallest valid mail configuration. Mail tests override +// or remove entries to cover each transport. +var mailFixture = map[string]string{ + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "Lincodex ", + "APP_PUBLIC_URL": "http://localhost:8080", +} + func TestLoadFromEnvSeaweedFS(t *testing.T) { settings, err := LoadFromEnv(testEnvironment(nil)) if err != nil { @@ -169,3 +198,112 @@ func TestLoadFromEnvRejectsSeaweedFSSettings(t *testing.T) { }) } } + +func TestLoadFromEnvKafkaBrokers(t *testing.T) { + tests := []struct { + name string + value string + want []string + }{ + {name: "single Compose broker", value: "kafka:9092", want: []string{"kafka:9092"}}, + {name: "trimmed list", value: " kafka-1:9092 , 10.0.0.2:9093,[::1]:9094 ", want: []string{"kafka-1:9092", "10.0.0.2:9093", "[::1]:9094"}}, + {name: "fully qualified name", value: "broker_1.internal.example:9092", want: []string{"broker_1.internal.example:9092"}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"KAFKA_BROKERS": test.value})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !slices.Equal(settings.KafkaBrokers, test.want) { + t.Fatalf("KafkaBrokers = %q, want %q", settings.KafkaBrokers, test.want) + } + }) + } +} + +func TestLoadFromEnvRejectsKafkaBrokers(t *testing.T) { + tests := []struct { + name string + value string + want string + }{ + {name: "explicitly empty", value: "", want: "Config.ValidateKafka - KAFKA_BROKERS must not be empty"}, + {name: "only spaces", value: " ", want: "Config.ValidateKafka - KAFKA_BROKERS must not be empty"}, + {name: "missing port", value: "kafka", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "empty host", value: ":9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "zero port", value: "kafka:0", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "port out of range", value: "kafka:70000", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "named port", value: "kafka:broker", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "empty middle entry", value: "kafka-1:9092,,kafka-2:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 2"}, + {name: "trailing separator", value: "kafka:9092,", want: "Config.ValidateKafka - KAFKA_BROKERS entry 2"}, + {name: "URL scheme", value: "PLAINTEXT://kafka:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "user info", value: "user:secret@kafka:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "path", value: "kafka/events:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + {name: "label with leading hyphen", value: "-kafka:9092", want: "Config.ValidateKafka - KAFKA_BROKERS entry 1"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{"KAFKA_BROKERS": test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + if strings.Contains(err.Error(), "secret") { + t.Fatal("configuration error disclosed the broker value") + } + }) + } +} + +func TestLoadFromEnvKafkaTopicReplication(t *testing.T) { + tests := []struct { + name string + values map[string]string + replication, minInsync int16 + }{ + {name: "broker defaults", values: nil, replication: -1, minInsync: 0}, + {name: "explicit broker default", values: map[string]string{"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "-1"}, replication: -1, minInsync: 0}, + {name: "production cluster", values: map[string]string{ + "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "3", + "KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": " 2 ", + }, replication: 3, minInsync: 2}, + {name: "min ISR with broker default replication", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "2"}, replication: -1, minInsync: 2}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(test.values)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.KafkaEventsTopicReplicationFactor != test.replication || settings.KafkaEventsTopicMinInsyncReplicas != test.minInsync { + t.Fatalf("replication = %d, min ISR = %d; want %d and %d", settings.KafkaEventsTopicReplicationFactor, + settings.KafkaEventsTopicMinInsyncReplicas, test.replication, test.minInsync) + } + }) + } +} + +func TestLoadFromEnvRejectsKafkaTopicReplication(t *testing.T) { + tests := []struct { + name string + values map[string]string + want string + }{ + {name: "negative replication other than -1", values: map[string]string{"KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "-2"}, want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR"}, + {name: "empty min ISR", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": ""}, want: "config.intOrDefault - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS"}, + {name: "zero min ISR", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "0"}, want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS"}, + {name: "min ISR too large", values: map[string]string{"KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "32768"}, want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS"}, + {name: "min ISR above replication", values: map[string]string{ + "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "2", + "KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS": "3", + }, want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must not exceed"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(test.values)) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + }) + } +} diff --git a/backend/config/consumer.go b/backend/config/consumer.go new file mode 100644 index 0000000..abc2345 --- /dev/null +++ b/backend/config/consumer.go @@ -0,0 +1,169 @@ +package config + +import ( + "errors" + "fmt" + "strings" + "time" +) + +const ( + // The consumer runtime runs by default. It starts a consumer only for a + // registered handler, and none is registered yet. + defaultConsumerEnabled = true + // defaultConsumerGroupPrefix is joined with a consumer name by a dot to + // form the Kafka consumer group ID, for example "lincodex.". + defaultConsumerGroupPrefix = "lincodex" + // maxConsumerGroupPrefixLength leaves room for the consumer name in the + // group ID, which the code limits to 64 characters. + maxConsumerGroupPrefixLength = 128 + // defaultConsumerMaxAttempts bounds the handler attempts for one event + // before it is dead-lettered. + defaultConsumerMaxAttempts = 5 + maxConsumerMaxAttempts = 20 + // The wait after a failed attempt starts at the initial delay, doubles + // per consecutive failure, and stops growing at the maximum. + defaultConsumerBackoffInitial = 500 * time.Millisecond + defaultConsumerBackoffMax = 10 * time.Second + maxConsumerBackoff = 5 * time.Minute + // defaultConsumerHandlerTimeout bounds one transaction: the dedup marker, + // the handler, and the commit. It keeps the worst case of one record + // below the default rebalance timeout; see validateConsumerRebalance. + defaultConsumerHandlerTimeout = 5 * time.Second + minConsumerHandlerTimeout = 100 * time.Millisecond + maxConsumerHandlerTimeout = 5 * time.Minute + // defaultConsumerMaxPollRecords bounds the records of one poll, which a + // consumer processes while it holds group rebalancing. + defaultConsumerMaxPollRecords = 100 + maxConsumerMaxPollRecords = 10000 + // defaultConsumerCommitTimeout bounds one offset commit. + defaultConsumerCommitTimeout = 5 * time.Second + minConsumerCommitTimeout = 100 * time.Millisecond + maxConsumerCommitTimeout = time.Minute + // defaultConsumerShutdownGrace is how long the record in progress may + // continue after shutdown begins. + defaultConsumerShutdownGrace = 5 * time.Second + // defaultConsumerRebalanceTimeout is the franz-go and Kafka default, + // set explicitly so the budget check below uses the real value. + defaultConsumerRebalanceTimeout = time.Minute + minConsumerRebalanceTimeout = 10 * time.Second + maxConsumerRebalanceTimeout = 30 * time.Minute + // consumerRebalanceMargin covers the poll, the heartbeat that notices + // the rebalance, and scheduling, on top of the worst case of one record. + consumerRebalanceMargin = 5 * time.Second +) + +func (config *Config) loadConsumer(lookup LookupEnv) error { + var err error + if config.ConsumerEnabled, err = boolOrDefault(lookup, "CONSUMER_ENABLED", defaultConsumerEnabled); err != nil { + return err + } + config.ConsumerGroupPrefix = strings.TrimSpace(valueOrDefault(lookup, "CONSUMER_GROUP_PREFIX", defaultConsumerGroupPrefix)) + if config.ConsumerMaxAttempts, err = intOrDefault(lookup, "CONSUMER_MAX_ATTEMPTS", defaultConsumerMaxAttempts); err != nil { + return err + } + if config.ConsumerBackoffInitial, err = durationOrDefault(lookup, "CONSUMER_BACKOFF_INITIAL", defaultConsumerBackoffInitial); err != nil { + return err + } + if config.ConsumerBackoffMax, err = durationOrDefault(lookup, "CONSUMER_BACKOFF_MAX", defaultConsumerBackoffMax); err != nil { + return err + } + if config.ConsumerHandlerTimeout, err = durationOrDefault(lookup, "CONSUMER_HANDLER_TIMEOUT", defaultConsumerHandlerTimeout); err != nil { + return err + } + if config.ConsumerMaxPollRecords, err = intOrDefault(lookup, "CONSUMER_MAX_POLL_RECORDS", defaultConsumerMaxPollRecords); err != nil { + return err + } + if config.ConsumerCommitTimeout, err = durationOrDefault(lookup, "CONSUMER_COMMIT_TIMEOUT", defaultConsumerCommitTimeout); err != nil { + return err + } + if config.ConsumerShutdownGrace, err = durationOrDefault(lookup, "CONSUMER_SHUTDOWN_GRACE", defaultConsumerShutdownGrace); err != nil { + return err + } + config.ConsumerRebalanceTimeout, err = durationOrDefault(lookup, "CONSUMER_REBALANCE_TIMEOUT", defaultConsumerRebalanceTimeout) + return err +} + +// ValidateConsumer checks the consumer settings even when consumers are +// disabled, so enabling them later cannot surface an old mistake. +func (config Config) ValidateConsumer() error { + // A group ID allows any characters, but the prefix also appears in logs + // and broker ACLs, so it follows the topic name rules. + if len(config.ConsumerGroupPrefix) > maxConsumerGroupPrefixLength || !kafkaTopicNamePattern.MatchString(config.ConsumerGroupPrefix) { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_GROUP_PREFIX must be 1 to %d letters, digits, dots, underscores, or hyphens", maxConsumerGroupPrefixLength) + } + if err := config.validateConsumerRetries(); err != nil { + return err + } + if err := config.validateConsumerTimeouts(); err != nil { + return err + } + return config.validateConsumerRebalance() +} + +func (config Config) validateConsumerRetries() error { + if config.ConsumerMaxAttempts < 1 || config.ConsumerMaxAttempts > maxConsumerMaxAttempts { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS must be between 1 and %d", maxConsumerMaxAttempts) + } + if config.ConsumerBackoffInitial <= 0 { + return errors.New("Config.ValidateConsumer - CONSUMER_BACKOFF_INITIAL must be positive") + } + if config.ConsumerBackoffMax < config.ConsumerBackoffInitial || config.ConsumerBackoffMax > maxConsumerBackoff { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_BACKOFF_MAX must be between CONSUMER_BACKOFF_INITIAL and %s", maxConsumerBackoff) + } + if config.ConsumerMaxPollRecords < 1 || config.ConsumerMaxPollRecords > maxConsumerMaxPollRecords { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS must be between 1 and %d", maxConsumerMaxPollRecords) + } + return nil +} + +func (config Config) validateConsumerTimeouts() error { + if config.ConsumerHandlerTimeout < minConsumerHandlerTimeout || config.ConsumerHandlerTimeout > maxConsumerHandlerTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT must be between %s and %s", minConsumerHandlerTimeout, maxConsumerHandlerTimeout) + } + if config.ConsumerCommitTimeout < minConsumerCommitTimeout || config.ConsumerCommitTimeout > maxConsumerCommitTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT must be between %s and %s", minConsumerCommitTimeout, maxConsumerCommitTimeout) + } + // The grace runs while the HTTP servers drain, so it must fit in the + // shutdown budget of the process. + if config.ConsumerShutdownGrace <= 0 || config.ConsumerShutdownGrace > config.ShutdownTimeout { + return errors.New("Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE must be positive and at most SHUTDOWN_TIMEOUT") + } + return nil +} + +// validateConsumerRebalance keeps the slowest record below the rebalance +// timeout. A consumer holds group rebalancing while it processes a poll and +// commits after every record that needed a retry, so one record is the unit +// that must fit: every handler attempt, the longest wait before each retry, +// the dead letter write, and the offset commit. A member that exceeds the +// timeout is removed from the group, and its records are processed again. +// Database outages are not part of the budget: they are retried without a +// bound, and the removal they can cause is harmless because of the markers. +func (config Config) validateConsumerRebalance() error { + if config.ConsumerRebalanceTimeout < minConsumerRebalanceTimeout || config.ConsumerRebalanceTimeout > maxConsumerRebalanceTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between %s and %s", minConsumerRebalanceTimeout, maxConsumerRebalanceTimeout) + } + worstRecord := config.consumerRecordBudget() + if worstRecord+consumerRebalanceMargin > config.ConsumerRebalanceTimeout { + return fmt.Errorf("Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed the worst case of one record (%s) by %s; lower CONSUMER_MAX_ATTEMPTS, CONSUMER_HANDLER_TIMEOUT, CONSUMER_BACKOFF_MAX, or CONSUMER_COMMIT_TIMEOUT, or raise the timeout", + worstRecord, consumerRebalanceMargin) + } + return nil +} + +// consumerRecordBudget is the longest time one record can take without a +// database outage: CONSUMER_MAX_ATTEMPTS handler attempts, the longest +// backoff before each retry, one dead letter write, and one offset commit. +// The backoff ceiling starts at CONSUMER_BACKOFF_INITIAL and doubles up to +// CONSUMER_BACKOFF_MAX, as the workers' retry.Backoff does. +func (config Config) consumerRecordBudget() time.Duration { + attempts := config.ConsumerMaxAttempts + budget := time.Duration(attempts+1) * config.ConsumerHandlerTimeout + ceiling := min(config.ConsumerBackoffInitial, config.ConsumerBackoffMax) + for retry := 1; retry < attempts; retry++ { + budget += ceiling + ceiling = min(ceiling*2, config.ConsumerBackoffMax) + } + return budget + config.ConsumerCommitTimeout +} diff --git a/backend/config/consumer_test.go b/backend/config/consumer_test.go new file mode 100644 index 0000000..dca2557 --- /dev/null +++ b/backend/config/consumer_test.go @@ -0,0 +1,126 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvConsumerDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !settings.ConsumerEnabled || settings.ConsumerGroupPrefix != "lincodex" || settings.ConsumerMaxAttempts != 5 || + settings.ConsumerBackoffInitial != 500*time.Millisecond || settings.ConsumerBackoffMax != 10*time.Second || + settings.ConsumerHandlerTimeout != 5*time.Second || settings.ConsumerMaxPollRecords != 100 || + settings.ConsumerCommitTimeout != 5*time.Second || settings.ConsumerShutdownGrace != 5*time.Second || + settings.ConsumerRebalanceTimeout != time.Minute { + t.Fatalf("unexpected consumer defaults: %+v", consumerSettings(settings)) + } + // Six handler timeouts (five attempts and the dead letter write), the + // backoff ceilings 0.5s, 1s, 2s, and 4s, and one commit; the deployment + // guide quotes this value. + if budget := settings.consumerRecordBudget(); budget != 42500*time.Millisecond { + t.Fatalf("default record budget = %s, want 42.5s", budget) + } +} + +func TestLoadFromEnvReadsConsumerSettings(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "CONSUMER_ENABLED": " False ", + "CONSUMER_GROUP_PREFIX": " stand-1.lincodex ", + "CONSUMER_MAX_ATTEMPTS": "20", + "CONSUMER_BACKOFF_INITIAL": "1s", + "CONSUMER_BACKOFF_MAX": "1s", + "CONSUMER_HANDLER_TIMEOUT": "100ms", + "CONSUMER_MAX_POLL_RECORDS": "10000", + "CONSUMER_COMMIT_TIMEOUT": "1m", + "CONSUMER_SHUTDOWN_GRACE": "20s", + "SHUTDOWN_TIMEOUT": "20s", + // 21 handler timeouts, 19 waits of 1s, and one commit fit easily. + "CONSUMER_REBALANCE_TIMEOUT": "10m", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.ConsumerEnabled || settings.ConsumerGroupPrefix != "stand-1.lincodex" || settings.ConsumerMaxAttempts != 20 || + settings.ConsumerBackoffInitial != time.Second || settings.ConsumerBackoffMax != time.Second || + settings.ConsumerRebalanceTimeout != 10*time.Minute || + settings.ConsumerHandlerTimeout != 100*time.Millisecond || settings.ConsumerMaxPollRecords != 10000 || + settings.ConsumerCommitTimeout != time.Minute || settings.ConsumerShutdownGrace != 20*time.Second { + t.Fatalf("consumer settings were not loaded: %+v", consumerSettings(settings)) + } +} + +func TestLoadFromEnvRejectsConsumerSettings(t *testing.T) { + tests := []struct { + key, value, want string + }{ + {key: "CONSUMER_ENABLED", value: "on", want: "config.boolOrDefault - CONSUMER_ENABLED"}, + {key: "CONSUMER_GROUP_PREFIX", value: "", want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"}, + {key: "CONSUMER_GROUP_PREFIX", value: "group/secret", want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"}, + {key: "CONSUMER_GROUP_PREFIX", value: strings.Repeat("g", 129), want: "Config.ValidateConsumer - CONSUMER_GROUP_PREFIX"}, + {key: "CONSUMER_MAX_ATTEMPTS", value: "", want: "config.intOrDefault - CONSUMER_MAX_ATTEMPTS"}, + {key: "CONSUMER_MAX_ATTEMPTS", value: "0", want: "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS"}, + {key: "CONSUMER_MAX_ATTEMPTS", value: "21", want: "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS"}, + {key: "CONSUMER_BACKOFF_INITIAL", value: "soon", want: "config.durationOrDefault - parse CONSUMER_BACKOFF_INITIAL"}, + {key: "CONSUMER_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_INITIAL"}, + {key: "CONSUMER_BACKOFF_INITIAL", value: "11s", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_MAX"}, + {key: "CONSUMER_BACKOFF_MAX", value: "6m", want: "Config.ValidateConsumer - CONSUMER_BACKOFF_MAX"}, + {key: "CONSUMER_HANDLER_TIMEOUT", value: "99ms", want: "Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT"}, + {key: "CONSUMER_HANDLER_TIMEOUT", value: "6m", want: "Config.ValidateConsumer - CONSUMER_HANDLER_TIMEOUT"}, + {key: "CONSUMER_MAX_POLL_RECORDS", value: "0", want: "Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS"}, + {key: "CONSUMER_MAX_POLL_RECORDS", value: "10001", want: "Config.ValidateConsumer - CONSUMER_MAX_POLL_RECORDS"}, + {key: "CONSUMER_COMMIT_TIMEOUT", value: "99ms", want: "Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT"}, + {key: "CONSUMER_COMMIT_TIMEOUT", value: "61s", want: "Config.ValidateConsumer - CONSUMER_COMMIT_TIMEOUT"}, + {key: "CONSUMER_SHUTDOWN_GRACE", value: "0s", want: "Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE"}, + // Longer than the default SHUTDOWN_TIMEOUT of 10s. + {key: "CONSUMER_SHUTDOWN_GRACE", value: "11s", want: "Config.ValidateConsumer - CONSUMER_SHUTDOWN_GRACE"}, + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "soon", want: "config.durationOrDefault - parse CONSUMER_REBALANCE_TIMEOUT"}, + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "9s", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between"}, + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "31m", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must be between"}, + // The default 42.5s budget plus the 5s margin exceeds 45s. + {key: "CONSUMER_REBALANCE_TIMEOUT", value: "45s", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed"}, + // Twenty attempts with the default timeouts need several minutes. + {key: "CONSUMER_MAX_ATTEMPTS", value: "20", want: "Config.ValidateConsumer - CONSUMER_REBALANCE_TIMEOUT must exceed"}, + } + for _, test := range tests { + t.Run(test.key+"/"+test.value, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + if strings.Contains(err.Error(), "secret") { + t.Fatal("configuration error disclosed the value") + } + }) + } +} + +func TestValidateConsumerChecksSettingsEvenWhenDisabled(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"CONSUMER_ENABLED": "false"})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + settings.ConsumerMaxAttempts = 0 + if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateConsumer - CONSUMER_MAX_ATTEMPTS") { + t.Fatalf("Validate() error = %v, want the consumer attempts error", err) + } +} + +// consumerSettings collects the consumer fields for failure messages. +func consumerSettings(settings Config) map[string]any { + return map[string]any{ + "enabled": settings.ConsumerEnabled, + "group_prefix": settings.ConsumerGroupPrefix, + "max_attempts": settings.ConsumerMaxAttempts, + "backoff_initial": settings.ConsumerBackoffInitial, + "backoff_max": settings.ConsumerBackoffMax, + "handler_timeout": settings.ConsumerHandlerTimeout, + "max_poll": settings.ConsumerMaxPollRecords, + "commit_timeout": settings.ConsumerCommitTimeout, + "shutdown_grace": settings.ConsumerShutdownGrace, + "rebalance": settings.ConsumerRebalanceTimeout, + } +} diff --git a/backend/config/identity.go b/backend/config/identity.go new file mode 100644 index 0000000..83afab2 --- /dev/null +++ b/backend/config/identity.go @@ -0,0 +1,173 @@ +package config + +import ( + "errors" + "fmt" + "strings" + "time" +) + +const ( + // defaultVerificationMailMinInterval is the shortest time between two + // verification messages to one address, counting the registration and + // every resend. + defaultVerificationMailMinInterval = time.Minute + // minVerificationMailMinInterval and maxVerificationMailMinInterval bound + // the setting: a shorter interval is no brake, a longer one is a + // lock-out that a person who mistyped cannot wait out. + minVerificationMailMinInterval = time.Second + maxVerificationMailMinInterval = time.Hour + // defaultVerificationMailDailyLimit is the number of verification + // messages to one address per 24 hours. + defaultVerificationMailDailyLimit = 5 + maxVerificationMailDailyLimit = 50 + // defaultIdentityClientHourlyLimit is the number of registration, + // confirmation, resend, and login attempts per client network address per + // hour. It is a brake on one source reaching many addresses; the per-address + // limits above protect one address from many sources. + defaultIdentityClientHourlyLimit = 30 + maxIdentityClientHourlyLimit = 10000 + // Login limits count attempts against both the client and normalized + // address buckets, regardless of whether the address has an account. + defaultIdentityLoginEmailHourlyLimit = 10 + maxIdentityLoginEmailHourlyLimit = 10000 + defaultIdentitySessionIdleTimeout = 24 * time.Hour + defaultIdentitySessionAbsoluteLifetime = 7 * 24 * time.Hour + minIdentitySessionTimeout = time.Minute + maxIdentitySessionIdleTimeout = 30 * 24 * time.Hour + maxIdentitySessionAbsoluteLifetime = 365 * 24 * time.Hour + // MinIdentityKeySecretBytes is the shortest accepted IDENTITY_KEY_SECRET. + MinIdentityKeySecretBytes = 32 + // examplePlaceholderPrefix starts the placeholder values of the example + // environment file; a secret that keeps it is public. + examplePlaceholderPrefix = "replace-this" +) + +// loadIdentity reads the identity settings. IDENTITY_KEY_SECRET is +// required: without it ValidateIdentity refuses the configuration, unless +// IDENTITY_ALLOW_EPHEMERAL_KEY is true, which lets a development stand draw a +// random secret for the life of the process, so idempotency records and rate +// limit buckets change and session CSRF tokens differ after a restart. +// +// Limit and timeout settings treat an empty value as unset, as the mail quota +// does: Compose passes an unset variable as an empty string. +func (config *Config) loadIdentity(lookup LookupEnv) error { + config.IdentityKeySecret = strings.TrimSpace(valueOrDefault(lookup, "IDENTITY_KEY_SECRET", "")) + var err error + config.IdentityAllowEphemeralKey, err = boolOrDefault(lookup, "IDENTITY_ALLOW_EPHEMERAL_KEY", false) + if err != nil { + return err + } + setOnly := func(key string) (string, bool) { + value, ok := lookup(key) + if strings.TrimSpace(value) == "" { + return "", false + } + return value, ok + } + config.VerificationMailMinInterval, err = durationOrDefault(setOnly, "VERIFICATION_MAIL_MIN_INTERVAL", defaultVerificationMailMinInterval) + if err != nil { + return err + } + config.VerificationMailDailyLimit, err = intOrDefault(setOnly, "VERIFICATION_MAIL_DAILY_LIMIT", defaultVerificationMailDailyLimit) + if err != nil { + return err + } + if config.IdentityClientHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_CLIENT_HOURLY_LIMIT", defaultIdentityClientHourlyLimit); err != nil { + return err + } + if config.IdentityLoginEmailHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT", defaultIdentityLoginEmailHourlyLimit); err != nil { + return err + } + if config.IdentitySessionIdleTimeout, err = durationOrDefault(setOnly, "IDENTITY_SESSION_IDLE_TIMEOUT", defaultIdentitySessionIdleTimeout); err != nil { + return err + } + config.IdentitySessionAbsoluteLifetime, err = durationOrDefault(setOnly, "IDENTITY_SESSION_ABSOLUTE_LIFETIME", defaultIdentitySessionAbsoluteLifetime) + return err +} + +// IdentityKeySecretFromEnv reads IDENTITY_KEY_SECRET for an operator command +// that recomputes keyed values of the server, such as the codes of the leak +// trace. It never draws an ephemeral secret: a random one would make every +// value unreadable, and a command that silently searched with it would report +// nothing found. The error never contains the secret. +func IdentityKeySecretFromEnv(lookup LookupEnv) ([]byte, error) { + secret := strings.TrimSpace(valueOrDefault(lookup, "IDENTITY_KEY_SECRET", "")) + switch { + case secret == "": + return nil, errors.New("config.IdentityKeySecretFromEnv - IDENTITY_KEY_SECRET is not set") + case strings.HasPrefix(secret, examplePlaceholderPrefix): + return nil, errors.New("config.IdentityKeySecretFromEnv - IDENTITY_KEY_SECRET is an example placeholder") + case len(secret) < MinIdentityKeySecretBytes: + return nil, fmt.Errorf("config.IdentityKeySecretFromEnv - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes) + } + return []byte(secret), nil +} + +// ValidateIdentity checks the registration settings. Errors never include +// the secret. +func (config Config) ValidateIdentity() error { + if err := config.validateIdentitySecret(); err != nil { + return err + } + if err := config.validateVerificationMailSettings(); err != nil { + return err + } + if err := config.validateIdentityLimits(); err != nil { + return err + } + return config.validateSessionTimeouts() +} + +func (config Config) validateIdentitySecret() error { + if config.IdentityKeySecret == "" && !config.IdentityAllowEphemeralKey { + return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is required (generate one with: openssl rand -base64 48); " + + "set IDENTITY_ALLOW_EPHEMERAL_KEY=true only on a development stand") + } + if strings.HasPrefix(config.IdentityKeySecret, examplePlaceholderPrefix) { + return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is an example placeholder; generate a real one with: openssl rand -base64 48") + } + if config.IdentityKeySecret != "" && len(config.IdentityKeySecret) < MinIdentityKeySecretBytes { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes) + } + return nil +} + +func (config Config) validateVerificationMailSettings() error { + if config.VerificationMailMinInterval < minVerificationMailMinInterval || config.VerificationMailMinInterval > maxVerificationMailMinInterval { + return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be between %s and %s", + minVerificationMailMinInterval, maxVerificationMailMinInterval) + } + if config.VerificationMailDailyLimit < 1 || config.VerificationMailDailyLimit > maxVerificationMailDailyLimit { + return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT must be between 1 and %d", maxVerificationMailDailyLimit) + } + if config.VerificationMailMinInterval >= 24*time.Hour { + return errors.New("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be shorter than the daily window") + } + return nil +} + +func (config Config) validateIdentityLimits() error { + if config.IdentityClientHourlyLimit < 1 || config.IdentityClientHourlyLimit > maxIdentityClientHourlyLimit { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT must be between 1 and %d", maxIdentityClientHourlyLimit) + } + if config.IdentityLoginEmailHourlyLimit < 1 || config.IdentityLoginEmailHourlyLimit > maxIdentityLoginEmailHourlyLimit { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT must be between 1 and %d", maxIdentityLoginEmailHourlyLimit) + } + return nil +} + +func (config Config) validateSessionTimeouts() error { + if config.IdentitySessionIdleTimeout < minIdentitySessionTimeout || config.IdentitySessionIdleTimeout > maxIdentitySessionIdleTimeout { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT must be between %s and %s", + minIdentitySessionTimeout, maxIdentitySessionIdleTimeout) + } + if config.IdentitySessionAbsoluteLifetime < minIdentitySessionTimeout || config.IdentitySessionAbsoluteLifetime > maxIdentitySessionAbsoluteLifetime { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_SESSION_ABSOLUTE_LIFETIME must be between %s and %s", + minIdentitySessionTimeout, maxIdentitySessionAbsoluteLifetime) + } + if config.IdentitySessionIdleTimeout > config.IdentitySessionAbsoluteLifetime { + return errors.New("Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT must not exceed IDENTITY_SESSION_ABSOLUTE_LIFETIME") + } + return nil +} diff --git a/backend/config/identity_test.go b/backend/config/identity_test.go new file mode 100644 index 0000000..b742896 --- /dev/null +++ b/backend/config/identity_test.go @@ -0,0 +1,160 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvIdentityDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_ALLOW_EPHEMERAL_KEY": "true", "IDENTITY_KEY_SECRET": ""})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.IdentityKeySecret != "" || + settings.VerificationMailMinInterval != time.Minute || + settings.VerificationMailDailyLimit != 5 || + settings.IdentityClientHourlyLimit != 30 || settings.IdentityLoginEmailHourlyLimit != 10 || + settings.IdentitySessionIdleTimeout != 24*time.Hour || settings.IdentitySessionAbsoluteLifetime != 7*24*time.Hour { + t.Fatalf("identity defaults = %+v", settings) + } +} + +func TestLoadFromEnvIdentityExplicit(t *testing.T) { + secret := strings.Repeat("k", MinIdentityKeySecretBytes) + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "IDENTITY_KEY_SECRET": " " + secret + " ", + "VERIFICATION_MAIL_MIN_INTERVAL": "90s", + "VERIFICATION_MAIL_DAILY_LIMIT": "3", + "IDENTITY_CLIENT_HOURLY_LIMIT": "100", + "IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT": "12", + "IDENTITY_SESSION_IDLE_TIMEOUT": "12h", + "IDENTITY_SESSION_ABSOLUTE_LIFETIME": "72h", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.IdentityKeySecret != secret || settings.VerificationMailMinInterval != 90*time.Second || + settings.VerificationMailDailyLimit != 3 || settings.IdentityClientHourlyLimit != 100 || + settings.IdentityLoginEmailHourlyLimit != 12 || settings.IdentitySessionIdleTimeout != 12*time.Hour || + settings.IdentitySessionAbsoluteLifetime != 72*time.Hour { + t.Fatalf("identity settings were not read: %+v", settings) + } +} + +func TestLoadFromEnvRejectsIdentitySettings(t *testing.T) { + tests := map[string]struct { + key, value, want string + }{ + "short secret": {"IDENTITY_KEY_SECRET", "too-short", "Config.ValidateIdentity - IDENTITY_KEY_SECRET"}, + "interval below": {"VERIFICATION_MAIL_MIN_INTERVAL", "500ms", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"}, + "interval above": {"VERIFICATION_MAIL_MIN_INTERVAL", "2h", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"}, + "interval malformed": {"VERIFICATION_MAIL_MIN_INTERVAL", "soon", "config.durationOrDefault - parse VERIFICATION_MAIL_MIN_INTERVAL"}, + "daily zero": {"VERIFICATION_MAIL_DAILY_LIMIT", "0", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"}, + "daily too high": {"VERIFICATION_MAIL_DAILY_LIMIT", "51", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"}, + "daily malformed": {"VERIFICATION_MAIL_DAILY_LIMIT", "five", "config.intOrDefault - VERIFICATION_MAIL_DAILY_LIMIT"}, + "client zero": {"IDENTITY_CLIENT_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT"}, + "login email zero": {"IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT"}, + "login email malformed": {"IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT", "ten", "config.intOrDefault - IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT"}, + "session idle too short": {"IDENTITY_SESSION_IDLE_TIMEOUT", "30s", "Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT"}, + "session idle too long": {"IDENTITY_SESSION_IDLE_TIMEOUT", "744h", "Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT"}, + "session absolute too long": {"IDENTITY_SESSION_ABSOLUTE_LIFETIME", "8784h", "Config.ValidateIdentity - IDENTITY_SESSION_ABSOLUTE_LIFETIME"}, + } + for name, test := range tests { + _, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want) + } + } +} + +func TestIdentitySessionIdleTimeoutDoesNotExceedAbsoluteLifetime(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{ + "IDENTITY_SESSION_IDLE_TIMEOUT": "25h", + "IDENTITY_SESSION_ABSOLUTE_LIFETIME": "24h", + })) + if err == nil || !strings.Contains(err.Error(), "IDENTITY_SESSION_IDLE_TIMEOUT must not exceed IDENTITY_SESSION_ABSOLUTE_LIFETIME") { + t.Fatalf("LoadFromEnv() error = %v, want idle timeout bounded by absolute lifetime", err) + } +} + +func TestIdentityErrorsDoNotQuoteTheSecret(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": "short-secret-value"})) + if err == nil || strings.Contains(err.Error(), "short-secret-value") { + t.Fatalf("LoadFromEnv() error = %v, want an error without the secret", err) + } +} + +func TestLoadFromEnvIdentityEmptyLimitsMeanUnset(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "VERIFICATION_MAIL_MIN_INTERVAL": "", + "VERIFICATION_MAIL_DAILY_LIMIT": " ", + "IDENTITY_CLIENT_HOURLY_LIMIT": "", + "IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT": "", + "IDENTITY_SESSION_IDLE_TIMEOUT": "", + "IDENTITY_SESSION_ABSOLUTE_LIFETIME": "", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.VerificationMailMinInterval != time.Minute || settings.VerificationMailDailyLimit != 5 || + settings.IdentityClientHourlyLimit != 30 || settings.IdentityLoginEmailHourlyLimit != 10 || + settings.IdentitySessionIdleTimeout != 24*time.Hour || settings.IdentitySessionAbsoluteLifetime != 7*24*time.Hour { + t.Fatalf("empty identity limits = %+v, want the defaults", settings) + } +} + +func TestLoadFromEnvRequiresTheIdentityKeySecret(t *testing.T) { + // Not through testEnvironment, which supplies a secret. + lookup := func(key string) (string, bool) { + if key == "IDENTITY_KEY_SECRET" || key == "IDENTITY_ALLOW_EPHEMERAL_KEY" { + return "", false + } + return testEnvironment(nil)(key) + } + _, err := LoadFromEnv(lookup) + if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET is required") || !strings.Contains(err.Error(), "openssl rand") { + t.Fatalf("LoadFromEnv() error = %v, want the missing secret named with how to generate one", err) + } + ephemeral := func(key string) (string, bool) { + if key == "IDENTITY_ALLOW_EPHEMERAL_KEY" { + return "true", true + } + return lookup(key) + } + settings, err := LoadFromEnv(ephemeral) + if err != nil || !settings.IdentityAllowEphemeralKey { + t.Fatalf("LoadFromEnv(ephemeral) = %v, %v, want an accepted development configuration", settings.IdentityAllowEphemeralKey, err) + } +} + +func TestLoadFromEnvRejectsThePlaceholderSecret(t *testing.T) { + const placeholder = "replace-this-identity-key-secret-0123456789abcdef" + _, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": placeholder})) + if err == nil || !strings.Contains(err.Error(), "example placeholder") || strings.Contains(err.Error(), placeholder) { + t.Fatalf("LoadFromEnv() error = %v, want a refusal that does not quote the value", err) + } +} + +func TestIdentityKeySecretFromEnvRefusesWhatTheServerCouldNotUseAndNeverEchoesIt(t *testing.T) { + secret := strings.Repeat("s", MinIdentityKeySecretBytes) + got, err := IdentityKeySecretFromEnv(func(key string) (string, bool) { return " " + secret + " ", key == "IDENTITY_KEY_SECRET" }) + if err != nil || string(got) != secret { + t.Fatalf("IdentityKeySecretFromEnv(valid) = %q, %v, want the trimmed secret", got, err) + } + for name, value := range map[string]string{ + "unset": "", + "placeholder": "replace-this-with-a-generated-secret-of-enough-length", + "too short": "short-secret", + } { + t.Run(name, func(t *testing.T) { + _, err := IdentityKeySecretFromEnv(func(key string) (string, bool) { return value, key == "IDENTITY_KEY_SECRET" && value != "" }) + if err == nil { + t.Fatal("IdentityKeySecretFromEnv() succeeded, want an error") + } + if value != "" && strings.Contains(err.Error(), value) { + t.Fatalf("the error contains the secret: %v", err) + } + }) + } +} diff --git a/backend/config/jobs.go b/backend/config/jobs.go new file mode 100644 index 0000000..b9d1f87 --- /dev/null +++ b/backend/config/jobs.go @@ -0,0 +1,99 @@ +package config + +import ( + "errors" + "fmt" + "time" +) + +const ( + // The scheduled job worker runs by default. It starts only when a job + // handler is registered and DATABASE_URL is set. + defaultJobsEnabled = true + // defaultJobsPollInterval is the wait after a pass that claimed less + // than a batch. It is also the usual lateness of a job after its due + // time. + defaultJobsPollInterval = time.Second + minJobsPollInterval = 10 * time.Millisecond + maxJobsPollInterval = 5 * time.Minute + // defaultJobsBatchSize bounds the jobs one claim leases. A worker runs + // them one after another under leases taken together, so a batch stays + // small next to the lease. + defaultJobsBatchSize = 10 + maxJobsBatchSize = 100 + // defaultJobsLeaseDuration is how long a claimed job belongs to one + // worker. It bounds one handler attempt, and a worker that crashed + // delays its jobs by at most this long. + defaultJobsLeaseDuration = time.Minute + minJobsLeaseDuration = time.Second + maxJobsLeaseDuration = time.Hour + // defaultJobsMaxAttempts bounds the attempts of a job scheduled without + // its own limit before it is dead. + defaultJobsMaxAttempts = 5 + // maxJobsMaxAttempts matches the database bound on a per-job limit. + maxJobsMaxAttempts = 100 + // A failed job is retried after a delay that starts at the initial + // value, doubles per failed attempt, and stops growing at the maximum. + defaultJobsBackoffInitial = time.Second + defaultJobsBackoffMax = 5 * time.Minute + maxJobsBackoff = 24 * time.Hour + // defaultJobsShutdownGrace is how long the job in progress may continue + // after shutdown begins. + defaultJobsShutdownGrace = 5 * time.Second +) + +func (config *Config) loadJobs(lookup LookupEnv) error { + var err error + if config.JobsEnabled, err = boolOrDefault(lookup, "JOBS_ENABLED", defaultJobsEnabled); err != nil { + return err + } + if config.JobsPollInterval, err = durationOrDefault(lookup, "JOBS_POLL_INTERVAL", defaultJobsPollInterval); err != nil { + return err + } + if config.JobsBatchSize, err = intOrDefault(lookup, "JOBS_BATCH_SIZE", defaultJobsBatchSize); err != nil { + return err + } + if config.JobsLeaseDuration, err = durationOrDefault(lookup, "JOBS_LEASE_DURATION", defaultJobsLeaseDuration); err != nil { + return err + } + if config.JobsMaxAttempts, err = intOrDefault(lookup, "JOBS_MAX_ATTEMPTS", defaultJobsMaxAttempts); err != nil { + return err + } + if config.JobsBackoffInitial, err = durationOrDefault(lookup, "JOBS_BACKOFF_INITIAL", defaultJobsBackoffInitial); err != nil { + return err + } + if config.JobsBackoffMax, err = durationOrDefault(lookup, "JOBS_BACKOFF_MAX", defaultJobsBackoffMax); err != nil { + return err + } + config.JobsShutdownGrace, err = durationOrDefault(lookup, "JOBS_SHUTDOWN_GRACE", defaultJobsShutdownGrace) + return err +} + +// ValidateJobs checks the scheduled job settings even when the worker is +// disabled, so enabling it later cannot surface an old mistake. +func (config Config) ValidateJobs() error { + if config.JobsPollInterval < minJobsPollInterval || config.JobsPollInterval > maxJobsPollInterval { + return fmt.Errorf("Config.ValidateJobs - JOBS_POLL_INTERVAL must be between %s and %s", minJobsPollInterval, maxJobsPollInterval) + } + if config.JobsBatchSize < 1 || config.JobsBatchSize > maxJobsBatchSize { + return fmt.Errorf("Config.ValidateJobs - JOBS_BATCH_SIZE must be between 1 and %d", maxJobsBatchSize) + } + if config.JobsLeaseDuration < minJobsLeaseDuration || config.JobsLeaseDuration > maxJobsLeaseDuration { + return fmt.Errorf("Config.ValidateJobs - JOBS_LEASE_DURATION must be between %s and %s", minJobsLeaseDuration, maxJobsLeaseDuration) + } + if config.JobsMaxAttempts < 1 || config.JobsMaxAttempts > maxJobsMaxAttempts { + return fmt.Errorf("Config.ValidateJobs - JOBS_MAX_ATTEMPTS must be between 1 and %d", maxJobsMaxAttempts) + } + if config.JobsBackoffInitial <= 0 { + return errors.New("Config.ValidateJobs - JOBS_BACKOFF_INITIAL must be positive") + } + if config.JobsBackoffMax < config.JobsBackoffInitial || config.JobsBackoffMax > maxJobsBackoff { + return fmt.Errorf("Config.ValidateJobs - JOBS_BACKOFF_MAX must be between JOBS_BACKOFF_INITIAL and %s", maxJobsBackoff) + } + // The grace runs while the HTTP servers drain, so it must fit in the + // shutdown budget of the process. + if config.JobsShutdownGrace <= 0 || config.JobsShutdownGrace > config.ShutdownTimeout { + return errors.New("Config.ValidateJobs - JOBS_SHUTDOWN_GRACE must be positive and at most SHUTDOWN_TIMEOUT") + } + return nil +} diff --git a/backend/config/jobs_test.go b/backend/config/jobs_test.go new file mode 100644 index 0000000..0e583ed --- /dev/null +++ b/backend/config/jobs_test.go @@ -0,0 +1,101 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvJobsDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !settings.JobsEnabled || settings.JobsPollInterval != time.Second || settings.JobsBatchSize != 10 || + settings.JobsLeaseDuration != time.Minute || settings.JobsMaxAttempts != 5 || + settings.JobsBackoffInitial != time.Second || settings.JobsBackoffMax != 5*time.Minute || + settings.JobsShutdownGrace != 5*time.Second { + t.Fatalf("unexpected job defaults: %+v", jobSettings(settings)) + } +} + +func TestLoadFromEnvReadsJobSettings(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "JOBS_ENABLED": " FALSE ", + "JOBS_POLL_INTERVAL": "10ms", + "JOBS_BATCH_SIZE": " 100 ", + "JOBS_LEASE_DURATION": "1h", + "JOBS_MAX_ATTEMPTS": "100", + "JOBS_BACKOFF_INITIAL": "2s", + "JOBS_BACKOFF_MAX": "24h", + "JOBS_SHUTDOWN_GRACE": "20s", + "SHUTDOWN_TIMEOUT": "20s", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.JobsEnabled || settings.JobsPollInterval != 10*time.Millisecond || settings.JobsBatchSize != 100 || + settings.JobsLeaseDuration != time.Hour || settings.JobsMaxAttempts != 100 || + settings.JobsBackoffInitial != 2*time.Second || settings.JobsBackoffMax != 24*time.Hour || + settings.JobsShutdownGrace != 20*time.Second { + t.Fatalf("job settings were not loaded: %+v", jobSettings(settings)) + } +} + +func TestLoadFromEnvRejectsJobSettings(t *testing.T) { + tests := []struct { + key, value, want string + }{ + {key: "JOBS_ENABLED", value: "yes", want: "config.boolOrDefault - JOBS_ENABLED"}, + {key: "JOBS_POLL_INTERVAL", value: "soon", want: "config.durationOrDefault - parse JOBS_POLL_INTERVAL"}, + {key: "JOBS_POLL_INTERVAL", value: "9ms", want: "Config.ValidateJobs - JOBS_POLL_INTERVAL"}, + {key: "JOBS_POLL_INTERVAL", value: "6m", want: "Config.ValidateJobs - JOBS_POLL_INTERVAL"}, + {key: "JOBS_BATCH_SIZE", value: "", want: "config.intOrDefault - JOBS_BATCH_SIZE"}, + {key: "JOBS_BATCH_SIZE", value: "0", want: "Config.ValidateJobs - JOBS_BATCH_SIZE"}, + {key: "JOBS_BATCH_SIZE", value: "101", want: "Config.ValidateJobs - JOBS_BATCH_SIZE"}, + {key: "JOBS_LEASE_DURATION", value: "999ms", want: "Config.ValidateJobs - JOBS_LEASE_DURATION"}, + {key: "JOBS_LEASE_DURATION", value: "61m", want: "Config.ValidateJobs - JOBS_LEASE_DURATION"}, + {key: "JOBS_MAX_ATTEMPTS", value: "many", want: "config.intOrDefault - JOBS_MAX_ATTEMPTS"}, + {key: "JOBS_MAX_ATTEMPTS", value: "0", want: "Config.ValidateJobs - JOBS_MAX_ATTEMPTS"}, + {key: "JOBS_MAX_ATTEMPTS", value: "101", want: "Config.ValidateJobs - JOBS_MAX_ATTEMPTS"}, + {key: "JOBS_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateJobs - JOBS_BACKOFF_INITIAL"}, + {key: "JOBS_BACKOFF_INITIAL", value: "6m", want: "Config.ValidateJobs - JOBS_BACKOFF_MAX"}, + {key: "JOBS_BACKOFF_MAX", value: "25h", want: "Config.ValidateJobs - JOBS_BACKOFF_MAX"}, + {key: "JOBS_SHUTDOWN_GRACE", value: "0s", want: "Config.ValidateJobs - JOBS_SHUTDOWN_GRACE"}, + // Longer than the default SHUTDOWN_TIMEOUT of 10s. + {key: "JOBS_SHUTDOWN_GRACE", value: "11s", want: "Config.ValidateJobs - JOBS_SHUTDOWN_GRACE"}, + } + for _, test := range tests { + t.Run(test.key+"/"+test.value, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + }) + } +} + +func TestValidateJobsChecksSettingsEvenWhenDisabled(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"JOBS_ENABLED": "false"})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + settings.JobsBatchSize = 0 + if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateJobs - JOBS_BATCH_SIZE") { + t.Fatalf("Validate() error = %v, want the job batch size error", err) + } +} + +// jobSettings collects the job fields for failure messages. +func jobSettings(settings Config) map[string]any { + return map[string]any{ + "enabled": settings.JobsEnabled, + "poll_interval": settings.JobsPollInterval, + "batch_size": settings.JobsBatchSize, + "lease": settings.JobsLeaseDuration, + "max_attempts": settings.JobsMaxAttempts, + "backoff_initial": settings.JobsBackoffInitial, + "backoff_max": settings.JobsBackoffMax, + "shutdown_grace": settings.JobsShutdownGrace, + } +} diff --git a/backend/config/kafka.go b/backend/config/kafka.go new file mode 100644 index 0000000..62c216b --- /dev/null +++ b/backend/config/kafka.go @@ -0,0 +1,169 @@ +package config + +import ( + "errors" + "fmt" + "math" + "net" + "regexp" + "strconv" + "strings" +) + +const ( + defaultKafkaBrokers = "localhost:9092" + kafkaBrokersSeparator = "," + + // defaultKafkaEventsTopic receives every domain event. One topic keeps + // the setup small; the record key keeps each aggregate's events ordered + // within one partition. + defaultKafkaEventsTopic = "lincodex.domain.events" + // defaultKafkaEventsTopicPartitions lets up to three consumers of one + // group share the topic. Partitions can be added later but not removed, + // and adding them moves keys to other partitions. + defaultKafkaEventsTopicPartitions = 3 + // maxKafkaEventsTopicPartitions bounds a mistyped value; one node does + // not benefit from more partitions. + maxKafkaEventsTopicPartitions = 1000 + // KafkaBrokerDefaultReplicationFactor asks the broker to apply its own + // default.replication.factor when it creates the topic, so one setting on + // the broker covers both the single-node stand and a replicated cluster. + KafkaBrokerDefaultReplicationFactor = -1 + // KafkaBrokerDefaultMinInsyncReplicas leaves min.insync.replicas of a + // created topic to the broker default. + KafkaBrokerDefaultMinInsyncReplicas = 0 + // Topic provisioning is on by default because the broker never creates + // topics on demand. + defaultKafkaProvisionTopics = true + // maxKafkaTopicNameLength is the Kafka limit for topic names. + maxKafkaTopicNameLength = 249 +) + +// kafkaTopicNamePattern holds the characters Kafka accepts in a topic name. +var kafkaTopicNamePattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`) + +// parseKafkaBrokers splits a comma-separated broker list. Empty entries are +// kept so that validation can reject values such as "a:9092,,b:9092". +func parseKafkaBrokers(raw string) []string { + if strings.TrimSpace(raw) == "" { + return nil + } + entries := strings.Split(raw, kafkaBrokersSeparator) + brokers := make([]string, 0, len(entries)) + for _, entry := range entries { + brokers = append(brokers, strings.TrimSpace(entry)) + } + return brokers +} + +// loadKafkaTopics reads the events topic settings. An unset value takes its +// default; an empty or malformed value is an error. +func (config *Config) loadKafkaTopics(lookup LookupEnv) error { + config.KafkaEventsTopic = strings.TrimSpace(valueOrDefault(lookup, "KAFKA_EVENTS_TOPIC", defaultKafkaEventsTopic)) + partitions, err := intOrDefault(lookup, "KAFKA_EVENTS_TOPIC_PARTITIONS", defaultKafkaEventsTopicPartitions) + if err != nil { + return err + } + if partitions < 1 || partitions > maxKafkaEventsTopicPartitions { + return fmt.Errorf("Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_PARTITIONS must be between 1 and %d", maxKafkaEventsTopicPartitions) + } + config.KafkaEventsTopicPartitions = int32(partitions) + replicationFactor, err := intOrDefault(lookup, "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR", KafkaBrokerDefaultReplicationFactor) + if err != nil { + return err + } + if replicationFactor < KafkaBrokerDefaultReplicationFactor || replicationFactor == 0 || replicationFactor > math.MaxInt16 { + return fmt.Errorf("Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR must be -1 for the broker default or between 1 and %d", math.MaxInt16) + } + config.KafkaEventsTopicReplicationFactor = int16(replicationFactor) + minInsyncReplicas, err := intOrDefault(lookup, "KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS", KafkaBrokerDefaultMinInsyncReplicas) + if err != nil { + return err + } + // An explicit 0 would read as the broker default, so only an unset + // variable selects it. + _, set := lookup("KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS") + if minInsyncReplicas < KafkaBrokerDefaultMinInsyncReplicas || minInsyncReplicas > math.MaxInt16 || (set && minInsyncReplicas == KafkaBrokerDefaultMinInsyncReplicas) { + return fmt.Errorf("Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must be between 1 and %d, or unset for the broker default", math.MaxInt16) + } + config.KafkaEventsTopicMinInsyncReplicas = int16(minInsyncReplicas) + config.KafkaProvisionTopics, err = boolOrDefault(lookup, "KAFKA_PROVISION_TOPICS", defaultKafkaProvisionTopics) + return err +} + +func (config Config) ValidateKafka() error { + if len(config.KafkaBrokers) == 0 { + return errors.New("Config.ValidateKafka - KAFKA_BROKERS must not be empty") + } + for index, broker := range config.KafkaBrokers { + // Report the position instead of the value so a mistyped entry with + // embedded credentials does not reach logs. + if !validKafkaBroker(broker) { + return fmt.Errorf("Config.ValidateKafka - KAFKA_BROKERS entry %d must be a host:port address with a nonzero port", index+1) + } + } + if !validKafkaTopicName(config.KafkaEventsTopic) { + return fmt.Errorf("Config.ValidateKafka - KAFKA_EVENTS_TOPIC must be 1 to %d letters, digits, dots, underscores, or hyphens other than a single or double dot", maxKafkaTopicNameLength) + } + if config.KafkaEventsTopicPartitions < 1 || config.KafkaEventsTopicPartitions > maxKafkaEventsTopicPartitions { + return fmt.Errorf("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_PARTITIONS must be between 1 and %d", maxKafkaEventsTopicPartitions) + } + if config.KafkaEventsTopicReplicationFactor != KafkaBrokerDefaultReplicationFactor && config.KafkaEventsTopicReplicationFactor < 1 { + return errors.New("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR must be -1 for the broker default or positive") + } + if config.KafkaEventsTopicMinInsyncReplicas < KafkaBrokerDefaultMinInsyncReplicas { + return errors.New("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must be positive or unset for the broker default") + } + // With an explicit replication factor, a larger min.insync.replicas would + // make every acks=all write fail. + if config.KafkaEventsTopicReplicationFactor > 0 && config.KafkaEventsTopicMinInsyncReplicas > config.KafkaEventsTopicReplicationFactor { + return errors.New("Config.ValidateKafka - KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS must not exceed KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR") + } + return nil +} + +// validKafkaTopicName applies the broker's topic name rules. +func validKafkaTopicName(topic string) bool { + return len(topic) <= maxKafkaTopicNameLength && topic != "." && topic != ".." && kafkaTopicNamePattern.MatchString(topic) +} + +// validKafkaBroker accepts a hostname or IP address with a port in 1-65535. +// URL schemes, user info, and paths are rejected because Kafka clients expect +// plain bootstrap addresses. +func validKafkaBroker(broker string) bool { + host, port, err := net.SplitHostPort(broker) + if err != nil { + return false + } + number, err := strconv.Atoi(port) + if err != nil || number < 1 || number > maxPortNumber { + return false + } + return net.ParseIP(host) != nil || validHostname(host) +} + +func validHostname(host string) bool { + if host == "" { + return false + } + for _, label := range strings.Split(host, ".") { + if !validHostnameLabel(label) { + return false + } + } + return true +} + +func validHostnameLabel(label string) bool { + if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") { + return false + } + for _, character := range label { + isLetter := (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') + isDigit := character >= '0' && character <= '9' + if !isLetter && !isDigit && character != '-' && character != '_' { + return false + } + } + return true +} diff --git a/backend/config/mail.go b/backend/config/mail.go new file mode 100644 index 0000000..40cc558 --- /dev/null +++ b/backend/config/mail.go @@ -0,0 +1,359 @@ +package config + +import ( + "errors" + "fmt" + "net" + "net/mail" + "net/url" + "regexp" + "strconv" + "strings" + "time" + + "lincodex/backend/internal/domain" +) + +// EmailProvider selects exactly one mail transport. There is no implicit +// fallback between transports. +type EmailProvider string + +const ( + EmailProviderResend EmailProvider = "resend" + EmailProviderSMTP EmailProvider = "smtp" + EmailProviderDisabled EmailProvider = "disabled" +) + +// SMTPTLSMode selects how the SMTP transport protects the connection. +// Plaintext SMTP is not supported. +type SMTPTLSMode string + +const ( + // SMTPTLSModeStartTLS upgrades the connection with STARTTLS and fails + // when the server does not offer it (submission, usually port 587). + SMTPTLSModeStartTLS SMTPTLSMode = "starttls" + // SMTPTLSModeImplicit opens TLS before the SMTP dialog (usually port 465). + SMTPTLSModeImplicit SMTPTLSMode = "tls" +) + +const ( + // defaultEmailAccount labels the only provider account of a stand that + // never switched accounts. + defaultEmailAccount = "default" + defaultEmailTimeout = 10 * time.Second + // One attempt waits at least long enough for a TLS handshake and an API + // answer, and at most one minute so that a hung provider cannot hold a + // delivery worker indefinitely. + minEmailTimeout = time.Second + maxEmailTimeout = time.Minute + + // The defaults are the Resend Free plan limits checked on 2026-10-05: + // 100 recipients per UTC day and 3000 per month. They apply to resend + // and to disabled, which sends nothing. smtp has no default: a relay's + // limits are not Resend's, so the operator states them. + defaultEmailQuotaDaily = 100 + defaultEmailQuotaMonthly = 3000 + // defaultEmailServiceReserveShare sets the service reserve default to one + // part of the limit of each window: a fifth, so 20 recipients a day and 600 + // a month on the Resend Free plan. Product notifications share the rest. + defaultEmailServiceReserveShare = 5 + // maxEmailQuota is far above any plan this project can afford; a larger + // value is a typo, not a plan. + maxEmailQuota = 1_000_000_000 +) + +// emailAccountPattern matches domain.NewMailProviderAccount: a lowercase +// label that cannot hold the mixed-case characters of an API key. +var emailAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) + +// loadMail reads the common mail settings and only the settings of the +// selected transport, so settings of an inactive transport, including its +// secrets, never reach Config. +// +// EMAIL_PROVIDER has no default. The working stand uses resend, but a default +// would either pick a transport that this build may not provide or silently +// turn mail off; an explicit choice makes both visible at deployment time. +func (config *Config) loadMail(lookup LookupEnv) error { + provider := strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "EMAIL_PROVIDER", ""))) + config.EmailProvider = EmailProvider(provider) + config.EmailFrom = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_FROM", "")) + config.EmailAccount = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_ACCOUNT", defaultEmailAccount)) + // One trailing slash is accepted and dropped so that the stored value is + // an origin that links can be appended to. + config.AppPublicURL = strings.TrimSuffix(strings.TrimSpace(valueOrDefault(lookup, "APP_PUBLIC_URL", "")), "/") + + var err error + config.EmailTimeout, err = durationOrDefault(lookup, "EMAIL_TIMEOUT", defaultEmailTimeout) + if err != nil { + return err + } + if err := config.loadMailQuota(lookup); err != nil { + return err + } + + switch config.EmailProvider { + case EmailProviderResend: + config.ResendAPIKey = valueOrDefault(lookup, "RESEND_API_KEY", "") + case EmailProviderSMTP: + return config.loadSMTP(lookup) + case EmailProviderDisabled: + // No transport settings are read. + } + return nil +} + +// loadMailQuota reads the quota of the configured provider account. The +// quota is read for every provider, so no transport can run without one. +// For smtp an unset value stays zero, which validation reports as missing. +// +// An empty value counts as unset, as for SMTP_PORT: Compose passes an unset +// variable as an empty string, and a Compose-side default would give smtp +// the Resend limits without the operator stating them. +func (config *Config) loadMailQuota(lookup LookupEnv) error { + daily, monthly := defaultEmailQuotaDaily, defaultEmailQuotaMonthly + if config.EmailProvider == EmailProviderSMTP { + daily, monthly = 0, 0 + } + setOnly := func(key string) (string, bool) { + value, ok := lookup(key) + if strings.TrimSpace(value) == "" { + return "", false + } + return value, ok + } + var err error + if config.EmailQuotaDaily, err = intOrDefault(setOnly, "EMAIL_QUOTA_DAILY", daily); err != nil { + return err + } + if config.EmailQuotaMonthly, err = intOrDefault(setOnly, "EMAIL_QUOTA_MONTHLY", monthly); err != nil { + return err + } + return config.loadServiceReserve(setOnly) +} + +// loadServiceReserve reads the recipients of each window that product +// notifications leave to service mail. An unset value takes a fifth of the +// configured limit, so the default follows the plan; a set value of 0 keeps +// the whole window for notifications too. +func (config *Config) loadServiceReserve(setOnly func(key string) (string, bool)) error { + var err error + if config.EmailServiceReserveDaily, err = intOrDefault(setOnly, "EMAIL_SERVICE_RESERVE_DAILY", config.EmailQuotaDaily/defaultEmailServiceReserveShare); err != nil { + return err + } + if config.EmailServiceReserveMonthly, err = intOrDefault(setOnly, "EMAIL_SERVICE_RESERVE_MONTHLY", config.EmailQuotaMonthly/defaultEmailServiceReserveShare); err != nil { + return err + } + return nil +} + +func (config *Config) loadSMTP(lookup LookupEnv) error { + config.SMTPHost = strings.TrimSpace(valueOrDefault(lookup, "SMTP_HOST", "")) + config.SMTPUsername = strings.TrimSpace(valueOrDefault(lookup, "SMTP_USERNAME", "")) + config.SMTPPassword = valueOrDefault(lookup, "SMTP_PASSWORD", "") + config.SMTPTLSMode = SMTPTLSMode(strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "SMTP_TLS_MODE", "")))) + + // An unset or empty port stays zero, which validation reports as missing. + port := strings.TrimSpace(valueOrDefault(lookup, "SMTP_PORT", "")) + if port == "" { + return nil + } + number, err := strconv.Atoi(port) + if err != nil { + return fmt.Errorf("Config.loadSMTP - SMTP_PORT must be an integer between 1 and %d", maxPortNumber) + } + config.SMTPPort = number + return nil +} + +// ValidateMail checks the common mail settings and the selected transport. +// Errors name the setting and never include secret values. +func (config Config) ValidateMail() error { + // The value is not echoed: a misplaced secret must not reach the logs. + switch config.EmailProvider { + case EmailProviderResend, EmailProviderSMTP, EmailProviderDisabled: + case "": + return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled") + default: + return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled") + } + if err := validateEmailFrom(config.EmailFrom); err != nil { + return err + } + // The value is not echoed: an API key pasted here must not reach logs. + if !emailAccountPattern.MatchString(config.EmailAccount) { + return errors.New("Config.ValidateMail - EMAIL_ACCOUNT must be a label of 1 to 64 lowercase letters, digits, '.', '_', or '-' that starts with a letter or digit") + } + if err := validateAppPublicURL(config.AppPublicURL); err != nil { + return err + } + if config.EmailTimeout < minEmailTimeout || config.EmailTimeout > maxEmailTimeout { + return fmt.Errorf("Config.ValidateMail - EMAIL_TIMEOUT must be between %s and %s", minEmailTimeout, maxEmailTimeout) + } + if err := config.validateMailQuota(); err != nil { + return err + } + + switch config.EmailProvider { + case EmailProviderResend: + return validateResendAPIKey(config.ResendAPIKey) + case EmailProviderSMTP: + return config.validateSMTP() + case EmailProviderDisabled: + } + return nil +} + +// validateMailQuota accepts limits from 1 to maxEmailQuota where the daily +// limit does not exceed the monthly one. There is no value that turns the +// quota off: zero is refused rather than read as "unlimited", so switching +// EMAIL_PROVIDER, for example to smtp, never skips the quota gate. +func (config Config) validateMailQuota() error { + for _, quota := range []struct { + name string + value int + }{{"EMAIL_QUOTA_DAILY", config.EmailQuotaDaily}, {"EMAIL_QUOTA_MONTHLY", config.EmailQuotaMonthly}} { + if quota.value >= 1 && quota.value <= maxEmailQuota { + continue + } + if config.EmailProvider == EmailProviderSMTP { + return fmt.Errorf("Config.validateMailQuota - %s must be set to an integer from 1 to %d when EMAIL_PROVIDER is smtp; the Resend defaults do not apply to a relay", quota.name, maxEmailQuota) + } + return fmt.Errorf("Config.validateMailQuota - %s must be an integer from 1 to %d", quota.name, maxEmailQuota) + } + if config.EmailQuotaDaily > config.EmailQuotaMonthly { + return errors.New("Config.validateMailQuota - EMAIL_QUOTA_DAILY must not exceed EMAIL_QUOTA_MONTHLY") + } + return config.validateServiceReserve() +} + +// validateServiceReserve accepts a reserve from 0 up to, not including, each +// limit. A reserve equal to a limit would leave product notifications no +// recipient in that window, so it is refused rather than read as "off". +func (config Config) validateServiceReserve() error { + for _, reserve := range []struct { + name string + value int + limit int + }{ + {"EMAIL_SERVICE_RESERVE_DAILY", config.EmailServiceReserveDaily, config.EmailQuotaDaily}, + {"EMAIL_SERVICE_RESERVE_MONTHLY", config.EmailServiceReserveMonthly, config.EmailQuotaMonthly}, + } { + if reserve.value < 0 || reserve.value >= reserve.limit { + return fmt.Errorf("Config.validateServiceReserve - %s must be an integer from 0 to below its quota limit", reserve.name) + } + } + return nil +} + +// validateEmailFrom accepts one RFC 5322 mailbox, with or without a display +// name. The address itself follows the account address rules of +// domain.NewEmailAddress: ASCII only, because the mailer does not support +// SMTPUTF8, an unquoted local part, and a DNS domain with at least two labels. +func validateEmailFrom(raw string) error { + if raw == "" { + return errors.New("config.validateEmailFrom - EMAIL_FROM must be set") + } + // Control characters such as CR and LF could inject header lines. + if !isPrintableASCII(raw) { + return errors.New("config.validateEmailFrom - EMAIL_FROM must contain printable ASCII characters only") + } + mailbox, err := mail.ParseAddress(raw) + if err != nil { + return errors.New("config.validateEmailFrom - EMAIL_FROM must be one mailbox such as Lincodex ") + } + if _, err := domain.NewEmailAddress(mailbox.Address); err != nil { + return errors.New("config.validateEmailFrom - EMAIL_FROM address must be an ASCII addr-spec with a DNS domain of at least two labels") + } + return nil +} + +// validateAppPublicURL accepts the public origin that links in mail point +// to. Plain HTTP is accepted only for a loopback host in local runs. +func validateAppPublicURL(raw string) error { + if raw == "" { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be set") + } + origin, err := url.Parse(raw) + if err != nil || origin.Hostname() == "" || !validHostOrIP(origin.Hostname()) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL with a valid host") + } + switch { + case origin.Scheme == "https": + case origin.Scheme == "http" && isLoopbackHost(origin.Hostname()): + default: + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]") + } + + if !isBareOrigin(origin, raw) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an origin without credentials, a path, query, or fragment") + } + if !validEndpointPort(origin) { + return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port") + } + return nil +} + +// isBareOrigin reports a URL with nothing after the authority. raw is checked +// for "#" because url.Parse drops an empty fragment. +func isBareOrigin(origin *url.URL, raw string) bool { + hasCredentials := origin.User != nil + hasPath := origin.Path != "" || origin.RawPath != "" + hasQuery := origin.RawQuery != "" || origin.ForceQuery + hasFragment := origin.Fragment != "" || strings.Contains(raw, "#") + return !hasCredentials && !hasPath && !hasQuery && !hasFragment +} + +// validateResendAPIKey checks only what the Authorization header needs. Resend +// shows keys as "re_..." in examples but does not document a stable format, +// so the prefix is not enforced; the provider itself rejects a wrong key. +func validateResendAPIKey(key string) error { + if key == "" { + return errors.New("config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend") + } + if !isPrintableASCII(key) || strings.Contains(key, " ") { + return errors.New("config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace or non-ASCII characters") + } + return nil +} + +func (config Config) validateSMTP() error { + if config.SMTPHost == "" { + return errors.New("Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp") + } + if !validHostOrIP(config.SMTPHost) { + return errors.New("Config.validateSMTP - SMTP_HOST must be a hostname or IP address without a port") + } + if config.SMTPPort < 1 || config.SMTPPort > maxPortNumber { + return fmt.Errorf("Config.validateSMTP - SMTP_PORT must be set to a port between 1 and %d when EMAIL_PROVIDER is smtp", maxPortNumber) + } + // An anonymous relay is not supported: both credentials are required. + if config.SMTPUsername == "" { + return errors.New("Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp") + } + if config.SMTPPassword == "" { + return errors.New("Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp") + } + switch config.SMTPTLSMode { + case SMTPTLSModeStartTLS, SMTPTLSModeImplicit: + return nil + default: + return errors.New("Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported") + } +} + +func validHostOrIP(host string) bool { + return net.ParseIP(host) != nil || validHostname(host) +} + +func isLoopbackHost(host string) bool { + return strings.EqualFold(host, "localhost") || host == "127.0.0.1" || host == "::1" +} + +func isPrintableASCII(value string) bool { + for index := range len(value) { + if value[index] < ' ' || value[index] > '~' { + return false + } + } + return true +} diff --git a/backend/config/mail_test.go b/backend/config/mail_test.go new file mode 100644 index 0000000..1d9ba77 --- /dev/null +++ b/backend/config/mail_test.go @@ -0,0 +1,300 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +const ( + testResendAPIKey = "re_test-key-value" + testSMTPPassword = "smtp password value" + secretMarker = "hidden-secret-marker" + testSMTPHost = "smtp.example.com" + testPublicOrigin = "https://lincodex.example" + testSenderMailbox = "Lincodex " +) + +// mailEnvironment overrides mail settings on top of the shared test +// environment and removes the keys named in unset. +func mailEnvironment(values map[string]string, unset ...string) LookupEnv { + base := testEnvironment(values) + return func(key string) (string, bool) { + for _, removed := range unset { + if key == removed { + return "", false + } + } + return base(key) + } +} + +func smtpValues(overrides map[string]string) map[string]string { + values := map[string]string{ + "EMAIL_PROVIDER": "smtp", + "SMTP_HOST": testSMTPHost, + "SMTP_PORT": "587", + "SMTP_USERNAME": "mailer", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "starttls", + // smtp has no quota default, so a relay always runs with stated + // limits. + "EMAIL_QUOTA_DAILY": "500", + "EMAIL_QUOTA_MONTHLY": "10000", + } + for key, value := range overrides { + values[key] = value + } + return values +} + +func TestLoadFromEnvMailDisabledIgnoresTransportSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": " Disabled ", + "EMAIL_FROM": " " + testSenderMailbox + " ", + "APP_PUBLIC_URL": testPublicOrigin + "/", + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": testSMTPHost, + "SMTP_PORT": "not-a-port", + "SMTP_PASSWORD": testSMTPPassword, + "SMTP_TLS_MODE": "plaintext", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailProvider != EmailProviderDisabled { + t.Fatalf("EmailProvider = %q, want disabled", settings.EmailProvider) + } + if settings.EmailFrom != testSenderMailbox || settings.AppPublicURL != testPublicOrigin { + t.Fatalf("EmailFrom = %q, AppPublicURL = %q", settings.EmailFrom, settings.AppPublicURL) + } + if settings.EmailTimeout != 10*time.Second { + t.Fatalf("EmailTimeout = %s, want the 10s default", settings.EmailTimeout) + } + if settings.EmailAccount != "default" { + t.Fatalf("EmailAccount = %q, want the default label", settings.EmailAccount) + } + if settings.EmailQuotaDaily != 100 || settings.EmailQuotaMonthly != 3000 { + t.Fatalf("quota = %d/%d, want the Resend Free defaults 100/3000", settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } + if settings.ResendAPIKey != "" || settings.SMTPHost != "" || settings.SMTPPort != 0 || settings.SMTPPassword != "" || settings.SMTPTLSMode != "" { + t.Fatal("settings of an inactive transport were loaded") + } +} + +func TestLoadFromEnvMailResendLoadsOnlyResendSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": "RESEND", + "EMAIL_TIMEOUT": "15s", + "RESEND_API_KEY": testResendAPIKey, + "SMTP_HOST": testSMTPHost, + "SMTP_PASSWORD": testSMTPPassword, + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailProvider != EmailProviderResend || settings.ResendAPIKey != testResendAPIKey || settings.EmailTimeout != 15*time.Second { + t.Fatalf("Resend settings were not loaded: provider=%q timeout=%s", settings.EmailProvider, settings.EmailTimeout) + } + if settings.SMTPHost != "" || settings.SMTPPassword != "" { + t.Fatal("SMTP settings were loaded for EMAIL_PROVIDER=resend") + } + if settings.EmailQuotaDaily != 100 || settings.EmailQuotaMonthly != 3000 { + t.Fatalf("quota = %d/%d, want the Resend Free defaults 100/3000", settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } +} + +func TestLoadFromEnvMailSMTPLoadsOnlySMTPSettings(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(smtpValues(map[string]string{ + "SMTP_PORT": " 465 ", + "SMTP_TLS_MODE": " TLS ", + "RESEND_API_KEY": testResendAPIKey, + }))) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.SMTPHost != testSMTPHost || settings.SMTPPort != 465 || settings.SMTPUsername != "mailer" || settings.SMTPPassword != testSMTPPassword || settings.SMTPTLSMode != SMTPTLSModeImplicit { + t.Fatal("SMTP settings were not loaded") + } + if settings.ResendAPIKey != "" { + t.Fatal("RESEND_API_KEY was loaded for EMAIL_PROVIDER=smtp") + } + if settings.EmailQuotaDaily != 500 || settings.EmailQuotaMonthly != 10000 { + t.Fatalf("quota = %d/%d, want the configured 500/10000", settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } +} + +func TestLoadFromEnvMailQuotaOverridesTheDefaults(t *testing.T) { + // A lowered limit is taken as configured, for every provider. + for _, values := range []map[string]string{ + {"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey}, + smtpValues(nil), + {"EMAIL_PROVIDER": "disabled"}, + } { + values["EMAIL_QUOTA_DAILY"] = " 2 " + values["EMAIL_QUOTA_MONTHLY"] = "5" + settings, err := LoadFromEnv(mailEnvironment(values)) + if err != nil { + t.Fatalf("%s: LoadFromEnv() error = %v", values["EMAIL_PROVIDER"], err) + } + if settings.EmailQuotaDaily != 2 || settings.EmailQuotaMonthly != 5 { + t.Fatalf("%s: quota = %d/%d, want 2/5", values["EMAIL_PROVIDER"], settings.EmailQuotaDaily, settings.EmailQuotaMonthly) + } + } +} + +func TestLoadFromEnvAcceptsMailBoundaries(t *testing.T) { + tests := []struct { + name string + values map[string]string + }{ + {name: "bare sender address", values: map[string]string{"EMAIL_FROM": "no-reply@example.com"}}, + {name: "quoted display name", values: map[string]string{"EMAIL_FROM": `"Lincodex Team" `}}, + {name: "punycode sender domain", values: map[string]string{"EMAIL_FROM": "no-reply@xn--e1afmkfd.xn--p1ai"}}, + {name: "minimum timeout", values: map[string]string{"EMAIL_TIMEOUT": "1s"}}, + {name: "maximum timeout", values: map[string]string{"EMAIL_TIMEOUT": "60s"}}, + {name: "account label with separators", values: map[string]string{"EMAIL_ACCOUNT": " resend-main.2_eu "}}, + {name: "account label of 64 characters", values: map[string]string{"EMAIL_ACCOUNT": strings.Repeat("a", 64)}}, + {name: "HTTPS origin with port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:8443"}}, + {name: "HTTP loopback IPv4", values: map[string]string{"APP_PUBLIC_URL": "http://127.0.0.1:8080"}}, + {name: "HTTP loopback IPv6", values: map[string]string{"APP_PUBLIC_URL": "http://[::1]:8080/"}}, + {name: "SMTP over STARTTLS", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "STARTTLS"})}, + {name: "SMTP host as IP address", values: smtpValues(map[string]string{"SMTP_HOST": "10.0.0.25"})}, + {name: "smallest quota", values: map[string]string{"EMAIL_QUOTA_DAILY": "1", "EMAIL_QUOTA_MONTHLY": "1"}}, + {name: "largest quota", values: map[string]string{"EMAIL_QUOTA_DAILY": "1000000000", "EMAIL_QUOTA_MONTHLY": "1000000000"}}, + {name: "empty quota takes the default", values: map[string]string{"EMAIL_QUOTA_DAILY": " ", "EMAIL_QUOTA_MONTHLY": ""}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if _, err := LoadFromEnv(mailEnvironment(test.values)); err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + }) + } +} + +func TestLoadFromEnvRejectsMailSettings(t *testing.T) { + resend := func(key string) map[string]string { + return map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": key} + } + tests := []struct { + name string + values map[string]string + unset []string + want string + }{ + {name: "provider unset", unset: []string{"EMAIL_PROVIDER"}, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "provider empty", values: map[string]string{"EMAIL_PROVIDER": " "}, want: "Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled"}, + {name: "unknown provider", values: map[string]string{"EMAIL_PROVIDER": "sendgrid"}, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled"}, + {name: "secret pasted as provider", values: map[string]string{"EMAIL_PROVIDER": secretMarker}, want: "Config.ValidateMail - EMAIL_PROVIDER must be one of"}, + {name: "sender unset", unset: []string{"EMAIL_FROM"}, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "sender empty", values: map[string]string{"EMAIL_FROM": " "}, want: "config.validateEmailFrom - EMAIL_FROM must be set"}, + {name: "sender without domain", values: map[string]string{"EMAIL_FROM": "no-reply"}, want: "config.validateEmailFrom - EMAIL_FROM must be one mailbox"}, + {name: "sender list", values: map[string]string{"EMAIL_FROM": "a@example.com, b@example.com"}, want: "config.validateEmailFrom - EMAIL_FROM must be one mailbox"}, + {name: "sender header injection", values: map[string]string{"EMAIL_FROM": "a@example.com\r\nBcc: b@example.com"}, want: "config.validateEmailFrom - EMAIL_FROM must contain printable ASCII"}, + {name: "sender non-ASCII name", values: map[string]string{"EMAIL_FROM": "Линкодекс "}, want: "config.validateEmailFrom - EMAIL_FROM must contain printable ASCII"}, + {name: "sender single-label domain", values: map[string]string{"EMAIL_FROM": "no-reply@localhost"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "sender IP literal", values: map[string]string{"EMAIL_FROM": "no-reply@[127.0.0.1]"}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "sender quoted local part", values: map[string]string{"EMAIL_FROM": `"no reply"@example.com`}, want: "config.validateEmailFrom - EMAIL_FROM address must be"}, + {name: "account empty", values: map[string]string{"EMAIL_ACCOUNT": " "}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"}, + {name: "account with uppercase", values: map[string]string{"EMAIL_ACCOUNT": "Main"}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"}, + {name: "API key pasted as account", values: map[string]string{"EMAIL_ACCOUNT": "re_" + strings.ToUpper(secretMarker)}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"}, + {name: "account starting with a dash", values: map[string]string{"EMAIL_ACCOUNT": "-main"}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"}, + {name: "account too long", values: map[string]string{"EMAIL_ACCOUNT": strings.Repeat("a", 65)}, want: "Config.ValidateMail - EMAIL_ACCOUNT must be a label"}, + {name: "timeout unparsable", values: map[string]string{"EMAIL_TIMEOUT": "soon"}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"}, + {name: "timeout empty", values: map[string]string{"EMAIL_TIMEOUT": ""}, want: "config.durationOrDefault - parse EMAIL_TIMEOUT"}, + {name: "timeout zero", values: map[string]string{"EMAIL_TIMEOUT": "0s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between 1s and 1m0s"}, + {name: "timeout too short", values: map[string]string{"EMAIL_TIMEOUT": "500ms"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between"}, + {name: "timeout too long", values: map[string]string{"EMAIL_TIMEOUT": "61s"}, want: "Config.ValidateMail - EMAIL_TIMEOUT must be between"}, + {name: "public URL unset", unset: []string{"APP_PUBLIC_URL"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be set"}, + {name: "public URL without scheme", values: map[string]string{"APP_PUBLIC_URL": "lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL"}, + {name: "public URL with space", values: map[string]string{"APP_PUBLIC_URL": "https://linco dex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL"}, + {name: "public URL other scheme", values: map[string]string{"APP_PUBLIC_URL": "ftp://lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL plain HTTP", values: map[string]string{"APP_PUBLIC_URL": "http://lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL loopback lookalike", values: map[string]string{"APP_PUBLIC_URL": "http://localhost.lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must use https"}, + {name: "public URL credentials", values: map[string]string{"APP_PUBLIC_URL": "https://user:" + secretMarker + "@lincodex.example"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL path", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example/app"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL double slash", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example//"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL query", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example?token=" + secretMarker}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL fragment", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example#top"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL empty fragment", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example#"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must be an origin"}, + {name: "public URL zero port", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:0"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port"}, + {name: "public URL port out of range", values: map[string]string{"APP_PUBLIC_URL": "https://lincodex.example:70000"}, want: "config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port"}, + {name: "Resend key unset", values: map[string]string{"EMAIL_PROVIDER": "resend"}, want: "config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend"}, + {name: "Resend key empty", values: resend(""), want: "config.validateResendAPIKey - RESEND_API_KEY must be set"}, + {name: "Resend key with space", values: resend("re_" + secretMarker + " x"), want: "config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace"}, + {name: "Resend key with newline", values: resend("re_" + secretMarker + "\n"), want: "config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace"}, + {name: "SMTP host unset", values: smtpValues(nil), unset: []string{"SMTP_HOST"}, want: "Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP host with port", values: smtpValues(map[string]string{"SMTP_HOST": "smtp.example.com:587"}), want: "Config.validateSMTP - SMTP_HOST must be a hostname or IP address"}, + {name: "SMTP port unset", values: smtpValues(nil), unset: []string{"SMTP_PORT"}, want: "Config.validateSMTP - SMTP_PORT must be set to a port between 1 and 65535"}, + {name: "SMTP port not a number", values: smtpValues(map[string]string{"SMTP_PORT": "submission"}), want: "Config.loadSMTP - SMTP_PORT must be an integer"}, + {name: "SMTP port zero", values: smtpValues(map[string]string{"SMTP_PORT": "0"}), want: "Config.validateSMTP - SMTP_PORT must be set to a port"}, + {name: "SMTP port out of range", values: smtpValues(map[string]string{"SMTP_PORT": "70000"}), want: "Config.validateSMTP - SMTP_PORT must be set to a port"}, + {name: "SMTP username unset", values: smtpValues(nil), unset: []string{"SMTP_USERNAME"}, want: "Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP password unset", values: smtpValues(nil), unset: []string{"SMTP_PASSWORD"}, want: "Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp"}, + {name: "SMTP TLS mode unset", values: smtpValues(nil), unset: []string{"SMTP_TLS_MODE"}, want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls"}, + {name: "SMTP plaintext", values: smtpValues(map[string]string{"SMTP_TLS_MODE": "none"}), want: "Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported"}, + {name: "SMTP daily quota unset", values: smtpValues(nil), unset: []string{"EMAIL_QUOTA_DAILY"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be set to an integer from 1 to 1000000000 when EMAIL_PROVIDER is smtp"}, + {name: "SMTP monthly quota unset", values: smtpValues(nil), unset: []string{"EMAIL_QUOTA_MONTHLY"}, want: "Config.validateMailQuota - EMAIL_QUOTA_MONTHLY must be set to an integer from 1 to 1000000000 when EMAIL_PROVIDER is smtp"}, + {name: "SMTP quota zero", values: smtpValues(map[string]string{"EMAIL_QUOTA_DAILY": "0"}), want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be set to an integer from 1"}, + {name: "daily quota zero", values: map[string]string{"EMAIL_QUOTA_DAILY": "0"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be an integer from 1 to 1000000000"}, + {name: "daily quota negative", values: map[string]string{"EMAIL_QUOTA_DAILY": "-1"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must be an integer from 1"}, + {name: "monthly quota above the maximum", values: map[string]string{"EMAIL_QUOTA_MONTHLY": "1000000001"}, want: "Config.validateMailQuota - EMAIL_QUOTA_MONTHLY must be an integer from 1"}, + {name: "daily quota not a number", values: map[string]string{"EMAIL_QUOTA_DAILY": "unlimited"}, want: "config.intOrDefault - EMAIL_QUOTA_DAILY must be an integer"}, + {name: "SMTP quota empty as Compose passes it unset", values: smtpValues(map[string]string{"EMAIL_QUOTA_MONTHLY": ""}), want: "Config.validateMailQuota - EMAIL_QUOTA_MONTHLY must be set to an integer from 1"}, + {name: "daily quota above the monthly quota", values: map[string]string{"EMAIL_QUOTA_DAILY": "3001"}, want: "Config.validateMailQuota - EMAIL_QUOTA_DAILY must not exceed EMAIL_QUOTA_MONTHLY"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := LoadFromEnv(mailEnvironment(test.values, test.unset...)) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + for _, secret := range []string{secretMarker, strings.ToUpper(secretMarker), testResendAPIKey, testSMTPPassword} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("configuration error discloses a configured value: %v", err) + } + } + }) + } +} + +func TestLoadFromEnvServiceReserveDefaultsToAFifthOfEachLimit(t *testing.T) { + settings, err := LoadFromEnv(mailEnvironment(map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailServiceReserveDaily != 20 || settings.EmailServiceReserveMonthly != 600 { + t.Fatalf("service reserve = %d a day and %d a month, want 20 and 600 for the Resend Free limits", settings.EmailServiceReserveDaily, settings.EmailServiceReserveMonthly) + } + + // Zero is a stated reserve, not an unset one: the notifications may then use + // the whole window. + settings, err = LoadFromEnv(mailEnvironment(map[string]string{ + "EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey, + "EMAIL_SERVICE_RESERVE_DAILY": "5", "EMAIL_SERVICE_RESERVE_MONTHLY": "0", + })) + if err != nil { + t.Fatalf("LoadFromEnv() with a stated reserve error = %v", err) + } + if settings.EmailServiceReserveDaily != 5 || settings.EmailServiceReserveMonthly != 0 { + t.Fatalf("service reserve = %d a day and %d a month, want 5 and 0", settings.EmailServiceReserveDaily, settings.EmailServiceReserveMonthly) + } +} + +func TestLoadFromEnvRejectsAServiceReserveThatLeavesNoRoom(t *testing.T) { + for name, value := range map[string]map[string]string{ + "daily reserve equal to the daily limit": {"EMAIL_SERVICE_RESERVE_DAILY": "100"}, + "monthly reserve above the monthly limit": {"EMAIL_SERVICE_RESERVE_MONTHLY": "3001"}, + "negative reserve": {"EMAIL_SERVICE_RESERVE_DAILY": "-1"}, + } { + values := map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": testResendAPIKey} + for key, reserve := range value { + values[key] = reserve + } + _, err := LoadFromEnv(mailEnvironment(values)) + if err == nil || !strings.Contains(err.Error(), "EMAIL_SERVICE_RESERVE") { + t.Fatalf("%s: LoadFromEnv() error = %v, want a refusal that names the reserve", name, err) + } + } +} diff --git a/backend/config/notification.go b/backend/config/notification.go new file mode 100644 index 0000000..f68fe9a --- /dev/null +++ b/backend/config/notification.go @@ -0,0 +1,12 @@ +package config + +// defaultNotificationSyntheticEnabled keeps the synthetic inbox event off: +// a production deployment neither consumes nor renders it. A development or +// browser-test stand turns it on. +const defaultNotificationSyntheticEnabled = false + +func (config *Config) loadNotification(lookup LookupEnv) error { + var err error + config.NotificationSyntheticEnabled, err = boolOrDefault(lookup, "NOTIFICATION_SYNTHETIC_ENABLED", defaultNotificationSyntheticEnabled) + return err +} diff --git a/backend/config/notification_test.go b/backend/config/notification_test.go new file mode 100644 index 0000000..434213c --- /dev/null +++ b/backend/config/notification_test.go @@ -0,0 +1,17 @@ +package config + +import "testing" + +func TestLoadFromEnvReadsTheSyntheticNotificationSwitch(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil || settings.NotificationSyntheticEnabled { + t.Fatalf("default = %t, %v, want off", settings.NotificationSyntheticEnabled, err) + } + settings, err = LoadFromEnv(testEnvironment(map[string]string{"NOTIFICATION_SYNTHETIC_ENABLED": " True "})) + if err != nil || !settings.NotificationSyntheticEnabled { + t.Fatalf("enabled = %t, %v, want on", settings.NotificationSyntheticEnabled, err) + } + if _, err := LoadFromEnv(testEnvironment(map[string]string{"NOTIFICATION_SYNTHETIC_ENABLED": "yes"})); err == nil { + t.Fatal("LoadFromEnv() accepted a value that is not true or false") + } +} diff --git a/backend/config/password_hash.go b/backend/config/password_hash.go new file mode 100644 index 0000000..d131c68 --- /dev/null +++ b/backend/config/password_hash.go @@ -0,0 +1,47 @@ +package config + +import ( + "fmt" + "runtime" + "strconv" + "strings" +) + +const ( + // defaultPasswordHashConcurrency is the default number of Argon2id + // derivations with the current parameters (64 MiB, 4 lanes each) that may + // run at once. The default is lowered to GOMAXPROCS, which Go derives from + // the container CPU limit, because more parallel derivations than CPUs + // only share the same CPUs while holding more memory. + defaultPasswordHashConcurrency = 2 + // maxPasswordHashConcurrency keeps the hashing budget at 256 MiB, which + // fits under the 600 MiB GOMEMLIMIT of the 768 MiB backend container + // together with the rest of the process. + maxPasswordHashConcurrency = 4 +) + +// loadPasswordHash reads PASSWORD_HASH_CONCURRENCY. An unset value takes the +// smaller of the default and GOMAXPROCS; an empty or non-integer value is an +// error. +func (config *Config) loadPasswordHash(lookup LookupEnv) error { + config.PasswordHashConcurrency = min(defaultPasswordHashConcurrency, runtime.GOMAXPROCS(0)) + value, ok := lookup("PASSWORD_HASH_CONCURRENCY") + if !ok { + return nil + } + number, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return fmt.Errorf("Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and %d", maxPasswordHashConcurrency) + } + config.PasswordHashConcurrency = number + return nil +} + +// ValidatePasswordHash checks the password hashing budget: the number of +// derivations with the current parameters that may run at once. +func (config Config) ValidatePasswordHash() error { + if config.PasswordHashConcurrency < 1 || config.PasswordHashConcurrency > maxPasswordHashConcurrency { + return fmt.Errorf("Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and %d", maxPasswordHashConcurrency) + } + return nil +} diff --git a/backend/config/password_hash_test.go b/backend/config/password_hash_test.go new file mode 100644 index 0000000..ffe7179 --- /dev/null +++ b/backend/config/password_hash_test.go @@ -0,0 +1,47 @@ +package config + +import ( + "runtime" + "strings" + "testing" +) + +func TestLoadFromEnvPasswordHashConcurrency(t *testing.T) { + tests := map[string]struct { + values map[string]string + want int + }{ + "default": {values: nil, want: min(2, runtime.GOMAXPROCS(0))}, + "explicit": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "3"}, want: 3}, + "spaces": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": " 1 "}, want: 1}, + "upper bound": {values: map[string]string{"PASSWORD_HASH_CONCURRENCY": "4"}, want: 4}, + } + for name, test := range tests { + settings, err := LoadFromEnv(testEnvironment(test.values)) + if err != nil { + t.Fatalf("LoadFromEnv(%s) error = %v", name, err) + } + if settings.PasswordHashConcurrency != test.want { + t.Fatalf("LoadFromEnv(%s) PasswordHashConcurrency = %d, want %d", name, settings.PasswordHashConcurrency, test.want) + } + } +} + +func TestLoadFromEnvRejectsPasswordHashConcurrency(t *testing.T) { + tests := map[string]struct { + value string + want string + }{ + "empty": {value: "", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY must be an integer between 1 and 4"}, + "not integer": {value: "four", want: "Config.loadPasswordHash - PASSWORD_HASH_CONCURRENCY"}, + "zero": {value: "0", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY must be between 1 and 4"}, + "negative": {value: "-1", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"}, + "over bound": {value: "5", want: "Config.ValidatePasswordHash - PASSWORD_HASH_CONCURRENCY"}, + } + for name, test := range tests { + _, err := LoadFromEnv(testEnvironment(map[string]string{"PASSWORD_HASH_CONCURRENCY": test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want) + } + } +} diff --git a/backend/config/practice.go b/backend/config/practice.go new file mode 100644 index 0000000..845d5ac --- /dev/null +++ b/backend/config/practice.go @@ -0,0 +1,95 @@ +package config + +import ( + "fmt" + "time" +) + +const ( + // Debug runs of one candidate are a technical abuse brake on the shared + // sandbox, not a product quota: a few runs a minute and a working + // session's worth an hour. + defaultPracticeRunsPerMinute = 6 + defaultPracticeRunsPerHour = 60 + maxPracticeRunsPerMinute = 600 + maxPracticeRunsPerHour = 36000 + // defaultPracticePollInterval is the wait between two reads of a running + // run and after a pass that found nothing to run. It is also the usual + // delay before a queued run starts. + defaultPracticePollInterval = time.Second + minPracticePollInterval = 10 * time.Millisecond + maxPracticePollInterval = 30 * time.Second + // defaultPracticeJobLease is how long a claimed practice job belongs to + // one worker without a renewal; every poll renews it. A worker that + // crashed delays its job by at most this long. + defaultPracticeJobLease = 30 * time.Second + maxPracticeJobLease = 10 * time.Minute + // defaultPracticeJobMaxAttempts bounds the failed tries and expired + // leases of a job before it fails without a verdict. + defaultPracticeJobMaxAttempts = 5 + maxPracticeJobMaxAttempts = 100 +) + +// PracticeSettings configure code practice: the rate limit of debug runs and +// the practice queue worker. The queue limits (one running, ten queued) are +// product rules in the practice usecase, not settings. +type PracticeSettings struct { + // RunsPerMinute and RunsPerHour bound the debug runs of one candidate. + RunsPerMinute int64 + RunsPerHour int64 + // PollInterval is the wait between two reads of a running run and after + // an empty pass of the queue worker. + PollInterval time.Duration + // JobLease is how long a claimed job belongs to one worker without a + // renewal. + JobLease time.Duration + // JobMaxAttempts bounds the failed tries of a job. + JobMaxAttempts int +} + +// LoadPracticeSettings reads the practice settings. requestTimeout is the +// code runner request timeout: a lease must outlast one runner call and one +// poll, or another worker could take a job over while its call is still +// running. +func LoadPracticeSettings(lookup LookupEnv, requestTimeout time.Duration) (PracticeSettings, error) { + settings := PracticeSettings{} + perMinute, err := intOrDefault(lookup, "PRACTICE_RUNS_PER_MINUTE", defaultPracticeRunsPerMinute) + if err != nil { + return PracticeSettings{}, err + } + perHour, err := intOrDefault(lookup, "PRACTICE_RUNS_PER_HOUR", defaultPracticeRunsPerHour) + if err != nil { + return PracticeSettings{}, err + } + settings.RunsPerMinute, settings.RunsPerHour = int64(perMinute), int64(perHour) + if settings.PollInterval, err = durationOrDefault(lookup, "PRACTICE_POLL_INTERVAL", defaultPracticePollInterval); err != nil { + return PracticeSettings{}, err + } + if settings.JobLease, err = durationOrDefault(lookup, "PRACTICE_JOB_LEASE", defaultPracticeJobLease); err != nil { + return PracticeSettings{}, err + } + if settings.JobMaxAttempts, err = intOrDefault(lookup, "PRACTICE_JOB_MAX_ATTEMPTS", defaultPracticeJobMaxAttempts); err != nil { + return PracticeSettings{}, err + } + return settings, settings.Validate(requestTimeout) +} + +// Validate checks the ranges. They are checked even without a code runner, so +// enabling the runner later cannot surface an old mistake. +func (settings PracticeSettings) Validate(requestTimeout time.Duration) error { + const location = "PracticeSettings.Validate" + switch { + case settings.RunsPerMinute < 1 || settings.RunsPerMinute > maxPracticeRunsPerMinute: + return fmt.Errorf("%s - PRACTICE_RUNS_PER_MINUTE must be between 1 and %d", location, maxPracticeRunsPerMinute) + case settings.RunsPerHour < settings.RunsPerMinute || settings.RunsPerHour > maxPracticeRunsPerHour: + return fmt.Errorf("%s - PRACTICE_RUNS_PER_HOUR must be between PRACTICE_RUNS_PER_MINUTE and %d", location, maxPracticeRunsPerHour) + case settings.PollInterval < minPracticePollInterval || settings.PollInterval > maxPracticePollInterval: + return fmt.Errorf("%s - PRACTICE_POLL_INTERVAL must be between %s and %s", location, minPracticePollInterval, maxPracticePollInterval) + case settings.JobLease <= requestTimeout+settings.PollInterval || settings.JobLease > maxPracticeJobLease: + return fmt.Errorf("%s - PRACTICE_JOB_LEASE must exceed CODE_RUNNER_REQUEST_TIMEOUT plus PRACTICE_POLL_INTERVAL and be at most %s", + location, maxPracticeJobLease) + case settings.JobMaxAttempts < 1 || settings.JobMaxAttempts > maxPracticeJobMaxAttempts: + return fmt.Errorf("%s - PRACTICE_JOB_MAX_ATTEMPTS must be between 1 and %d", location, maxPracticeJobMaxAttempts) + } + return nil +} diff --git a/backend/config/practice_test.go b/backend/config/practice_test.go new file mode 100644 index 0000000..16e48c7 --- /dev/null +++ b/backend/config/practice_test.go @@ -0,0 +1,43 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvPracticeDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + want := PracticeSettings{RunsPerMinute: 6, RunsPerHour: 60, PollInterval: time.Second, JobLease: 30 * time.Second, JobMaxAttempts: 5} + if settings.Practice != want { + t.Fatalf("practice defaults = %+v, want %+v", settings.Practice, want) + } +} + +func TestLoadFromEnvRejectsInvalidPracticeSettings(t *testing.T) { + cases := map[string]struct { + values map[string]string + message string + }{ + "zero runs per minute": {map[string]string{"PRACTICE_RUNS_PER_MINUTE": "0"}, "PRACTICE_RUNS_PER_MINUTE"}, + "hour below minute": { + map[string]string{"PRACTICE_RUNS_PER_MINUTE": "10", "PRACTICE_RUNS_PER_HOUR": "5"}, "PRACTICE_RUNS_PER_HOUR", + }, + "poll too short": {map[string]string{"PRACTICE_POLL_INTERVAL": "1ms"}, "PRACTICE_POLL_INTERVAL"}, + // The lease must outlast one runner request (10s by default) and a poll. + "lease within a request": {map[string]string{"PRACTICE_JOB_LEASE": "10s"}, "PRACTICE_JOB_LEASE"}, + "no attempts": {map[string]string{"PRACTICE_JOB_MAX_ATTEMPTS": "0"}, "PRACTICE_JOB_MAX_ATTEMPTS"}, + "malformed duration": {map[string]string{"PRACTICE_JOB_LEASE": "soon"}, "PRACTICE_JOB_LEASE"}, + } + for name, testCase := range cases { + t.Run(name, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(testCase.values)) + if err == nil || !strings.Contains(err.Error(), testCase.message) { + t.Fatalf("LoadFromEnv() error = %v, want one naming %s", err, testCase.message) + } + }) + } +} diff --git a/backend/config/relay.go b/backend/config/relay.go new file mode 100644 index 0000000..eb469de --- /dev/null +++ b/backend/config/relay.go @@ -0,0 +1,90 @@ +package config + +import ( + "errors" + "fmt" + "time" +) + +const ( + // The relay runs by default so committed events reach Kafka without an + // extra switch. It still needs DATABASE_URL; without it bootstrap skips + // the relay with a warning. + defaultRelayEnabled = true + // defaultRelayBatchSize bounds the events one pass locks and publishes in + // one transaction. + defaultRelayBatchSize = 100 + // maxRelayBatchSize keeps a pass, and the time its transaction holds row + // locks, short. + maxRelayBatchSize = 1000 + // defaultRelayPollInterval is the wait after a pass that found nothing. + defaultRelayPollInterval = time.Second + minRelayPollInterval = 10 * time.Millisecond + maxRelayPollInterval = 5 * time.Minute + // defaultRelayProduceTimeout bounds one publish, during which the pass + // holds its transaction open. + defaultRelayProduceTimeout = 10 * time.Second + // minRelayProduceTimeout is the smallest record delivery timeout that + // franz-go accepts. + minRelayProduceTimeout = time.Second + maxRelayProduceTimeout = 2 * time.Minute + // defaultRelayStatementTimeout bounds each SQL statement of a pass. The + // claim reads one batch through the partial indexes and the mark updates + // at most one batch, so a healthy database answers well below it. + defaultRelayStatementTimeout = 5 * time.Second + minRelayStatementTimeout = 100 * time.Millisecond + maxRelayStatementTimeout = time.Minute + // The backoff after a failed pass starts at the initial delay, doubles + // per consecutive failure, and stops growing at the maximum. + defaultRelayBackoffInitial = 500 * time.Millisecond + defaultRelayBackoffMax = 30 * time.Second + maxRelayBackoff = 10 * time.Minute +) + +func (config *Config) loadRelay(lookup LookupEnv) error { + var err error + if config.RelayEnabled, err = boolOrDefault(lookup, "RELAY_ENABLED", defaultRelayEnabled); err != nil { + return err + } + if config.RelayBatchSize, err = intOrDefault(lookup, "RELAY_BATCH_SIZE", defaultRelayBatchSize); err != nil { + return err + } + if config.RelayPollInterval, err = durationOrDefault(lookup, "RELAY_POLL_INTERVAL", defaultRelayPollInterval); err != nil { + return err + } + if config.RelayProduceTimeout, err = durationOrDefault(lookup, "RELAY_PRODUCE_TIMEOUT", defaultRelayProduceTimeout); err != nil { + return err + } + if config.RelayStatementTimeout, err = durationOrDefault(lookup, "RELAY_STATEMENT_TIMEOUT", defaultRelayStatementTimeout); err != nil { + return err + } + if config.RelayBackoffInitial, err = durationOrDefault(lookup, "RELAY_BACKOFF_INITIAL", defaultRelayBackoffInitial); err != nil { + return err + } + config.RelayBackoffMax, err = durationOrDefault(lookup, "RELAY_BACKOFF_MAX", defaultRelayBackoffMax) + return err +} + +// ValidateRelay checks the relay settings even when the relay is disabled, so +// enabling it later cannot surface an old mistake. +func (config Config) ValidateRelay() error { + if config.RelayBatchSize < 1 || config.RelayBatchSize > maxRelayBatchSize { + return fmt.Errorf("Config.ValidateRelay - RELAY_BATCH_SIZE must be between 1 and %d", maxRelayBatchSize) + } + if config.RelayPollInterval < minRelayPollInterval || config.RelayPollInterval > maxRelayPollInterval { + return fmt.Errorf("Config.ValidateRelay - RELAY_POLL_INTERVAL must be between %s and %s", minRelayPollInterval, maxRelayPollInterval) + } + if config.RelayProduceTimeout < minRelayProduceTimeout || config.RelayProduceTimeout > maxRelayProduceTimeout { + return fmt.Errorf("Config.ValidateRelay - RELAY_PRODUCE_TIMEOUT must be between %s and %s", minRelayProduceTimeout, maxRelayProduceTimeout) + } + if config.RelayStatementTimeout < minRelayStatementTimeout || config.RelayStatementTimeout > maxRelayStatementTimeout { + return fmt.Errorf("Config.ValidateRelay - RELAY_STATEMENT_TIMEOUT must be between %s and %s", minRelayStatementTimeout, maxRelayStatementTimeout) + } + if config.RelayBackoffInitial <= 0 { + return errors.New("Config.ValidateRelay - RELAY_BACKOFF_INITIAL must be positive") + } + if config.RelayBackoffMax < config.RelayBackoffInitial || config.RelayBackoffMax > maxRelayBackoff { + return fmt.Errorf("Config.ValidateRelay - RELAY_BACKOFF_MAX must be between RELAY_BACKOFF_INITIAL and %s", maxRelayBackoff) + } + return nil +} diff --git a/backend/config/relay_test.go b/backend/config/relay_test.go new file mode 100644 index 0000000..101f5c6 --- /dev/null +++ b/backend/config/relay_test.go @@ -0,0 +1,112 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvRelayAndTopicDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(nil)) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if !settings.RelayEnabled || settings.RelayBatchSize != 100 || settings.RelayPollInterval != time.Second || + settings.RelayProduceTimeout != 10*time.Second || settings.RelayStatementTimeout != 5*time.Second || settings.RelayBackoffInitial != 500*time.Millisecond || + settings.RelayBackoffMax != 30*time.Second { + t.Fatalf("unexpected relay defaults: enabled=%t batch=%d poll=%s produce=%s backoff=%s..%s", + settings.RelayEnabled, settings.RelayBatchSize, settings.RelayPollInterval, + settings.RelayProduceTimeout, settings.RelayBackoffInitial, settings.RelayBackoffMax) + } + if settings.KafkaEventsTopic != "lincodex.domain.events" || settings.KafkaEventsTopicPartitions != 3 || + settings.KafkaEventsTopicReplicationFactor != -1 || settings.KafkaEventsTopicMinInsyncReplicas != 0 || + !settings.KafkaProvisionTopics { + t.Fatalf("unexpected topic defaults: topic=%q partitions=%d replication=%d provision=%t", + settings.KafkaEventsTopic, settings.KafkaEventsTopicPartitions, + settings.KafkaEventsTopicReplicationFactor, settings.KafkaProvisionTopics) + } +} + +func TestLoadFromEnvReadsRelayAndTopicSettings(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "RELAY_ENABLED": " FALSE ", + "RELAY_BATCH_SIZE": " 1000 ", + "RELAY_POLL_INTERVAL": "10ms", + "RELAY_PRODUCE_TIMEOUT": "2m", + "RELAY_STATEMENT_TIMEOUT": "1m", + "RELAY_BACKOFF_INITIAL": "1s", + "RELAY_BACKOFF_MAX": "1s", + "KAFKA_EVENTS_TOPIC": " Team_1.events-v2 ", + "KAFKA_EVENTS_TOPIC_PARTITIONS": "1000", + "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR": "3", + "KAFKA_PROVISION_TOPICS": "false", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.RelayEnabled || settings.RelayBatchSize != 1000 || settings.RelayPollInterval != 10*time.Millisecond || + settings.RelayProduceTimeout != 2*time.Minute || settings.RelayStatementTimeout != time.Minute || settings.RelayBackoffInitial != time.Second || + settings.RelayBackoffMax != time.Second { + t.Fatal("relay settings were not loaded") + } + if settings.KafkaEventsTopic != "Team_1.events-v2" || settings.KafkaEventsTopicPartitions != 1000 || + settings.KafkaEventsTopicReplicationFactor != 3 || settings.KafkaProvisionTopics { + t.Fatal("topic settings were not loaded") + } +} + +func TestLoadFromEnvRejectsRelayAndTopicSettings(t *testing.T) { + tests := []struct { + key, value, want string + }{ + {key: "RELAY_ENABLED", value: "yes", want: "config.boolOrDefault - RELAY_ENABLED"}, + {key: "RELAY_BATCH_SIZE", value: "", want: "config.intOrDefault - RELAY_BATCH_SIZE"}, + {key: "RELAY_BATCH_SIZE", value: "ten", want: "config.intOrDefault - RELAY_BATCH_SIZE"}, + {key: "RELAY_BATCH_SIZE", value: "0", want: "Config.ValidateRelay - RELAY_BATCH_SIZE"}, + {key: "RELAY_BATCH_SIZE", value: "1001", want: "Config.ValidateRelay - RELAY_BATCH_SIZE"}, + {key: "RELAY_POLL_INTERVAL", value: "soon", want: "config.durationOrDefault - parse RELAY_POLL_INTERVAL"}, + {key: "RELAY_POLL_INTERVAL", value: "9ms", want: "Config.ValidateRelay - RELAY_POLL_INTERVAL"}, + {key: "RELAY_POLL_INTERVAL", value: "6m", want: "Config.ValidateRelay - RELAY_POLL_INTERVAL"}, + {key: "RELAY_PRODUCE_TIMEOUT", value: "999ms", want: "Config.ValidateRelay - RELAY_PRODUCE_TIMEOUT"}, + {key: "RELAY_PRODUCE_TIMEOUT", value: "3m", want: "Config.ValidateRelay - RELAY_PRODUCE_TIMEOUT"}, + {key: "RELAY_STATEMENT_TIMEOUT", value: "99ms", want: "Config.ValidateRelay - RELAY_STATEMENT_TIMEOUT"}, + {key: "RELAY_STATEMENT_TIMEOUT", value: "61s", want: "Config.ValidateRelay - RELAY_STATEMENT_TIMEOUT"}, + {key: "RELAY_BACKOFF_INITIAL", value: "0s", want: "Config.ValidateRelay - RELAY_BACKOFF_INITIAL"}, + {key: "RELAY_BACKOFF_MAX", value: "100ms", want: "Config.ValidateRelay - RELAY_BACKOFF_MAX"}, + {key: "RELAY_BACKOFF_MAX", value: "11m", want: "Config.ValidateRelay - RELAY_BACKOFF_MAX"}, + {key: "RELAY_BACKOFF_INITIAL", value: "40s", want: "Config.ValidateRelay - RELAY_BACKOFF_MAX"}, + {key: "KAFKA_EVENTS_TOPIC", value: "", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"}, + {key: "KAFKA_EVENTS_TOPIC", value: "..", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"}, + {key: "KAFKA_EVENTS_TOPIC", value: "domain events", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"}, + {key: "KAFKA_EVENTS_TOPIC", value: "events/secret", want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"}, + {key: "KAFKA_EVENTS_TOPIC", value: strings.Repeat("a", 250), want: "Config.ValidateKafka - KAFKA_EVENTS_TOPIC"}, + {key: "KAFKA_EVENTS_TOPIC_PARTITIONS", value: "0", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_PARTITIONS"}, + {key: "KAFKA_EVENTS_TOPIC_PARTITIONS", value: "1001", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_PARTITIONS"}, + {key: "KAFKA_EVENTS_TOPIC_PARTITIONS", value: "many", want: "config.intOrDefault - KAFKA_EVENTS_TOPIC_PARTITIONS"}, + {key: "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR", value: "0", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR"}, + {key: "KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR", value: "32768", want: "Config.loadKafkaTopics - KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR"}, + {key: "KAFKA_PROVISION_TOPICS", value: "1", want: "config.boolOrDefault - KAFKA_PROVISION_TOPICS"}, + } + for _, test := range tests { + t.Run(test.key+"/"+test.value, func(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv() error = %v, want an error starting with %q", err, test.want) + } + if strings.Contains(err.Error(), "secret") { + t.Fatal("configuration error disclosed the value") + } + }) + } +} + +func TestValidateRelayChecksSettingsEvenWhenDisabled(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"RELAY_ENABLED": "false"})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + settings.RelayBatchSize = 0 + if err := settings.Validate(); err == nil || !strings.HasPrefix(err.Error(), "Config.ValidateRelay - RELAY_BATCH_SIZE") { + t.Fatalf("Validate() error = %v, want the relay batch size error", err) + } +} diff --git a/backend/config/semantic.go b/backend/config/semantic.go new file mode 100644 index 0000000..dfa0ef6 --- /dev/null +++ b/backend/config/semantic.go @@ -0,0 +1,178 @@ +package config + +import ( + "errors" + "fmt" + "log/slog" + "net/url" + "strings" + "time" +) + +const ( + // Semantic matching is off by default: a stand without the ML service + // ranks with the neutral Sem, as before. + defaultSemanticMatchingEnabled = false + // defaultMLRequestTimeout bounds one embedding request. A whole card is at + // most a dozen texts; on four CPU threads each takes well under a second. + defaultMLRequestTimeout = 30 * time.Second + maxMLRequestTimeout = 5 * time.Minute + // After this many consecutive failures the client stops calling the ML + // service for the open duration, so a dead service costs no timeouts. + defaultMLCircuitFailures = 3 + maxMLCircuitFailures = 100 + defaultMLCircuitOpen = 30 * time.Second + maxMLCircuitOpen = time.Hour + // Repository checks call api.github.com; they are off unless enabled. + defaultGitHubChecksEnabled = false + defaultGitHubTimeout = 10 * time.Second + maxGitHubTimeout = time.Minute + // minMLServiceTokenLength matches the ML service: 32 printable characters + // of a CSPRNG token are far beyond an online guess. + minMLServiceTokenLength = 32 + maxMLServiceTokenLength = 512 + // defaultRepositoryCheckInterval is the shortest time between two check + // requests of one candidate through the refresh operation. + defaultRepositoryCheckInterval = 10 * time.Minute + maxRepositoryCheckInterval = 24 * time.Hour +) + +// SemanticSettings configure semantic matching and repository checks. +// +// String, GoString, Format, and LogValue redact everything, because the ML +// service token and the GitHub token are secrets of the deployment. +type SemanticSettings struct { + // SemanticMatchingEnabled schedules vector jobs on changes and runs them + // against MLServiceURL. The search reads stored vectors either way. + SemanticMatchingEnabled bool + MLServiceURL string + // MLServiceToken is the shared bearer token of the ML service. It is + // required while semantic matching is enabled and is a secret: never log it. + MLServiceToken string + MLRequestTimeout time.Duration + MLCircuitFailures int + MLCircuitOpen time.Duration + // GitHubChecksEnabled schedules and runs repository checks against the + // public GitHub API. + GitHubChecksEnabled bool + // GitHubToken is an optional read-only token that raises the GitHub rate + // limit. It is a secret: never log it. + GitHubToken string + GitHubTimeout time.Duration + RepositoryCheckInterval time.Duration +} + +const redactedSemanticSettings = "[semantic settings redacted]" + +func (settings SemanticSettings) String() string { return redactedSemanticSettings } + +func (settings SemanticSettings) GoString() string { return redactedSemanticSettings } + +// Format redacts every verb; without it %+v would print the tokens. +func (settings SemanticSettings) Format(state fmt.State, _ rune) { + _, _ = state.Write([]byte(redactedSemanticSettings)) +} + +func (settings SemanticSettings) LogValue() slog.Value { + return slog.StringValue(redactedSemanticSettings) +} + +// LoadSemanticSettings reads the semantic settings; the operator commands +// that need only them use it directly. +func LoadSemanticSettings(lookup LookupEnv) (SemanticSettings, error) { + settings := SemanticSettings{ + MLServiceURL: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_URL", "")), + MLServiceToken: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_TOKEN", "")), + GitHubToken: strings.TrimSpace(valueOrDefault(lookup, "GITHUB_TOKEN", "")), + } + var err error + if settings.SemanticMatchingEnabled, err = boolOrDefault(lookup, "SEMANTIC_MATCHING_ENABLED", defaultSemanticMatchingEnabled); err != nil { + return SemanticSettings{}, err + } + if settings.MLRequestTimeout, err = durationOrDefault(lookup, "ML_REQUEST_TIMEOUT", defaultMLRequestTimeout); err != nil { + return SemanticSettings{}, err + } + if settings.MLCircuitFailures, err = intOrDefault(lookup, "ML_CIRCUIT_FAILURES", defaultMLCircuitFailures); err != nil { + return SemanticSettings{}, err + } + if settings.MLCircuitOpen, err = durationOrDefault(lookup, "ML_CIRCUIT_OPEN", defaultMLCircuitOpen); err != nil { + return SemanticSettings{}, err + } + if settings.GitHubChecksEnabled, err = boolOrDefault(lookup, "GITHUB_REPOSITORY_CHECKS_ENABLED", defaultGitHubChecksEnabled); err != nil { + return SemanticSettings{}, err + } + if settings.GitHubTimeout, err = durationOrDefault(lookup, "GITHUB_TIMEOUT", defaultGitHubTimeout); err != nil { + return SemanticSettings{}, err + } + if settings.RepositoryCheckInterval, err = durationOrDefault(lookup, "REPOSITORY_CHECK_INTERVAL", defaultRepositoryCheckInterval); err != nil { + return SemanticSettings{}, err + } + return settings, settings.Validate() +} + +// Validate checks the values even while the features are off, so enabling +// them later cannot surface an old mistake. +func (settings SemanticSettings) Validate() error { + if err := settings.validateMLService(); err != nil { + return err + } + return settings.validateLimits() +} + +func (settings SemanticSettings) validateMLService() error { + const location = "SemanticSettings.Validate" + if settings.SemanticMatchingEnabled && settings.MLServiceURL == "" { + return errors.New(location + " - ML_SERVICE_URL is required when SEMANTIC_MATCHING_ENABLED is true") + } + if settings.SemanticMatchingEnabled && settings.MLServiceToken == "" { + return errors.New(location + " - ML_SERVICE_TOKEN is required when SEMANTIC_MATCHING_ENABLED is true") + } + if err := validateMLServiceToken(settings.MLServiceToken); err != nil { + return err + } + if settings.MLServiceURL != "" { + parsed, err := url.Parse(settings.MLServiceURL) + if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || + parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || strings.Trim(parsed.Path, "/") != "" { + return errors.New(location + " - ML_SERVICE_URL must be an http or https origin without credentials or path") + } + } + return nil +} + +// validateMLServiceToken checks an optional token; the messages never quote +// the value. +func validateMLServiceToken(token string) error { + const location = "SemanticSettings.Validate" + if token == "" { + return nil + } + if len(token) < minMLServiceTokenLength || len(token) > maxMLServiceTokenLength { + return errors.New(location + " - ML_SERVICE_TOKEN must have between 32 and 512 characters") + } + for _, character := range token { + if character < 0x21 || character > 0x7e { + return errors.New(location + " - ML_SERVICE_TOKEN must be printable ASCII without white space") + } + } + return nil +} + +func (settings SemanticSettings) validateLimits() error { + const location = "SemanticSettings.Validate" + switch { + case settings.MLRequestTimeout <= 0 || settings.MLRequestTimeout > maxMLRequestTimeout: + return errors.New(location + " - ML_REQUEST_TIMEOUT must be positive and at most 5m") + case settings.MLCircuitFailures < 1 || settings.MLCircuitFailures > maxMLCircuitFailures: + return errors.New(location + " - ML_CIRCUIT_FAILURES must be between 1 and 100") + case settings.MLCircuitOpen <= 0 || settings.MLCircuitOpen > maxMLCircuitOpen: + return errors.New(location + " - ML_CIRCUIT_OPEN must be positive and at most 1h") + case settings.GitHubTimeout <= 0 || settings.GitHubTimeout > maxGitHubTimeout: + return errors.New(location + " - GITHUB_TIMEOUT must be positive and at most 1m") + case settings.RepositoryCheckInterval <= 0 || settings.RepositoryCheckInterval > maxRepositoryCheckInterval: + return errors.New(location + " - REPOSITORY_CHECK_INTERVAL must be positive and at most 24h") + case strings.ContainsAny(settings.GitHubToken, " \t\r\n"): + return errors.New(location + " - GITHUB_TOKEN must not contain white space") + } + return nil +} diff --git a/backend/config/semantic_test.go b/backend/config/semantic_test.go new file mode 100644 index 0000000..1132c8e --- /dev/null +++ b/backend/config/semantic_test.go @@ -0,0 +1,58 @@ +package config + +import ( + "fmt" + "strings" + "testing" + "time" +) + +func lookupOf(values map[string]string) LookupEnv { + return func(key string) (string, bool) { + value, ok := values[key] + return value, ok + } +} + +func TestSemanticSettingsDefaultOffAndValidateTheMLOrigin(t *testing.T) { + settings, err := LoadSemanticSettings(lookupOf(nil)) + if err != nil || settings.SemanticMatchingEnabled || settings.GitHubChecksEnabled || + settings.MLRequestTimeout != 30*time.Second || settings.RepositoryCheckInterval != 10*time.Minute { + t.Fatalf("defaults = %+v, %v", settings, err) + } + const mlToken = "ml-service-token-0123456789abcdefghij" + enabled, err := LoadSemanticSettings(lookupOf(map[string]string{ + "SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://192.168.10.25:8790", "ML_SERVICE_TOKEN": mlToken, + "GITHUB_TOKEN": "token-value", + })) + if err != nil || !enabled.SemanticMatchingEnabled || enabled.GitHubToken != "token-value" || enabled.MLServiceToken != mlToken { + t.Fatalf("enabled = %v, %v", enabled.SemanticMatchingEnabled, err) + } + for _, rendered := range []string{fmt.Sprintf("%v %+v %#v %s", enabled, enabled, enabled, enabled), enabled.LogValue().String()} { + if strings.Contains(rendered, mlToken) || strings.Contains(rendered, "token-value") { + t.Fatalf("formatted settings quote a token: %s", rendered) + } + } + for name, values := range map[string]map[string]string{ + "missing URL": {"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_TOKEN": "ml-service-token-0123456789abcdefghij"}, + "missing token": {"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://ml:8000"}, + "short token": {"ML_SERVICE_TOKEN": "secret-but-short"}, + "spaced token": {"ML_SERVICE_TOKEN": "secret 0123456789abcdefghijklmnopqrstuvwxyz"}, + "credentials": {"ML_SERVICE_URL": "http://user:secret@ml:8000"}, + "path": {"ML_SERVICE_URL": "http://ml:8000/v1"}, + "scheme": {"ML_SERVICE_URL": "file:///tmp/ml"}, + "timeout": {"ML_REQUEST_TIMEOUT": "0s"}, + "circuit": {"ML_CIRCUIT_FAILURES": "0"}, + "interval": {"REPOSITORY_CHECK_INTERVAL": "48h"}, + "token whitespace": {"GITHUB_TOKEN": "a b"}, + } { + _, err := LoadSemanticSettings(lookupOf(values)) + if err == nil { + t.Errorf("%s: invalid settings were accepted", name) + continue + } + if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "a b") { + t.Errorf("%s: the error quotes the value: %v", name, err) + } + } +} diff --git a/backend/config/trusted_proxies.go b/backend/config/trusted_proxies.go new file mode 100644 index 0000000..3204467 --- /dev/null +++ b/backend/config/trusted_proxies.go @@ -0,0 +1,48 @@ +package config + +import ( + "fmt" + "net/netip" + "strings" +) + +// loadTrustedProxies reads TRUSTED_PROXY_CIDRS, a comma-separated list of +// CIDR prefixes or single addresses of the reverse proxies in front of the +// API. Unset or empty means no proxy is trusted: the client address is the +// connecting peer and X-Forwarded-For is ignored. +func (config *Config) loadTrustedProxies(lookup LookupEnv) error { + value, _ := lookup("TRUSTED_PROXY_CIDRS") + for entry := range strings.SplitSeq(value, ",") { + entry = strings.TrimSpace(entry) + if entry == "" { + continue + } + prefix, err := parseProxyPrefix(entry) + if err != nil { + return fmt.Errorf("Config.loadTrustedProxies - TRUSTED_PROXY_CIDRS entry %q: %w", entry, err) + } + config.TrustedProxyCIDRs = append(config.TrustedProxyCIDRs, prefix) + } + return nil +} + +func parseProxyPrefix(entry string) (netip.Prefix, error) { + if !strings.Contains(entry, "/") { + addr, err := netip.ParseAddr(entry) + if err != nil { + return netip.Prefix{}, fmt.Errorf("must be an IP address or a CIDR prefix") + } + addr = addr.Unmap() + return netip.PrefixFrom(addr, addr.BitLen()), nil + } + prefix, err := netip.ParsePrefix(entry) + if err != nil { + return netip.Prefix{}, fmt.Errorf("must be an IP address or a CIDR prefix") + } + if prefix.Bits() == 0 { + // A prefix that matches every address would trust every client and + // let it choose its own address. + return netip.Prefix{}, fmt.Errorf("must not match every address") + } + return prefix.Masked(), nil +} diff --git a/backend/config/trusted_proxies_test.go b/backend/config/trusted_proxies_test.go new file mode 100644 index 0000000..9ac6c24 --- /dev/null +++ b/backend/config/trusted_proxies_test.go @@ -0,0 +1,45 @@ +package config + +import ( + "strings" + "testing" +) + +func TestLoadFromEnvTrustedProxyCIDRs(t *testing.T) { + tests := map[string]struct { + value string + want []string + }{ + "unset": {value: "", want: nil}, + "list": {value: " 172.16.0.0/12, 10.79.0.1 ,fd00::/8", want: []string{"172.16.0.0/12", "10.79.0.1/32", "fd00::/8"}}, + "masked": {value: "10.79.0.1/30", want: []string{"10.79.0.0/30"}}, + "empty items": {value: ",,10.0.0.0/8,", want: []string{"10.0.0.0/8"}}, + } + for name, test := range tests { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"TRUSTED_PROXY_CIDRS": test.value})) + if err != nil { + t.Fatalf("LoadFromEnv(%s) error = %v", name, err) + } + got := make([]string, 0, len(settings.TrustedProxyCIDRs)) + for _, prefix := range settings.TrustedProxyCIDRs { + got = append(got, prefix.String()) + } + if strings.Join(got, ";") != strings.Join(test.want, ";") { + t.Fatalf("LoadFromEnv(%s) TrustedProxyCIDRs = %v, want %v", name, got, test.want) + } + } +} + +func TestLoadFromEnvRejectsTrustedProxyCIDRs(t *testing.T) { + for name, value := range map[string]string{ + "not an address": "proxy.internal", + "bad prefix": "10.0.0.0/33", + "match all v4": "0.0.0.0/0", + "match all v6": "::/0", + } { + _, err := LoadFromEnv(testEnvironment(map[string]string{"TRUSTED_PROXY_CIDRS": value})) + if err == nil || !strings.Contains(err.Error(), "Config.loadTrustedProxies - TRUSTED_PROXY_CIDRS") { + t.Fatalf("LoadFromEnv(%s) error = %v, want a TRUSTED_PROXY_CIDRS error", name, err) + } + } +} diff --git a/backend/db/evidence_queries_test.go b/backend/db/evidence_queries_test.go new file mode 100644 index 0000000..3a0c5ea --- /dev/null +++ b/backend/db/evidence_queries_test.go @@ -0,0 +1,165 @@ +package db + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" +) + +var ( + evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`) + // evidenceReaders are the only queries that may name the evidence tables. + evidenceReaders = []string{ + "ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence", "ListOrganizationVisibleEvidenceBatch", + } + // evidenceForbiddenSources are tables whose content must never reach the + // evidence reads: raw answers and items, results with their scores, + // attempts, signals, and the anti-cheat review band. + evidenceForbiddenSources = []string{ + "assessment_attempt_results", "assessment_attempt_items", "assessment_attempts", + "assessment_attempt_reviews", "assessment_attempt_origin_marks", "assessment_answer_observations", + "assessment_answer_fingerprint_holders", "assessment_answer_family_totals", + "assessment_signal_events", "assessment_signal_batches", "assessment_signal_idempotency_outcomes", + "assessment_attempt_idempotency_outcomes", "candidate_assessment_categories", + "assessment_synthetic_category_reviews", "candidate_profile_claims", "candidate_questionnaires", + } +) + +// evidenceStatements returns the statement of every query of the query files +// by name, with comments removed. +func evidenceStatements(t *testing.T) map[string]string { + t.Helper() + files, err := filepath.Glob("queries/*.sql") + if err != nil || len(files) == 0 { + t.Fatalf("list the query files = %v, %v", files, err) + } + statements := make(map[string]string) + for _, file := range files { + content, err := os.ReadFile(file) + if err != nil { + t.Fatalf("read %s: %v", file, err) + } + text := string(content) + headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1) + for index, header := range headers { + end := len(text) + if index+1 < len(headers) { + end = headers[index+1][0] + } + statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "") + statements[text[header[2]:header[3]]] = strings.ToLower(strings.Join(strings.Fields(statement), " ")) + } + } + return statements +} + +// Only the evidence reads name the projection, and the projection reads +// reach no table of raw answers, scores, failures, or anti-cheat data. +func TestEvidenceReadsNameOnlyTheProjection(t *testing.T) { + statements := evidenceStatements(t) + var found []string + for name, statement := range statements { + if evidenceTableName.MatchString(statement) { + found = append(found, name) + } + } + slices.Sort(found) + want := slices.Clone(evidenceReaders) + slices.Sort(want) + if !slices.Equal(found, want) { + t.Fatalf("queries that name the evidence tables = %v, want only %v", found, want) + } + for _, name := range evidenceReaders { + statement := statements[name] + for _, forbidden := range evidenceForbiddenSources { + if regexp.MustCompile(`\b` + forbidden + `\b`).MatchString(statement) { + t.Errorf("%s reads %s: %s", name, forbidden, statement) + } + } + } +} + +// The organization read goes through the effective publication view, excludes +// the candidates that hide the organization, requires the categories field, +// and returns an allowlist of columns with no identifier. +func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) { + statement := evidenceStatements(t)["ListOrganizationVisibleEvidence"] + if statement == "" { + t.Fatal("the organization evidence query is missing") + } + for _, required := range []string{ + "from candidate_effective_publications as effective", + "from candidate_hidden_organizations as hidden", + "not exists", + "hidden.organization_id = sqlc.arg(organization_id)", + "'categories' = any(effective.fields)", + "fact.visibility = 'visible'", + "effective.user_id = sqlc.arg(candidate_id)", + "select distinct on (skill.skill_code)", + "(skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])", + "fact.kind = 'measurement'", + } { + if !strings.Contains(statement, required) { + t.Errorf("organization evidence query lacks %q: %s", required, statement) + } + } + selected := statement[len("select"):strings.Index(statement, " from candidate_effective_publications")] + for _, private := range []string{"fact.id", "event_id", "result_id", "candidate_id", "visibility"} { + if strings.Contains(selected, private) { + t.Errorf("organization evidence query selects %q: %s", private, selected) + } + } + // The columns are exactly the skill, the grade, the trust level, and the + // year, with the basis and calibration of the method: nothing else of the + // fact leaves. + const wantSelected = " distinct on (skill.skill_code) skill.skill_code as skill, fact.grade, fact.trust, " + + "fact.basis, fact.calibration_status, " + + "extract(year from fact.occurred_at at time zone 'utc')::integer as observed_year" + if selected != wantSelected { + t.Errorf("organization evidence query selects %q, want %q", selected, wantSelected) + } + if strings.Contains(statement, "candidate_publications") { + t.Errorf("organization evidence query reads the publication table directly: %s", statement) + } +} + +// The batch read repeats every barrier of the single organization read, and +// the match-search queries name no evidence table. +func TestOrganizationEvidenceBatchReadRepeatsTheVisibilityBarrier(t *testing.T) { + statements := evidenceStatements(t) + statement := statements["ListOrganizationVisibleEvidenceBatch"] + if statement == "" { + t.Fatal("the batch organization evidence query is missing") + } + for _, required := range []string{ + "inner join candidate_effective_publications as effective", + "from candidate_hidden_organizations as hidden", + "not exists", + "hidden.organization_id = sqlc.arg(organization_id)", + "'categories' = any(effective.fields)", + "fact.visibility = 'visible'", + "fact.kind = 'measurement'", + "(skill.skill_code || '/' || fact.grade) = wanted.category", + } { + if !strings.Contains(statement, required) { + t.Errorf("batch organization evidence query lacks %q: %s", required, statement) + } + } + if strings.Contains(statement, "candidate_publications") && !strings.Contains(statement, "candidate_effective_publications") { + t.Errorf("batch organization evidence query reads the publication table directly: %s", statement) + } + for _, private := range []string{"fact.id,", "event_id", "result_id", "fact.visibility,", "occurred_at,"} { + selected := statement[len("select"):strings.Index(statement, " from (")] + if strings.Contains(selected, private) { + t.Errorf("batch organization evidence query selects %q: %s", private, selected) + } + } + for name, search := range statements { + if strings.HasPrefix(name, "CountReal") && evidenceTableName.MatchString(search) { + t.Errorf("%s names an evidence table: %s", name, search) + } + } +} diff --git a/backend/db/migrations.go b/backend/db/migrations.go new file mode 100644 index 0000000..61811ed --- /dev/null +++ b/backend/db/migrations.go @@ -0,0 +1,25 @@ +// Package db embeds the versioned SQL migrations so the backend binary applies +// exactly the schema it was built with. The SQL files stay in db/migrations, +// where sqlc and sqlfluff also read them; go:embed cannot reach a parent +// directory, so the embedding package lives next to that directory. +package db + +import ( + "embed" + "fmt" + "io/fs" +) + +const migrationsDirectory = "migrations" + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +// Migrations returns the goose SQL migrations with file names at the root. +func Migrations() (fs.FS, error) { + migrations, err := fs.Sub(migrationFiles, migrationsDirectory) + if err != nil { + return nil, fmt.Errorf("db.Migrations - open embedded migrations: %w", err) + } + return migrations, nil +} diff --git a/backend/db/migrations/.gitkeep b/backend/db/migrations/.gitkeep deleted file mode 100644 index 8b13789..0000000 --- a/backend/db/migrations/.gitkeep +++ /dev/null @@ -1 +0,0 @@ - diff --git a/backend/db/migrations/00001_create_outbox_events.sql b/backend/db/migrations/00001_create_outbox_events.sql new file mode 100644 index 0000000..4e55b5d --- /dev/null +++ b/backend/db/migrations/00001_create_outbox_events.sql @@ -0,0 +1,54 @@ +-- +goose Up +-- Transactional outbox: a business transaction appends its domain events here +-- in the same PostgreSQL transaction as the business change. A relay publishes +-- unpublished rows to Kafka. Payloads carry identifiers and minimal facts only, +-- never contact data, tokens, passwords, or document contents. +CREATE TABLE outbox_events ( + -- Monotonic insertion key for the relay scan. It is assigned at insert + -- time, so a transaction that waited on a row lock gets a larger value + -- than the transaction it waited for. + position bigint GENERATED ALWAYS AS IDENTITY, + event_id uuid NOT NULL, + event_type text NOT NULL, + schema_version integer NOT NULL, + aggregate_type text NOT NULL, + aggregate_id uuid NOT NULL, + aggregate_version bigint NOT NULL, + payload jsonb NOT NULL, + -- Statement time rather than transaction start time. Informational only: + -- ordering uses position and aggregate_version. + occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(), + published_at timestamptz, + CONSTRAINT outbox_events_pkey PRIMARY KEY (event_id), + CONSTRAINT outbox_events_position_key UNIQUE (position), + CONSTRAINT outbox_events_aggregate_version_event_type_key UNIQUE ( + aggregate_type, aggregate_id, aggregate_version, event_type + ), + CONSTRAINT outbox_events_event_type_format CHECK ( + char_length(event_type) <= 128 + AND event_type ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$' + ), + CONSTRAINT outbox_events_schema_version_positive CHECK (schema_version > 0), + CONSTRAINT outbox_events_aggregate_type_format CHECK ( + char_length(aggregate_type) <= 64 + AND aggregate_type ~ '^[a-z][a-z0-9_]*$' + ), + CONSTRAINT outbox_events_aggregate_version_positive CHECK ( + aggregate_version > 0 + ), + -- The payload size limit is enforced in Go on compact JSON. The jsonb text + -- and binary forms differ in size from that input, so a database length + -- check could reject an event that the domain accepted. + CONSTRAINT outbox_events_payload_object CHECK ( + jsonb_typeof(payload) = 'object' + ) +); + +-- Supports the relay scan of unpublished events in insertion order. The index +-- shrinks as events are published. +CREATE INDEX outbox_events_unpublished_idx +ON outbox_events (position) +WHERE published_at IS NULL; + +-- +goose Down +DROP TABLE outbox_events; diff --git a/backend/db/migrations/00002_create_identity_tables.sql b/backend/db/migrations/00002_create_identity_tables.sql new file mode 100644 index 0000000..a40df8e --- /dev/null +++ b/backend/db/migrations/00002_create_identity_tables.sql @@ -0,0 +1,167 @@ +-- +goose Up +-- Identity storage: accounts, one-time email tokens, and server-side sessions. +-- Passwords, raw email tokens, and raw session tokens are never stored; only +-- an Argon2id PHC string and SHA-256 digests are. Every timestamp comes from +-- the application clock, so expiry checks and the stored deadlines use one +-- clock. Enum-like columns are text with CHECK constraints rather than +-- PostgreSQL enum types: a new value then changes one constraint in a later +-- migration, which can also be rolled back, while an enum value cannot be +-- removed and cannot be used in the transaction that adds it. +CREATE TABLE users ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- Delivery form: trimmed ASCII, letter case as typed. + email text NOT NULL, + -- Comparison key computed in Go: the delivery form with A-Z lowercased. + email_normalized text NOT NULL, + -- Argon2id PHC string; never the password. + password_hash text NOT NULL, + scenario text NOT NULL, + onboarding_step text NOT NULL, + email_verified_at timestamptz, + -- Advanced on every registration of the unverified email. Email tokens + -- are bound to the version they were issued for. + registration_version bigint NOT NULL, + -- Time of the latest registration; the planned cleanup of unverified + -- accounts counts its deadline from here. + last_registered_at timestamptz NOT NULL, + -- Optimistic concurrency version, advanced on every update. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT users_pkey PRIMARY KEY (id), + CONSTRAINT users_email_normalized_key UNIQUE (email_normalized), + -- Addresses are ASCII until the mailer supports SMTPUTF8: one byte per + -- character in the UTF-8 database encoding. + CONSTRAINT users_email_ascii CHECK ( + char_length(email) BETWEEN 3 AND 254 + AND octet_length(email) = char_length(email) + ), + -- translate() maps A-Z by code point, independent of the collation, + -- unlike lower(). + CONSTRAINT users_email_normalized_rule CHECK ( + email_normalized = translate( + email, + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', + 'abcdefghijklmnopqrstuvwxyz' + ) + ), + CONSTRAINT users_password_hash_format CHECK ( + char_length(password_hash) <= 512 + AND password_hash + ~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ), + CONSTRAINT users_scenario_onboarding_step CHECK ( + ( + scenario = 'candidate' + AND onboarding_step IN ( + 'candidate_consents', + 'candidate_profile', + 'candidate_questionnaire', + 'candidate_assessment', + 'completed' + ) + ) + OR ( + scenario = 'employer' + AND onboarding_step IN ('employer_company', 'completed') + ) + ), + CONSTRAINT users_registration_version_positive CHECK ( + registration_version > 0 + ), + CONSTRAINT users_version_positive CHECK (version > 0), + CONSTRAINT users_timestamps_after_creation CHECK ( + updated_at >= created_at + AND last_registered_at >= created_at + AND (email_verified_at IS NULL OR email_verified_at >= created_at) + ) +); + +-- Supports the planned cleanup of accounts that stay unverified after their +-- latest registration. Verified accounts are not indexed. +CREATE INDEX users_unverified_last_registered_at_idx +ON users (last_registered_at) +WHERE email_verified_at IS NULL; + +CREATE TABLE email_tokens ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + user_id uuid NOT NULL, + purpose text NOT NULL, + -- SHA-256 of the raw token as 32 raw bytes: half the size of hex text, + -- with an exact length check and no letter-case or encoding variants. + token_hash bytea NOT NULL, + registration_version bigint NOT NULL, + created_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + consumed_at timestamptz, + -- Set when a re-registration or a resend replaces the token. + invalidated_at timestamptz, + CONSTRAINT email_tokens_pkey PRIMARY KEY (id), + CONSTRAINT email_tokens_token_hash_key UNIQUE (token_hash), + CONSTRAINT email_tokens_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification') + ), + CONSTRAINT email_tokens_token_hash_sha256 CHECK ( + octet_length(token_hash) = 32 + ), + CONSTRAINT email_tokens_registration_version_positive CHECK ( + registration_version > 0 + ), + CONSTRAINT email_tokens_expiry_after_creation CHECK ( + expires_at > created_at + ), + -- A token ends at most once: either consumed or invalidated. + CONSTRAINT email_tokens_single_outcome CHECK ( + consumed_at IS NULL OR invalidated_at IS NULL + ), + CONSTRAINT email_tokens_outcome_after_creation CHECK ( + (consumed_at IS NULL OR consumed_at >= created_at) + AND (invalidated_at IS NULL OR invalidated_at >= created_at) + ) +); + +-- Serves invalidation of a user's tokens for one purpose and the cascade +-- delete of a user's tokens. +CREATE INDEX email_tokens_user_id_purpose_idx +ON email_tokens (user_id, purpose); + +CREATE TABLE sessions ( + -- UUIDv7 generated in Go; internal only, never sent to the client. + id uuid NOT NULL, + user_id uuid NOT NULL, + -- SHA-256 of the raw session token that the cookie carries. + token_hash bytea NOT NULL, + created_at timestamptz NOT NULL, + -- The idle timeout counts from here. + last_seen_at timestamptz NOT NULL, + -- Absolute deadline fixed at creation. + expires_at timestamptz NOT NULL, + revoked_at timestamptz, + CONSTRAINT sessions_pkey PRIMARY KEY (id), + CONSTRAINT sessions_token_hash_key UNIQUE (token_hash), + CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT sessions_token_hash_sha256 CHECK ( + octet_length(token_hash) = 32 + ), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at), + CONSTRAINT sessions_last_seen_after_creation CHECK ( + last_seen_at >= created_at + ), + CONSTRAINT sessions_revoked_after_creation CHECK ( + revoked_at IS NULL OR revoked_at >= created_at + ) +); + +-- Serves revocation of all of a user's sessions and the cascade delete. +CREATE INDEX sessions_user_id_idx +ON sessions (user_id); + +-- +goose Down +DROP TABLE sessions; +DROP TABLE email_tokens; +DROP TABLE users; diff --git a/backend/db/migrations/00003_create_policy_versions.sql b/backend/db/migrations/00003_create_policy_versions.sql new file mode 100644 index 0000000..2dd2594 --- /dev/null +++ b/backend/db/migrations/00003_create_policy_versions.sql @@ -0,0 +1,116 @@ +-- +goose Up +-- Versioned product policy: deadlines, quotas, thresholds, and coefficients +-- that product rules read. Every row is one immutable version of one policy +-- family. Records built under a policy, such as grade decisions, selection +-- snapshots, and invitations, will store the policy_versions.id they used, so +-- a newer version never changes how an earlier decision was made. +CREATE TABLE policy_versions ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- Policy family. Each family has one document layout and one decoder in + -- Go; "product" is the only family. A new family changes this CHECK. + policy_key text NOT NULL, + -- Numbered from 1 within the family; the newest publication has the + -- highest number. + version integer NOT NULL, + -- Calibration state of the whole version, the flag consumers read. "demo" + -- values are an initial policy for verification and make no calibrated + -- quality claim. + kind text NOT NULL, + -- The version can apply to decisions made at or after this time. A NULL + -- in the INSERT means "at publication"; the stamp trigger fills it in. + effective_at timestamptz NOT NULL, + -- Operator identity such as "system:demo-seed" or "operator:". + -- Never an email address or other contact data. + author text NOT NULL, + -- The typed policy serialized by the domain in canonical form. jsonb + -- normalizes key order and whitespace; integrity is checked against + -- document_sha256 after the domain re-encodes the decoded document. + document jsonb NOT NULL, + -- SHA-256 of the canonical document bytes, 32 raw bytes. + document_sha256 bytea NOT NULL, + -- Publication time from the database clock, set by the stamp trigger on + -- every insert; a value from the caller is ignored. + created_at timestamptz NOT NULL, + CONSTRAINT policy_versions_pkey PRIMARY KEY (id), + CONSTRAINT policy_versions_policy_key_version_key UNIQUE ( + policy_key, version + ), + CONSTRAINT policy_versions_policy_key_known CHECK ( + policy_key IN ('product') + ), + CONSTRAINT policy_versions_version_positive CHECK (version > 0), + CONSTRAINT policy_versions_kind_known CHECK ( + kind IN ('demo', 'calibrated') + ), + CONSTRAINT policy_versions_author_format CHECK ( + char_length(author) <= 128 + AND author ~ '^(system|operator):[a-z0-9][a-z0-9._-]*$' + ), + CONSTRAINT policy_versions_document_object CHECK ( + jsonb_typeof(document) = 'object' + ), + -- A calibrated version cannot carry an assessment section that its own + -- document marks as uncalibrated. + CONSTRAINT policy_versions_calibrated_kind_matches_document CHECK ( + kind <> 'calibrated' + OR document #>> '{assessment,calibration}' = 'calibrated' + ), + CONSTRAINT policy_versions_document_sha256_size CHECK ( + octet_length(document_sha256) = 32 + ), + -- A version is never backdated: publishing it cannot change which version + -- applied at a moment that already passed. + CONSTRAINT policy_versions_effective_after_creation CHECK ( + effective_at >= created_at + ) +); + +-- Sets created_at from the database clock and defaults effective_at to it. +-- NOT NULL and CHECK constraints run after BEFORE triggers, so they see the +-- stamped values. +-- +goose StatementBegin +CREATE FUNCTION policy_versions_stamp_creation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.created_at := clock_timestamp(); + NEW.effective_at := coalesce(NEW.effective_at, NEW.created_at); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER policy_versions_stamp_creation +BEFORE INSERT ON policy_versions +FOR EACH ROW EXECUTE FUNCTION policy_versions_stamp_creation(); + +-- Refuses every UPDATE, DELETE, and TRUNCATE of policy versions. The error +-- uses SQLSTATE 23000 (integrity_constraint_violation) and the constraint name +-- policy_versions_immutable, which the adapter maps to a port sentinel without +-- reading the message. The message quotes no row values. +-- +goose StatementBegin +CREATE FUNCTION policy_versions_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'policy_versions_immutable', + TABLE = 'policy_versions', + MESSAGE = 'policy versions are immutable: publish a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER policy_versions_refuse_update_delete +BEFORE UPDATE OR DELETE ON policy_versions +FOR EACH ROW EXECUTE FUNCTION policy_versions_refuse_change(); + +-- Row triggers do not fire for TRUNCATE, so a statement trigger covers it. +CREATE TRIGGER policy_versions_refuse_truncate +BEFORE TRUNCATE ON policy_versions +FOR EACH STATEMENT EXECUTE FUNCTION policy_versions_refuse_change(); + +-- +goose Down +DROP TABLE policy_versions; +DROP FUNCTION policy_versions_refuse_change(); +DROP FUNCTION policy_versions_stamp_creation(); diff --git a/backend/db/migrations/00004_add_outbox_relay_index.sql b/backend/db/migrations/00004_add_outbox_relay_index.sql new file mode 100644 index 0000000..6d1e28b --- /dev/null +++ b/backend/db/migrations/00004_add_outbox_relay_index.sql @@ -0,0 +1,13 @@ +-- +goose Up +-- Supports the relay check that an outbox row is the earliest unpublished +-- event of its aggregate. The relay publishes only that row for each +-- aggregate per pass, so the check runs once for every candidate row. Without +-- this index the lookup reads every published event of the aggregate through +-- the unique key. The index covers only unpublished rows and shrinks as +-- events are published. +CREATE INDEX outbox_events_unpublished_aggregate_idx +ON outbox_events (aggregate_type, aggregate_id, aggregate_version, position) +WHERE published_at IS NULL; + +-- +goose Down +DROP INDEX outbox_events_unpublished_aggregate_idx; diff --git a/backend/db/migrations/00005_create_event_consumer_tables.sql b/backend/db/migrations/00005_create_event_consumer_tables.sql new file mode 100644 index 0000000..27587ec --- /dev/null +++ b/backend/db/migrations/00005_create_event_consumer_tables.sql @@ -0,0 +1,95 @@ +-- +goose Up +-- Idempotent event consumers. The event bus delivers at least once, so a +-- consumer records every event it applied in the same transaction as the +-- effect. A repeated or concurrent delivery of the same event to the same +-- consumer finds the marker and skips the effect. +-- There is no index on processed_at yet: every applied event would pay for +-- it, and nothing reads by time until marker retention is implemented. +CREATE TABLE consumer_processed_events ( + -- Stable consumer name from the code; also the consumer group suffix. + consumer_name text NOT NULL, + event_id uuid NOT NULL, + processed_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT consumer_processed_events_pkey PRIMARY KEY ( + consumer_name, event_id + ), + CONSTRAINT consumer_processed_events_consumer_name_format CHECK ( + char_length(consumer_name) <= 64 + AND consumer_name ~ '^[a-z][a-z0-9_]*$' + ) +); + +-- Records a consumer could not apply: a value that is not a valid event +-- envelope, an event the handler rejected, or one whose retries ran out. The +-- consumer commits the offset after writing the row, so one bad record does +-- not stop its partition. The record value is not stored: a valid event is +-- still in outbox_events under its event_id, and an invalid record can be +-- read from Kafka by topic, partition, and offset while the topic retains +-- it. value_sha256 identifies that exact value without keeping a copy of +-- data that may later be personal. +CREATE TABLE consumer_dead_letters ( + id bigint GENERATED ALWAYS AS IDENTITY, + consumer_name text NOT NULL, + topic text NOT NULL, + kafka_partition integer NOT NULL, + kafka_offset bigint NOT NULL, + -- From the envelope, or from the event_id header of an invalid record; + -- NULL when neither holds a UUID. + event_id uuid, + -- NULL when the record is not a valid envelope. + event_type text, + error_class text NOT NULL, + -- Short sanitized cause; never the record value. + reason text NOT NULL, + -- Handler attempts made; 0 for a record that was never handed to it. + attempts integer NOT NULL, + value_size integer NOT NULL, + value_sha256 bytea NOT NULL, + dead_lettered_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT consumer_dead_letters_pkey PRIMARY KEY (id), + -- A record delivered again, after a crash before the offset commit or a + -- rewind of the group, updates its row instead of adding one. The value + -- digest is part of the key: a topic that was deleted and created again + -- reuses offsets, and a different value at a reused position is another + -- record that keeps its own row. + CONSTRAINT consumer_dead_letters_record_key UNIQUE ( + consumer_name, topic, kafka_partition, kafka_offset, value_sha256 + ), + CONSTRAINT consumer_dead_letters_consumer_name_format CHECK ( + char_length(consumer_name) <= 64 + AND consumer_name ~ '^[a-z][a-z0-9_]*$' + ), + CONSTRAINT consumer_dead_letters_topic_length CHECK ( + char_length(topic) BETWEEN 1 AND 249 + ), + CONSTRAINT consumer_dead_letters_position_not_negative CHECK ( + kafka_partition >= 0 AND kafka_offset >= 0 + ), + CONSTRAINT consumer_dead_letters_event_type_length CHECK ( + char_length(event_type) <= 128 + ), + CONSTRAINT consumer_dead_letters_error_class_known CHECK ( + error_class IN ( + 'invalid_record', + 'handler_rejected', + 'handler_panic', + 'retries_exhausted' + ) + ), + CONSTRAINT consumer_dead_letters_reason_length CHECK ( + char_length(reason) BETWEEN 1 AND 512 + ), + CONSTRAINT consumer_dead_letters_attempts_not_negative CHECK ( + attempts >= 0 + ), + CONSTRAINT consumer_dead_letters_value_size_not_negative CHECK ( + value_size >= 0 + ), + CONSTRAINT consumer_dead_letters_value_sha256_size CHECK ( + octet_length(value_sha256) = 32 + ) +); + +-- +goose Down +DROP TABLE consumer_dead_letters; +DROP TABLE consumer_processed_events; diff --git a/backend/db/migrations/00006_create_deliveries.sql b/backend/db/migrations/00006_create_deliveries.sql new file mode 100644 index 0000000..e7d7f7b --- /dev/null +++ b/backend/db/migrations/00006_create_deliveries.sql @@ -0,0 +1,295 @@ +-- +goose Up +-- Mail requests: the caller text of a requested notification, written in the +-- producer's business transaction next to the outbox event that announces +-- it. The event carries only the request ID, so the text never reaches the +-- event bus. The delivery consumer reads the row, stores the rendered +-- Delivery, and deletes the row in the same transaction; a request whose +-- account is deleted first goes with the account. +CREATE TABLE mail_requests ( + -- Generated in Go; the aggregate ID of the event and the ID of the + -- delivery it becomes. + id uuid NOT NULL, + recipient_user_id uuid NOT NULL, + kind text NOT NULL, + subject text NOT NULL, + body text NOT NULL, + link_path text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT mail_requests_pkey PRIMARY KEY (id), + CONSTRAINT mail_requests_recipient_user_id_fkey FOREIGN KEY ( + recipient_user_id + ) REFERENCES users (id) ON DELETE CASCADE, + -- Mail with a one-time token is never requested through an event. + CONSTRAINT mail_requests_kind_known CHECK (kind IN ('notification')), + CONSTRAINT mail_requests_text_length CHECK ( + char_length(subject) <= 1000 + AND char_length(body) <= 16000 + AND octet_length(link_path) <= 256 + ) +); + +-- Serves the cascade from users and the account cleanup. +CREATE INDEX mail_requests_recipient_user_id_idx +ON mail_requests (recipient_user_id); + +-- Mail deliveries: the durable state of sending one message to one +-- recipient. A delivery keeps the rendered content it was created with, the +-- provider account it is pinned to, and the idempotency key sent with every +-- attempt, so a retry repeats exactly the same request even after the +-- templates or the configuration changed. Every timestamp comes from the +-- application clock. +-- +-- The rows hold personal data: the recipient address and the bodies. Bodies +-- of verification and password reset mail hold a one-time bearer token until +-- it expires or is used. Read them only to send the message; never copy them +-- into logs, metrics, tickets, or events. +CREATE TABLE deliveries ( + -- Stable ID of the logical request, generated in Go. A repeated request + -- maps to the same row. + id uuid NOT NULL, + -- The domain event the delivery was created from; NULL for a delivery + -- created directly in a business transaction. + source_event_id uuid, + recipient_user_id uuid NOT NULL, + -- Delivery form of the account address when the delivery was created. + recipient_email text NOT NULL, + kind text NOT NULL, + -- ".v", the immutable template version that rendered the body. + template_version text NOT NULL, + subject text NOT NULL, + text_body text NOT NULL, + html_body text NOT NULL, + -- SHA-256 over the version, subject, and both parts as netstrings; the + -- domain checks it on every read. + content_sha256 bytea NOT NULL, + -- Transport and provider account label from configuration; never a + -- credential. + provider text NOT NULL, + provider_account text NOT NULL, + -- Sent with every attempt; contains no personal data. + idempotency_key text NOT NULL, + status text NOT NULL, + attempt_count integer NOT NULL, + -- When the delivery is due; NULL when no automatic attempt is scheduled. + next_attempt_at timestamptz, + last_attempt_at timestamptz, + -- Set once the provider accepted the message. + provider_message_id text, + -- Optimistic concurrency version, advanced by every attempt. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT deliveries_pkey PRIMARY KEY (id), + CONSTRAINT deliveries_idempotency_key_key UNIQUE (idempotency_key), + -- Deleting an account deletes the copies of its address and the bodies + -- addressed to it. + CONSTRAINT deliveries_recipient_user_id_fkey FOREIGN KEY ( + recipient_user_id + ) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT deliveries_recipient_email_ascii CHECK ( + char_length(recipient_email) BETWEEN 3 AND 254 + AND octet_length(recipient_email) = char_length(recipient_email) + ), + CONSTRAINT deliveries_kind_known CHECK ( + kind IN ('verification', 'password_reset', 'notification') + ), + CONSTRAINT deliveries_template_version_of_kind CHECK ( + template_version ~ '^[a-z][a-z_]*\.v[1-9][0-9]{0,8}$' + AND left(template_version, char_length(kind) + 2) = kind || '.v' + ), + CONSTRAINT deliveries_subject_length CHECK ( + char_length(subject) BETWEEN 1 AND 150 + ), + CONSTRAINT deliveries_body_present CHECK ( + text_body <> '' OR html_body <> '' + ), + CONSTRAINT deliveries_content_sha256_size CHECK ( + octet_length(content_sha256) = 32 + ), + CONSTRAINT deliveries_provider_format CHECK ( + provider ~ '^[a-z][a-z0-9_]{0,31}$' + ), + CONSTRAINT deliveries_provider_account_format CHECK ( + provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$' + ), + -- PostgreSQL regular expressions bound repetition at 255, so the length + -- is checked separately. + CONSTRAINT deliveries_idempotency_key_format CHECK ( + char_length(idempotency_key) <= 256 + AND idempotency_key ~ '^[!-~]+$' + ), + CONSTRAINT deliveries_status_known CHECK ( + status IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota' + ) + ), + -- pending is picked up again by the worker, so it says when; accepted + -- and rejected are terminal; unknown and waiting_quota may wait without + -- a time for a reconciliation, an unknown quota reset, or an operator. + CONSTRAINT deliveries_next_attempt_matches_status CHECK ( + (status = 'pending' AND next_attempt_at IS NOT NULL) + OR (status IN ('accepted', 'rejected') AND next_attempt_at IS NULL) + OR status IN ('unknown', 'waiting_quota') + ), + CONSTRAINT deliveries_provider_message_id_when_accepted CHECK ( + (status = 'accepted') = (provider_message_id IS NOT NULL) + AND ( + provider_message_id IS NULL + OR provider_message_id ~ '^[!-~]{1,128}$' + ) + ), + CONSTRAINT deliveries_attempts_counted CHECK ( + attempt_count >= 0 + AND (attempt_count = 0) = (last_attempt_at IS NULL) + ), + CONSTRAINT deliveries_version_positive CHECK (version > 0), + CONSTRAINT deliveries_timestamps_after_creation CHECK ( + updated_at >= created_at + AND (last_attempt_at IS NULL OR last_attempt_at >= created_at) + ) +); + +-- Serves the cascade from users and the account cleanup, which locks the +-- deliveries of each account it deletes. +CREATE INDEX deliveries_recipient_user_id_idx +ON deliveries (recipient_user_id); + +-- One row per transport attempt, appended in the transaction that advances +-- the delivery. Kept as history next to the counters on deliveries: the +-- worker reads the counters, while operators and the retry and quota rules +-- need every outcome, provider code, and wait hint. +CREATE TABLE delivery_attempts ( + delivery_id uuid NOT NULL, + -- 1 for the first attempt of the delivery. + attempt_number integer NOT NULL, + attempted_at timestamptz NOT NULL, + outcome text NOT NULL, + -- Set only for a rejected attempt. + rejection text, + -- Documented provider error name; never provider free text. + provider_code text, + provider_message_id text, + -- Provider or transport wait hint in nanoseconds, the exact Go + -- time.Duration; 0 when there was none. + retry_after_ns bigint NOT NULL, + status_after text NOT NULL, + next_attempt_at timestamptz, + CONSTRAINT delivery_attempts_pkey PRIMARY KEY ( + delivery_id, attempt_number + ), + CONSTRAINT delivery_attempts_delivery_id_fkey FOREIGN KEY ( + delivery_id + ) REFERENCES deliveries (id) ON DELETE CASCADE, + CONSTRAINT delivery_attempts_number_positive CHECK (attempt_number > 0), + CONSTRAINT delivery_attempts_outcome_known CHECK ( + outcome IN ('accepted', 'rejected', 'unknown') + ), + CONSTRAINT delivery_attempts_rejection_when_rejected CHECK ( + (outcome = 'rejected') = (rejection IS NOT NULL) + AND ( + rejection IS NULL + OR rejection IN ( + 'permanent', + 'invalid_request', + 'rate_limited', + 'quota_exhausted', + 'temporary' + ) + ) + ), + CONSTRAINT delivery_attempts_message_id_when_accepted CHECK ( + (outcome = 'accepted') = (provider_message_id IS NOT NULL) + AND ( + provider_message_id IS NULL + OR provider_message_id ~ '^[!-~]{1,128}$' + ) + ), + CONSTRAINT delivery_attempts_provider_code_format CHECK ( + provider_code ~ '^[a-z][a-z0-9_]{0,63}$' + ), + CONSTRAINT delivery_attempts_retry_after_not_negative CHECK ( + retry_after_ns >= 0 + ), + CONSTRAINT delivery_attempts_status_after_known CHECK ( + status_after IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota' + ) + ), + CONSTRAINT delivery_attempts_next_after_attempt CHECK ( + next_attempt_at IS NULL OR next_attempt_at >= attempted_at + ) +); + +-- Refuses an UPDATE that changes what a delivery sends or where: the +-- recipient, the content, the idempotency key, the source event, and the +-- creation time. The provider account may change only while the delivery +-- has no attempt, because a provider that saw an attempt may hold the key. +-- The attempt state stays updatable. Errors use SQLSTATE 23000 and the +-- constraint names deliveries_content_immutable and +-- deliveries_provider_pinned, which the adapter maps without reading the +-- message; the messages quote no row values. +-- +goose StatementBegin +CREATE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.text_body, NEW.html_body, NEW.content_sha256, + NEW.idempotency_key, NEW.created_at + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.text_body, OLD.html_body, OLD.content_sha256, + OLD.idempotency_key, OLD.created_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER deliveries_refuse_content_change +BEFORE UPDATE ON deliveries +FOR EACH ROW EXECUTE FUNCTION deliveries_refuse_content_change(); + +-- Attempts are history: an UPDATE is refused. Deletes stay possible for the +-- cascade from an account and for a later retention rule. +-- +goose StatementBegin +CREATE FUNCTION delivery_attempts_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'delivery_attempts_immutable', + TABLE = 'delivery_attempts', + MESSAGE = 'delivery attempts are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER delivery_attempts_refuse_update +BEFORE UPDATE ON delivery_attempts +FOR EACH ROW EXECUTE FUNCTION delivery_attempts_refuse_update(); + +-- +goose Down +DROP TABLE delivery_attempts; +DROP TABLE deliveries; +DROP TABLE mail_requests; +DROP FUNCTION delivery_attempts_refuse_update(); +DROP FUNCTION deliveries_refuse_content_change(); diff --git a/backend/db/migrations/00007_create_mail_quota_usage.sql b/backend/db/migrations/00007_create_mail_quota_usage.sql new file mode 100644 index 0000000..2c573f2 --- /dev/null +++ b/backend/db/migrations/00007_create_mail_quota_usage.sql @@ -0,0 +1,110 @@ +-- +goose Up +-- Mail quota usage: the recipients counted against a provider account per +-- UTC day and per UTC calendar month. The sending path reserves recipients +-- here before it calls the transport, in one transaction that locks the +-- window rows, so concurrent senders never exceed a configured limit +-- together. The limits themselves come from configuration +-- (EMAIL_QUOTA_DAILY, EMAIL_QUOTA_MONTHLY) and are not stored: lowering one +-- takes effect on the next reservation. +-- +-- The table has no foreign key to users or deliveries on purpose. Deleting +-- an account deletes its deliveries and attempts, but the provider still +-- counted the messages already sent, so the usage must stay. The rows hold +-- no personal data: provider and account are configuration labels. +CREATE TABLE mail_quota_usage ( + provider text NOT NULL, + provider_account text NOT NULL, + period_kind text NOT NULL, + -- The UTC date that starts the window: the day itself, or the first day + -- of the month. + period_start date NOT NULL, + used_recipients bigint NOT NULL, + -- Last time the provider itself refused a send for an exhausted quota in + -- this window; NULL when it never did. used_recipients was then raised + -- to the limit, and releases no longer lower it. + provider_exhausted_at timestamptz, + -- Application clock time of the last change. + updated_at timestamptz NOT NULL, + CONSTRAINT mail_quota_usage_pkey PRIMARY KEY ( + provider, provider_account, period_kind, period_start + ), + -- The same label rules as deliveries.provider and + -- deliveries.provider_account. + CONSTRAINT mail_quota_usage_provider_format CHECK ( + provider ~ '^[a-z][a-z0-9_]{0,31}$' + ), + CONSTRAINT mail_quota_usage_provider_account_format CHECK ( + provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$' + ), + CONSTRAINT mail_quota_usage_period_kind_known CHECK ( + period_kind IN ('day', 'month') + ), + CONSTRAINT mail_quota_usage_month_starts_on_day_one CHECK ( + period_kind <> 'month' OR extract(DAY FROM period_start) = 1 + ), + CONSTRAINT mail_quota_usage_used_not_negative CHECK (used_recipients >= 0) +); + +-- Mail quota reservations: one row per admitted send, written in the +-- transaction that adds it to mail_quota_usage. The journal makes a release +-- happen at most once per reservation, whatever the caller retries, and lets +-- a retry of the same delivery inside the provider's idempotency window +-- reuse its open reservation instead of counting the message again. +-- +-- Like the usage, it has no foreign key: a reservation outlives its delivery, +-- and delivery_id is an opaque ID without personal data. Every write that +-- also changes mail_quota_usage locks the usage rows first, in +-- (period_kind, period_start) order, and the journal row second. +CREATE TABLE mail_quota_reservations ( + -- Generated in Go. + id uuid NOT NULL, + delivery_id uuid NOT NULL, + provider text NOT NULL, + provider_account text NOT NULL, + -- The windows the recipients were counted in. + day_start date NOT NULL, + month_start date NOT NULL, + recipients bigint NOT NULL, + reserved_at timestamptz NOT NULL, + -- Set once, when the recipients were given back. + released_at timestamptz, + -- The last settled outcome of a send under this reservation; NULL while + -- the send is in flight or its process stopped before settling. + settled_outcome text, + settled_at timestamptz, + CONSTRAINT mail_quota_reservations_pkey PRIMARY KEY (id), + CONSTRAINT mail_quota_reservations_provider_format CHECK ( + provider ~ '^[a-z][a-z0-9_]{0,31}$' + ), + CONSTRAINT mail_quota_reservations_provider_account_format CHECK ( + provider_account ~ '^[a-z0-9][a-z0-9._-]{0,63}$' + ), + CONSTRAINT mail_quota_reservations_windows_match CHECK ( + extract(DAY FROM month_start) = 1 + AND day_start >= month_start + AND day_start < month_start + INTERVAL '1 month' + ), + CONSTRAINT mail_quota_reservations_recipients_positive CHECK ( + recipients > 0 + ), + CONSTRAINT mail_quota_reservations_outcome_known CHECK ( + (settled_outcome IS NULL) = (settled_at IS NULL) + AND ( + settled_outcome IS NULL + OR settled_outcome IN ('accepted', 'unknown', 'rejected', 'not_sent') + ) + ), + CONSTRAINT mail_quota_reservations_times_ordered CHECK ( + (released_at IS NULL OR released_at >= reserved_at) + AND (settled_at IS NULL OR settled_at >= reserved_at) + ) +); + +-- Serves the lookup of an open reservation of a delivery. +CREATE INDEX mail_quota_reservations_open_delivery_idx +ON mail_quota_reservations (delivery_id, reserved_at) +WHERE released_at IS NULL; + +-- +goose Down +DROP TABLE mail_quota_reservations; +DROP TABLE mail_quota_usage; diff --git a/backend/db/migrations/00008_create_scheduled_jobs.sql b/backend/db/migrations/00008_create_scheduled_jobs.sql new file mode 100644 index 0000000..339445d --- /dev/null +++ b/backend/db/migrations/00008_create_scheduled_jobs.sql @@ -0,0 +1,127 @@ +-- +goose Up +-- Durable jobs that run when they fall due, such as a response deadline. A +-- usecase schedules a job in its own business transaction, so the job exists +-- exactly when the business change committed. The scheduled job worker +-- claims due jobs under a lease and runs each handler in one transaction +-- with the completion of its job, so a database-only effect happens once. +-- +-- Every due and lease time comes from the application clock, never from the +-- database clock, so tests can move time without waiting. created_at and +-- updated_at are informational database times for operators. +-- +-- The payload holds identifiers only. Rows are kept after they finish: the +-- (kind, dedup_key) pair stays reserved, so a repeated schedule of a job +-- that already ran or was canceled does nothing. Retention of finished rows +-- is not implemented yet. +CREATE TABLE scheduled_jobs ( + id bigint GENERATED ALWAYS AS IDENTITY, + -- Handler name from the code, for example "invitation.response_deadline". + kind text NOT NULL, + -- Caller key of the logical job within its kind, for example an + -- aggregate ID. It must not contain personal data. + dedup_key text NOT NULL, + -- Small JSON object of identifiers for the handler. + payload jsonb NOT NULL, + -- When the job falls due: the deadline it stands for. It never changes, + -- so a handler that runs late or on a retry still sees the deadline. + due_at timestamptz NOT NULL, + -- When a worker may claim the job next: due_at at first, then the + -- retry time after a failed attempt. + available_at timestamptz NOT NULL, + -- pending: waits for available_at and no attempt failed yet; + -- failed: an attempt failed and the job waits for its retry at + -- available_at; + -- running: claimed under a lease; done, dead, cancelled: final. + status text NOT NULL, + -- Attempts counted so far, including a running one. A claim counts its + -- attempt before the handler runs, so a job that crashes the process + -- cannot loop forever; a claim whose attempt never started is reused + -- by the next claim instead of counted twice. + attempts integer NOT NULL, + -- NULL means the worker default, JOBS_MAX_ATTEMPTS. + max_attempts integer, + -- Random ID of the worker instance that holds the lease. + lease_owner uuid, + lease_expires_at timestamptz, + -- When the worker started the handler of the running attempt and + -- renewed its lease, by the application clock. NULL while the job is + -- claimed but not started, and whenever it is not running. + started_at timestamptz, + -- Bounded cause of the last failed or abandoned attempt; never text + -- from the handler. + last_error_class text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT scheduled_jobs_pkey PRIMARY KEY (id), + CONSTRAINT scheduled_jobs_kind_dedup_key_key UNIQUE (kind, dedup_key), + CONSTRAINT scheduled_jobs_kind_format CHECK ( + char_length(kind) <= 64 + AND kind ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$' + ), + CONSTRAINT scheduled_jobs_dedup_key_format CHECK ( + char_length(dedup_key) <= 128 + AND dedup_key ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + ), + -- The application allows 2 KiB of compact JSON; the jsonb text form + -- adds spaces, so this backstop is wider. + CONSTRAINT scheduled_jobs_payload_object CHECK ( + jsonb_typeof(payload) = 'object' + AND octet_length(payload::text) <= 4096 + ), + CONSTRAINT scheduled_jobs_status_known CHECK ( + status IN ('pending', 'failed', 'running', 'done', 'dead', 'cancelled') + ), + CONSTRAINT scheduled_jobs_attempts_bounded CHECK ( + attempts >= 0 + AND (max_attempts IS NULL OR max_attempts BETWEEN 1 AND 100) + ), + -- Only a running job holds a lease, and a running job always does. + CONSTRAINT scheduled_jobs_lease_when_running CHECK ( + (status = 'running') + = (lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL) + AND (lease_owner IS NULL) = (lease_expires_at IS NULL) + ), + CONSTRAINT scheduled_jobs_running_counted CHECK ( + status <> 'running' OR attempts > 0 + ), + CONSTRAINT scheduled_jobs_started_when_running CHECK ( + status = 'running' OR started_at IS NULL + ), + -- failed differs from pending only by the recorded cause, so an + -- operator can tell a first wait from a retry. + CONSTRAINT scheduled_jobs_failed_has_cause CHECK ( + (status <> 'pending' OR last_error_class IS NULL) + AND (status <> 'failed' OR last_error_class IS NOT NULL) + ), + CONSTRAINT scheduled_jobs_error_class_known CHECK ( + last_error_class IN ( + 'handler_failed', + 'handler_rejected', + 'handler_panic', + 'timeout', + 'conflict', + 'effect_rejected', + 'lease_expired', + 'completion_conflict' + ) + ) +); + +-- Serves the claim of due jobs. It covers only waiting rows, so it stays +-- small while finished rows accumulate. +CREATE INDEX scheduled_jobs_available_idx +ON scheduled_jobs (available_at, id) +WHERE status IN ('pending', 'failed'); + +-- Serves the claim of running jobs whose lease expired. +CREATE INDEX scheduled_jobs_lease_idx +ON scheduled_jobs (lease_expires_at) +WHERE status = 'running'; + +-- Serves the dead job gauge and operator queries; dead jobs are rare. +CREATE INDEX scheduled_jobs_dead_idx +ON scheduled_jobs (kind, updated_at) +WHERE status = 'dead'; + +-- +goose Down +DROP TABLE scheduled_jobs; diff --git a/backend/db/migrations/00009_create_consent_ledger.sql b/backend/db/migrations/00009_create_consent_ledger.sql new file mode 100644 index 0000000..767071d --- /dev/null +++ b/backend/db/migrations/00009_create_consent_ledger.sql @@ -0,0 +1,413 @@ +-- +goose Up +-- Versioned consent ledger for the independent consents C1-C5 (PRD FR01, +-- FR12, and 7.3): the published consent texts and an append-only record of +-- every grant and revocation. Purposes are independent: a grant or a +-- revocation of one purpose never changes another. +-- +-- consent_texts holds the published text of each purpose and version. A +-- grant references the text it was given for, so a client cannot invent a +-- version and the stored hash always belongs to a published text. +CREATE TABLE consent_texts ( + -- c1 personal data processing, c2 publication of the candidate card, c3 + -- automatic categorization, c4 transfer of selected contact data to one + -- organization, c5 import of FSP results. + purpose text NOT NULL, + -- Identifier that clients see as ConsentTextVersion, such as + -- "c1-2026-10-01". + version text NOT NULL, + -- Exact text in plain UTF-8. The C4 text contains the placeholder + -- {organization}, which the shown text replaces with the name of the + -- organization. + body text NOT NULL, + -- SHA-256 of the UTF-8 bytes of body, 32 raw bytes. + body_sha256 bytea NOT NULL, + -- "demo" marks a synthetic text for the demonstration on synthetic data + -- without a legal review; "operator" a text published by the actual + -- personal data operator, required before real data are accepted. + kind text NOT NULL, + -- The text applies to grants given at or after this time. The current + -- text of a purpose is the one with the latest published_at that is not + -- after the grant time. + published_at timestamptz NOT NULL, + CONSTRAINT consent_texts_pkey PRIMARY KEY (purpose, version), + -- Target of the hash binding of consent_records. + CONSTRAINT consent_texts_purpose_version_body_sha256_key UNIQUE ( + purpose, version, body_sha256 + ), + CONSTRAINT consent_texts_purpose_published_at_key UNIQUE ( + purpose, published_at + ), + CONSTRAINT consent_texts_purpose_known CHECK ( + purpose IN ('c1', 'c2', 'c3', 'c4', 'c5') + ), + CONSTRAINT consent_texts_version_format CHECK ( + version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + CONSTRAINT consent_texts_body_length CHECK ( + char_length(body) BETWEEN 1 AND 100000 + ), + -- The database encoding is fixed for the life of a database, so + -- convert_to gives the same bytes on every evaluation. + CONSTRAINT consent_texts_body_sha256_matches CHECK ( + body_sha256 = sha256(convert_to(body, 'UTF8')) + ), + -- Only the C4 text names an organization. + CONSTRAINT consent_texts_organization_placeholder CHECK ( + (purpose = 'c4') = (strpos(body, '{organization}') > 0) + ), + CONSTRAINT consent_texts_kind_known CHECK (kind IN ('demo', 'operator')) +); + +-- Refuses every UPDATE, DELETE, and TRUNCATE of consent texts: a grant +-- proves which text the subject saw only while that text stays unchanged. +-- A changed text is a new version. The error uses SQLSTATE 23000 and the +-- constraint name consent_texts_immutable, which the adapter maps without +-- reading the message. +-- +goose StatementBegin +CREATE FUNCTION consent_texts_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_texts_immutable', + TABLE = 'consent_texts', + MESSAGE = 'consent texts are immutable: publish a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_texts_refuse_update_delete +BEFORE UPDATE OR DELETE ON consent_texts +FOR EACH ROW EXECUTE FUNCTION consent_texts_refuse_change(); + +CREATE TRIGGER consent_texts_refuse_truncate +BEFORE TRUNCATE ON consent_texts +FOR EACH STATEMENT EXECUTE FUNCTION consent_texts_refuse_change(); + +-- Demonstration texts, version 1 of every purpose. They are synthetic and +-- carry no legal review; the operator publishes its own texts as new +-- versions in a later migration before real data are accepted (PRD 7.3). +INSERT INTO consent_texts ( + purpose, version, body, body_sha256, kind, published_at +) +SELECT + seed.purpose, + seed.version, + seed.body, + sha256(convert_to(seed.body, 'UTF8')), + 'demo', + '2026-10-01T00:00:00Z'::timestamptz +FROM ( + VALUES + ( + 'c1', + 'c1-2026-10-01', + 'I consent to the processing of my personal data for registration ' + || 'and the use of the service.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c2', + 'c2-2026-10-01', + 'I consent to the publication of my candidate card with the fields ' + || 'I select in the publication settings.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c3', + 'c3-2026-10-01', + 'I consent to the automatic categorization of my assessment ' + || 'results. Without this consent I can request a manual assessment ' + || 'by the same rubric.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c4', + 'c4-2026-10-01', + 'I consent to the transfer of the contact data I select to ' + || '{organization} for this invitation.' || E'\n\n' + || 'The full text is published by the operator.' + ), + ( + 'c5', + 'c5-2026-10-01', + 'I consent to the import of my FSP results into my profile.' + || E'\n\n' + || 'The full text is published by the operator.' + ) +) AS seed (purpose, version, body); + +-- Reports whether a C4 field set is canonical: one to four distinct known +-- contact kinds (ContactFieldKind) in ascending byte order without NULLs. +-- A canonical form makes equal sets equal arrays. +-- +goose StatementBegin +CREATE FUNCTION consent_field_set_is_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + array_ndims(fields) = 1 + AND cardinality(fields) BETWEEN 1 AND 4 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- One row per grant. A grant is never updated except for the one-time +-- revocation stamp: a new text version or a grant after a revocation is a +-- new row, so the history of a purpose is the sequence of its rows. Every +-- time comes from the application clock. +-- +-- The rows are personal data of the subject: never copy them into logs, +-- metrics, or events beyond the record ID and purpose. +CREATE TABLE consent_records ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- The account that gave the consent. + subject_id uuid NOT NULL, + purpose text NOT NULL, + text_version text NOT NULL, + -- SHA-256 of exactly the text the subject saw, 32 raw bytes. For C1-C3 + -- and C5 it equals the hash of the published text; for C4 it is the + -- hash of the published text with organization_name filled in, which a + -- trigger checks. + text_hash bytea NOT NULL, + -- The hash that must equal the published text: text_hash except for + -- C4, NULL for C4, so the composite foreign key below skips C4. + published_text_hash bytea GENERATED ALWAYS AS ( + CASE WHEN purpose <> 'c4' THEN text_hash END + ) STORED, + -- Where the grant was given: registration (C1 only), consent_settings + -- (C1-C3 and C5), or invitation_acceptance (C4 only). + source text NOT NULL, + -- C4 scope: the organization, the name of the organization as the + -- shown text named it (a snapshot that a later rename never changes), + -- the canonical set of contact kinds, and the invitation and its terms + -- version that the acceptance accepted. NULL for every other purpose. + -- The organization and invitation tables do not exist yet; their + -- foreign keys arrive with them. + organization_id uuid, + organization_name text, + field_set text [], + invitation_id uuid, + invitation_terms_version bigint, + granted_at timestamptz NOT NULL, + -- Set once; the row is never updated again. + revoked_at timestamptz, + -- consent_settings: the subject revoked it in the product; + -- support_request: an operator recorded a revocation the subject asked + -- for through support. + revocation_source text, + CONSTRAINT consent_records_pkey PRIMARY KEY (id), + -- Consent evidence must outlive a careless account delete: an account + -- with consent history cannot be deleted until the deleting procedure + -- handles the ledger explicitly (PRD 7.3 keeps consents for three + -- years). The unverified account cleanup deletes the records of the + -- accounts it removes in the same statement, and the re-registration of + -- an unverified account deletes its registration C1. + CONSTRAINT consent_records_subject_id_fkey FOREIGN KEY (subject_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT consent_records_text_fkey FOREIGN KEY ( + purpose, text_version + ) REFERENCES consent_texts (purpose, version), + -- MATCH SIMPLE skips the check when published_text_hash is NULL (C4). + CONSTRAINT consent_records_published_text_fkey FOREIGN KEY ( + purpose, text_version, published_text_hash + ) REFERENCES consent_texts (purpose, version, body_sha256), + CONSTRAINT consent_records_purpose_known CHECK ( + purpose IN ('c1', 'c2', 'c3', 'c4', 'c5') + ), + CONSTRAINT consent_records_text_version_format CHECK ( + text_version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + CONSTRAINT consent_records_text_hash_sha256 CHECK ( + octet_length(text_hash) = 32 + ), + CONSTRAINT consent_records_source_of_purpose CHECK ( + (purpose = 'c1' AND source IN ('registration', 'consent_settings')) + OR (purpose IN ('c2', 'c3', 'c5') AND source = 'consent_settings') + OR (purpose = 'c4' AND source = 'invitation_acceptance') + ), + -- C4 always has its scope; no other purpose has one. + CONSTRAINT consent_records_c4_scope CHECK ( + ( + purpose = 'c4' + AND organization_id IS NOT NULL + AND organization_name IS NOT NULL + AND char_length(organization_name) BETWEEN 1 AND 200 + AND organization_name !~ '[[:cntrl:]]' + AND field_set IS NOT NULL + AND consent_field_set_is_canonical(field_set) + AND invitation_id IS NOT NULL + AND invitation_terms_version IS NOT NULL + AND invitation_terms_version > 0 + ) + OR ( + purpose <> 'c4' + AND organization_id IS NULL + AND organization_name IS NULL + AND field_set IS NULL + AND invitation_id IS NULL + AND invitation_terms_version IS NULL + ) + ), + CONSTRAINT consent_records_revocation_stamp CHECK ( + (revoked_at IS NULL) = (revocation_source IS NULL) + AND ( + revocation_source IS NULL + OR revocation_source IN ('consent_settings', 'support_request') + ) + AND (revoked_at IS NULL OR revoked_at >= granted_at) + ) +); + +-- Serves the subject's history, newest first, and the foreign key from +-- users. +CREATE INDEX consent_records_subject_granted_idx +ON consent_records (subject_id, granted_at DESC, id DESC); + +-- One unrevoked grant per subject, purpose, and text version: repeating a +-- grant of the same version returns the existing record. A newer version is +-- a new row next to the older one. +CREATE UNIQUE INDEX consent_records_active_version_key +ON consent_records (subject_id, purpose, text_version) +WHERE revoked_at IS NULL AND purpose <> 'c4'; + +-- One C4 grant per invitation, revoked or not: a repeated acceptance +-- returns the existing record, and a revoked C4 never comes back. +CREATE UNIQUE INDEX consent_records_invitation_key +ON consent_records (invitation_id) +WHERE invitation_id IS NOT NULL; + +-- Serves the current C4 grants of a subject for one organization and their +-- revocation. +CREATE INDEX consent_records_active_organization_idx +ON consent_records (subject_id, organization_id) +WHERE purpose = 'c4' AND revoked_at IS NULL; + +-- Refuses a grant for a text version that is not published at the grant +-- time (SQLSTATE 23514, constraint consent_records_text_published) and a C4 +-- grant whose hash is not the hash of the published text with its +-- organization_name filled in (23514, consent_records_c4_text_hash). A +-- version that does not exist at all is left to the foreign key, and a C4 +-- row without a name to consent_records_c4_scope. +-- +goose StatementBegin +CREATE FUNCTION consent_records_require_published_text() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM consent_texts AS text + WHERE + text.purpose = NEW.purpose + AND text.version = NEW.text_version + AND text.published_at > NEW.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'consent_records_text_published', + TABLE = 'consent_records', + MESSAGE = 'the consent text is not published at the grant time'; + END IF; + IF NEW.purpose = 'c4' AND NEW.organization_name IS NOT NULL AND EXISTS ( + SELECT 1 FROM consent_texts AS text + WHERE + text.purpose = NEW.purpose + AND text.version = NEW.text_version + AND sha256(convert_to( + replace(text.body, '{organization}', NEW.organization_name), + 'UTF8' + )) IS DISTINCT FROM NEW.text_hash + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'consent_records_c4_text_hash', + TABLE = 'consent_records', + MESSAGE = 'the C4 hash does not match the published text for the organization name'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_require_published_text +BEFORE INSERT ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_require_published_text(); + +-- Allows exactly one UPDATE of a record: setting revoked_at and +-- revocation_source on an unrevoked record, with every other column +-- unchanged. Every other UPDATE is refused with SQLSTATE 23000 and the +-- constraint name consent_records_immutable; the message quotes no row +-- values. Deletes are guarded separately below. +-- +goose StatementBegin +CREATE FUNCTION consent_records_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.revoked_at IS NOT NULL + OR NEW.revoked_at IS NULL + OR ( + NEW.id, NEW.subject_id, NEW.purpose, NEW.text_version, + NEW.text_hash, NEW.source, NEW.organization_id, + NEW.organization_name, NEW.field_set, + NEW.invitation_id, NEW.invitation_terms_version, NEW.granted_at + ) IS DISTINCT FROM ( + OLD.id, OLD.subject_id, OLD.purpose, OLD.text_version, + OLD.text_hash, OLD.source, OLD.organization_id, + OLD.organization_name, OLD.field_set, + OLD.invitation_id, OLD.invitation_terms_version, OLD.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_records_immutable', + TABLE = 'consent_records', + MESSAGE = 'consent records are append-only: only an unrevoked record can be revoked, once'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_refuse_change +BEFORE UPDATE ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_change(); + +-- Allows deleting a record only while its subject is not a confirmed +-- account: the unverified account cleanup and the re-registration of an +-- unverified account. The ledger of a confirmed account is consent +-- evidence and stays (SQLSTATE 23000, constraint consent_records_retained). +-- The retention rule for consents (PRD 7.3, three years) and the account +-- deletion procedure will extend this condition in their own migration. +-- TRUNCATE fires no row trigger and stays allowed for test isolation. +-- +goose StatementBegin +CREATE FUNCTION consent_records_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM users + WHERE users.id = OLD.subject_id AND users.email_verified_at IS NOT NULL + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_records_retained', + TABLE = 'consent_records', + MESSAGE = 'consent records of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_refuse_delete +BEFORE DELETE ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_delete(); + +-- +goose Down +DROP TABLE consent_records; +DROP TABLE consent_texts; +DROP FUNCTION consent_records_refuse_delete(); +DROP FUNCTION consent_records_refuse_change(); +DROP FUNCTION consent_records_require_published_text(); +DROP FUNCTION consent_field_set_is_canonical(text []); +DROP FUNCTION consent_texts_refuse_change(); diff --git a/backend/db/migrations/00010_create_organizations.sql b/backend/db/migrations/00010_create_organizations.sql new file mode 100644 index 0000000..921c1a9 --- /dev/null +++ b/backend/db/migrations/00010_create_organizations.sql @@ -0,0 +1,227 @@ +-- +goose Up +-- Organizations, their public representatives, and the memberships that give +-- an account a role in an organization (PRD 2.2, FR07, and 6.4). Enum-like +-- columns are text with CHECK constraints, as in the identity tables. +-- +-- The organization row holds the profile that the owner edits and the +-- verification level that only the server sets. The columns of the two are +-- separate on purpose: the profile update statement never names the +-- verification columns, so editing a profile cannot move the level. Every +-- time comes from the application clock. +-- +-- The rows hold personal data of employees (representative names, the +-- membership of an account), so the application never copies them into +-- logs, metrics, or events beyond identifiers. +CREATE TABLE organizations ( + -- UUIDv7 generated in Go. It is the org_id of every organization path. + id uuid NOT NULL, + -- The name consent records snapshot, so the bound equals the bound of + -- consent_records.organization_name. + name text NOT NULL, + description text, + -- Field of business as free text; the product has no sphere taxonomy. + sphere text, + -- Public company contacts only, never personal ones. Each is NULL or a + -- value in the format of the contract; the domain checks them in full. + contact_website text, + contact_email text, + contact_phone text, + contact_telegram text, + -- Trust level (PRD FR07). It starts at e0 and moves only by a + -- verification process of the server, which will record the change in + -- its own history table. No profile statement writes these columns. + verification_level text NOT NULL, + verification_basis text NOT NULL, + verification_changed_at timestamptz NOT NULL, + -- Optimistic concurrency version of the profile, advanced by every + -- profile update. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT organizations_pkey PRIMARY KEY (id), + CONSTRAINT organizations_name_format CHECK ( + char_length(name) BETWEEN 1 AND 200 + AND name !~ '^\s|\s$' + AND name !~ '[[:cntrl:]]' + ), + -- Line breaks are allowed inside the text; every other control + -- character, and whitespace at the ends, are not. + CONSTRAINT organizations_description_format CHECK ( + description IS NULL OR ( + char_length(description) BETWEEN 1 AND 2000 + AND description !~ '^\s|\s$' + AND translate(description, E'\n', '') !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT organizations_sphere_format CHECK ( + sphere IS NULL OR ( + char_length(sphere) BETWEEN 1 AND 100 + AND sphere !~ '^\s|\s$' + AND sphere !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT organizations_contact_website_format CHECK ( + contact_website IS NULL OR ( + char_length(contact_website) BETWEEN 9 AND 300 + AND contact_website ~ '^https://[^\s/?#@]+([/?#]\S*)?$' + ) + ), + CONSTRAINT organizations_contact_email_format CHECK ( + contact_email IS NULL OR ( + char_length(contact_email) BETWEEN 3 AND 254 + AND contact_email ~ '^[^@\s]+@[^@\s]+$' + ) + ), + CONSTRAINT organizations_contact_phone_format CHECK ( + contact_phone IS NULL OR contact_phone ~ '^\+[1-9][0-9]{6,14}$' + ), + CONSTRAINT organizations_contact_telegram_format CHECK ( + contact_telegram IS NULL OR contact_telegram ~ '^@[A-Za-z0-9_]{5,32}$' + ), + -- Each level has its own bases (PRD FR07), so a level never carries the + -- ground of another one. + CONSTRAINT organizations_verification_known CHECK ( + (verification_level = 'e0' AND verification_basis = 'confirmed_email') + OR ( + verification_level = 'e1' + AND verification_basis = 'corporate_domain' + ) + OR ( + verification_level = 'e2' + AND verification_basis = 'requisites_and_authority' + ) + OR ( + verification_level = 'e3' + AND verification_basis IN ('manual_review', 'partner_status') + ) + ), + CONSTRAINT organizations_version_positive CHECK (version > 0), + CONSTRAINT organizations_timestamps_after_creation CHECK ( + updated_at >= created_at + AND verification_changed_at >= created_at + ) +); + +-- The representatives that the owner presents on the card. They are +-- presentation only: no account link, no right. The list is replaced as a +-- whole with the organization update, in the order of ordinal. +CREATE TABLE organization_representatives ( + organization_id uuid NOT NULL, + -- Position in the list, from 0; at most ten representatives. + ordinal smallint NOT NULL, + name text NOT NULL, + job_title text NOT NULL, + CONSTRAINT organization_representatives_pkey PRIMARY KEY ( + organization_id, ordinal + ), + -- The list is part of the organization row and goes with it. + CONSTRAINT organization_representatives_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE CASCADE, + CONSTRAINT organization_representatives_ordinal_range CHECK ( + ordinal BETWEEN 0 AND 9 + ), + CONSTRAINT organization_representatives_name_format CHECK ( + char_length(name) BETWEEN 1 AND 100 + AND name !~ '^\s|\s$' + AND name !~ '[[:cntrl:]]' + ), + CONSTRAINT organization_representatives_job_title_format CHECK ( + char_length(job_title) BETWEEN 1 AND 100 + AND job_title !~ '^\s|\s$' + AND job_title !~ '[[:cntrl:]]' + ) +); + +-- One row per account and organization, whatever its role and state: a +-- former member who returns gets the same row back in the active state, and +-- the history of the pair belongs to the audit events. The role lives only +-- here, never on the organization. Only an active membership gives access; +-- the full role matrix (PRD FR07) is applied by the application, and a row +-- grants nothing by itself. +CREATE TABLE memberships ( + -- UUIDv7 generated in Go; the planned assignments of needs refer to it. + id uuid NOT NULL, + organization_id uuid NOT NULL, + user_id uuid NOT NULL, + -- owner, recruiter, hiring_manager, or technical_expert. + role text NOT NULL, + -- active, suspended, removed (by the owner or the platform), or left (by + -- the member). + state text NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT memberships_pkey PRIMARY KEY (id), + -- A repeated membership of the same pair fails here. The leading + -- user_id also serves the list of an account's organizations. + CONSTRAINT memberships_user_id_organization_id_key UNIQUE ( + user_id, organization_id + ), + -- Target of the composite foreign keys that later tables use to bind a + -- membership to its organization, such as the assignments of needs. + CONSTRAINT memberships_organization_id_id_key UNIQUE ( + organization_id, id + ), + -- Both references restrict: an organization with members and an account + -- with memberships cannot be deleted until an explicit procedure ends + -- the memberships first. The application never deletes an organization. + CONSTRAINT memberships_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT memberships_user_id_fkey FOREIGN KEY ( + user_id + ) REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT memberships_role_known CHECK ( + role IN ('owner', 'recruiter', 'hiring_manager', 'technical_expert') + ), + CONSTRAINT memberships_state_known CHECK ( + state IN ('active', 'suspended', 'removed', 'left') + ), + CONSTRAINT memberships_updated_after_creation CHECK ( + updated_at >= created_at + ) +); + +-- Serves the members of an organization and the foreign key. +CREATE INDEX memberships_organization_id_idx +ON memberships (organization_id); + +-- Refuses an organization that has no active owner when the transaction that +-- inserted it commits (SQLSTATE 23514, constraint +-- organizations_owner_required). The check is deferred, so the organization +-- and its owner membership are inserted in either order inside one +-- transaction, and a transaction that fails between the two statements +-- leaves neither. Removing or demoting the last owner later is a rule of +-- the member management, not of this constraint. +-- +goose StatementBegin +CREATE FUNCTION organizations_require_owner() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM memberships + WHERE + memberships.organization_id = NEW.id + AND memberships.role = 'owner' + AND memberships.state = 'active' + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'organizations_owner_required', + TABLE = 'organizations', + MESSAGE = 'an organization needs an active owner'; + END IF; + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER organizations_owner_required +AFTER INSERT ON organizations +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION organizations_require_owner(); + +-- +goose Down +DROP TABLE memberships; +DROP TABLE organization_representatives; +DROP TABLE organizations; +DROP FUNCTION organizations_require_owner(); diff --git a/backend/db/migrations/00011_create_assessment_bank.sql b/backend/db/migrations/00011_create_assessment_bank.sql new file mode 100644 index 0000000..93225b1 --- /dev/null +++ b/backend/db/migrations/00011_create_assessment_bank.sql @@ -0,0 +1,379 @@ +-- +goose Up +-- Assessment bank: immutable versions of assessment task families and the +-- openings that make a category available. +-- +-- One row of assessment_families is one version of one family. Its content +-- (key, rubric, seed generator, authorship, review) never changes: a change +-- is a new row with the next version number. The only columns that move are +-- lifecycle, published_at, published_by, retired_at, and retired_by, and only +-- forward (draft -> published -> retired), which the guard trigger enforces. +-- At most one version of a family is published at a time. +-- +-- The tables hold task content and operator identities only, never personal +-- data of candidates. +CREATE TABLE assessment_families ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + -- Stable name of the family across versions. + family_key text NOT NULL, + -- Numbered from 1 within the family key. + version integer NOT NULL, + category text NOT NULL, + -- Specialization or domain inside the category. + specialization text NOT NULL, + title text NOT NULL, + -- Name of the bundle the version was imported from. Provenance only; it + -- is not part of the content hash. + bundle_name text NOT NULL, + -- "ai:" for a generated draft or "operator:" for a person. + author text NOT NULL, + -- The independent reviewer, "operator:"; NULL while the review + -- is pending. + reviewer text, + review_status text NOT NULL, + -- Seed generator: algorithm, parameter ranges, statement template. + seed_generator jsonb NOT NULL, + -- Answer key: answer format and the reference solution description. + answer_key jsonb NOT NULL, + -- Rubric: principle and criteria. It holds no points or thresholds; + -- grading rules come from the versioned policy. + rubric jsonb NOT NULL, + -- SHA-256 of the canonical content, 32 raw bytes. The domain recomputes + -- it when it reads a row, with the hash function that hash_scheme names. + content_sha256 bytea NOT NULL, + -- Version of the layout that content_sha256 hashes. A row keeps the + -- scheme it was stored with, so a later scheme verifies new rows without + -- invalidating old ones. Part of the immutable columns. + hash_scheme smallint NOT NULL, + lifecycle text NOT NULL, + -- Time from the database clock, set by the stamp trigger. + created_at timestamptz NOT NULL, + published_at timestamptz, + -- "operator:" that the caller declared when it published or + -- retired the version; not an authenticated identity until operator + -- accounts exist. + published_by text, + retired_at timestamptz, + retired_by text, + CONSTRAINT assessment_families_pkey PRIMARY KEY (id), + CONSTRAINT assessment_families_family_key_version_key UNIQUE ( + family_key, version + ), + CONSTRAINT assessment_families_family_key_format CHECK ( + family_key ~ '^[a-z][a-z0-9-]{2,63}$' + ), + CONSTRAINT assessment_families_version_positive CHECK (version > 0), + CONSTRAINT assessment_families_category_format CHECK ( + category ~ '^[a-z][a-z0-9-]{1,47}$' + ), + CONSTRAINT assessment_families_specialization_format CHECK ( + specialization ~ '^[a-z][a-z0-9-]{1,63}$' + ), + CONSTRAINT assessment_families_title_format CHECK ( + char_length(title) BETWEEN 1 AND 200 + AND title !~ '^\s|\s$' + AND title !~ '[[:cntrl:]]' + -- Invisible format characters: zero-width, bidirectional marks and + -- overrides, line and paragraph separators, word joiner and + -- invisible operators, and the BOM. + AND title !~ '[\u200B-\u200F\u202A-\u202E\u2028\u2029\u2060-\u2064\u2066-\u206F\uFEFF]' + ), + CONSTRAINT assessment_families_bundle_name_format CHECK ( + bundle_name ~ '^[a-z][a-z0-9._-]{2,63}$' + ), + CONSTRAINT assessment_families_author_format CHECK ( + char_length(author) <= 128 + AND author ~ '^(ai|operator):[a-z0-9][a-z0-9._-]*$' + ), + CONSTRAINT assessment_families_reviewer_format CHECK ( + reviewer IS NULL OR ( + char_length(reviewer) <= 128 + AND reviewer ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) + ), + CONSTRAINT assessment_families_review_status_known CHECK ( + review_status IN ('pending', 'approved', 'rejected') + ), + -- A review is pending exactly while no reviewer is recorded. + CONSTRAINT assessment_families_review_has_reviewer CHECK ( + (review_status = 'pending') = (reviewer IS NULL) + ), + -- The review is independent: the reviewer is never the author. + CONSTRAINT assessment_families_reviewer_independent CHECK ( + reviewer IS NULL OR reviewer <> author + ), + CONSTRAINT assessment_families_documents_are_objects CHECK ( + jsonb_typeof(seed_generator) = 'object' + AND jsonb_typeof(answer_key) = 'object' + AND jsonb_typeof(rubric) = 'object' + ), + CONSTRAINT assessment_families_content_sha256_size CHECK ( + octet_length(content_sha256) = 32 + ), + CONSTRAINT assessment_families_hash_scheme_known CHECK ( + hash_scheme IN (1) + ), + CONSTRAINT assessment_families_lifecycle_known CHECK ( + lifecycle IN ('draft', 'published', 'retired') + ), + CONSTRAINT assessment_families_lifecycle_stamps CHECK ( + ( + lifecycle = 'draft' + AND published_at IS NULL AND published_by IS NULL + AND retired_at IS NULL AND retired_by IS NULL + ) OR ( + lifecycle = 'published' + AND published_at IS NOT NULL AND published_by IS NOT NULL + AND retired_at IS NULL AND retired_by IS NULL + ) OR ( + lifecycle = 'retired' + AND published_at IS NOT NULL AND published_by IS NOT NULL + AND retired_at IS NOT NULL AND retired_by IS NOT NULL + ) + ), + CONSTRAINT assessment_families_published_by_format CHECK ( + published_by IS NULL OR ( + char_length(published_by) <= 128 + AND published_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) + ), + CONSTRAINT assessment_families_retired_by_format CHECK ( + retired_by IS NULL OR ( + char_length(retired_by) <= 128 + AND retired_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) + ), + -- A family is published only with an approved review by a reviewer. + CONSTRAINT assessment_families_published_requires_review CHECK ( + lifecycle = 'draft' OR ( + reviewer IS NOT NULL AND review_status = 'approved' + ) + ) +); + +-- Coverage counts published families of a category. +CREATE INDEX assessment_families_category_lifecycle_idx +ON assessment_families (category, lifecycle); + +-- At most one version of a family is published. Publishing a newer version +-- retires the older one first, in the same transaction. +CREATE UNIQUE INDEX assessment_families_one_published_key +ON assessment_families (family_key) WHERE lifecycle = 'published'; + +-- Every new version starts as a draft. The database clock sets created_at and +-- the lifecycle columns, whatever the caller sent. +-- +goose StatementBegin +CREATE FUNCTION assessment_families_stamp_creation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + NEW.created_at := clock_timestamp(); + NEW.lifecycle := 'draft'; + NEW.published_at := NULL; + NEW.published_by := NULL; + NEW.retired_at := NULL; + NEW.retired_by := NULL; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_families_stamp_creation +BEFORE INSERT ON assessment_families +FOR EACH ROW EXECUTE FUNCTION assessment_families_stamp_creation(); + +-- Refuses every change except a forward lifecycle step. Any column other than +-- the lifecycle columns that differs between OLD and NEW is an edit of a +-- stored version. The caller names the operator of the step; the trigger sets +-- the time and keeps the publisher through a retirement. The errors use +-- SQLSTATE 23000 and the constraint names below, which the adapter maps to +-- port sentinels without reading the message. +-- +goose StatementBegin +CREATE FUNCTION assessment_families_guard_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (to_jsonb(NEW) - 'lifecycle' - 'published_at' - 'published_by' - 'retired_at' - 'retired_by') + IS DISTINCT FROM + (to_jsonb(OLD) - 'lifecycle' - 'published_at' - 'published_by' - 'retired_at' - 'retired_by') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_families_immutable', + TABLE = 'assessment_families', + MESSAGE = 'assessment family versions are immutable: import a new version instead'; + END IF; + IF OLD.lifecycle = 'draft' AND NEW.lifecycle = 'published' THEN + NEW.published_at := clock_timestamp(); + NEW.retired_at := NULL; + NEW.retired_by := NULL; + ELSIF OLD.lifecycle = 'published' AND NEW.lifecycle = 'retired' THEN + NEW.published_at := OLD.published_at; + NEW.published_by := OLD.published_by; + NEW.retired_at := clock_timestamp(); + ELSE + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_families_lifecycle_transition', + TABLE = 'assessment_families', + MESSAGE = 'assessment family lifecycle moves only draft to published to retired'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_families_guard_update +BEFORE UPDATE ON assessment_families +FOR EACH ROW EXECUTE FUNCTION assessment_families_guard_update(); + +-- Refuses DELETE and TRUNCATE. Row triggers do not fire for TRUNCATE, so a +-- statement trigger covers it. +-- +goose StatementBegin +CREATE FUNCTION assessment_families_refuse_removal() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_families_immutable', + TABLE = 'assessment_families', + MESSAGE = 'assessment family versions are immutable: import a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_families_refuse_delete +BEFORE DELETE ON assessment_families +FOR EACH ROW EXECUTE FUNCTION assessment_families_refuse_removal(); + +CREATE TRIGGER assessment_families_refuse_truncate +BEFORE TRUNCATE ON assessment_families +FOR EACH STATEMENT EXECUTE FUNCTION assessment_families_refuse_removal(); + +-- A category opening makes a category available. It records the versioned +-- policy the opening was made under, by reference, and the coverage the +-- database counted at that moment. An opening is never edited; the newest +-- opening of a category is the current one. +CREATE TABLE assessment_category_openings ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + category text NOT NULL, + -- The agreed basic grading policy: a policy_versions.id. Product + -- thresholds are read from this version; the bank stores no thresholds + -- of its own. The insert trigger checks that the version exists instead + -- of a FOREIGN KEY, because PostgreSQL refuses TRUNCATE of a referenced + -- table before the policy_versions trigger can refuse it with its own + -- error. Versions are never deleted, so the check cannot go stale. + policy_version_id uuid NOT NULL, + -- "operator:" of the person who agreed to open the category. + opened_by text NOT NULL, + -- Distinct published families the policy requires: the insert trigger + -- derives it from the referenced policy document, so a value from the + -- caller is ignored. + required_families integer NOT NULL, + -- Distinct published families counted by the insert trigger. + published_families integer NOT NULL, + -- Time from the database clock, set by the stamp trigger. + opened_at timestamptz NOT NULL, + CONSTRAINT assessment_category_openings_pkey PRIMARY KEY (id), + CONSTRAINT assessment_category_openings_category_format CHECK ( + category ~ '^[a-z][a-z0-9-]{1,47}$' + ), + CONSTRAINT assessment_category_openings_opened_by_format CHECK ( + char_length(opened_by) <= 128 + AND opened_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ), + CONSTRAINT assessment_category_openings_required_positive CHECK ( + required_families > 0 + ), + CONSTRAINT assessment_category_openings_coverage CHECK ( + published_families >= required_families + ) +); + +CREATE INDEX assessment_category_openings_category_idx +ON assessment_category_openings (category, opened_at DESC, id DESC); + +-- Checks the policy reference, derives the required coverage from the stored +-- policy document, counts the published families of the category, and stamps +-- the opening time. The coverage CHECK then refuses an opening whose category +-- has fewer published families than the policy requires. The requirement is +-- assessment.stop_rule.max_scored_items + assessment.stop_rule.seed_items, the +-- two paths that domain.RequiredPublishedAssessmentFamilies reads. A missing +-- policy version raises SQLSTATE 23503 under the constraint name that a +-- foreign key would have had; a document without the two values is refused +-- as well. The caller serializes openings, publications, and retirements of +-- a category with an advisory lock, so the count cannot miss a concurrent +-- retirement. +-- +goose StatementBegin +CREATE FUNCTION assessment_category_openings_stamp() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + maximum_text text; + seed_text text; +BEGIN + SELECT + policy.document #>> '{assessment,stop_rule,max_scored_items}', + policy.document #>> '{assessment,stop_rule,seed_items}' + INTO maximum_text, seed_text + FROM policy_versions AS policy + WHERE policy.id = NEW.policy_version_id; + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = 'foreign_key_violation', + CONSTRAINT = 'assessment_category_openings_policy_version_id_fkey', + TABLE = 'assessment_category_openings', + MESSAGE = 'assessment category opening references an unknown policy version'; + END IF; + -- The text is checked before the cast, so a malformed document of a row + -- written around the application raises the refusal below and not a cast + -- error (22P02 or 22003). + IF maximum_text IS NULL OR seed_text IS NULL + OR maximum_text !~ '^[0-9]{1,4}$' OR seed_text !~ '^[0-9]{1,4}$' THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'assessment_category_openings_policy_thresholds', + TABLE = 'assessment_category_openings', + MESSAGE = 'the referenced policy version has no scored item bounds'; + END IF; + NEW.required_families := maximum_text::integer + seed_text::integer; + NEW.opened_at := clock_timestamp(); + SELECT count(DISTINCT family.family_key)::integer + INTO NEW.published_families + FROM assessment_families AS family + WHERE family.category = NEW.category AND family.lifecycle = 'published'; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_category_openings_stamp +BEFORE INSERT ON assessment_category_openings +FOR EACH ROW EXECUTE FUNCTION assessment_category_openings_stamp(); + +-- +goose StatementBegin +CREATE FUNCTION assessment_category_openings_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_category_openings_immutable', + TABLE = 'assessment_category_openings', + MESSAGE = 'assessment category openings are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_category_openings_refuse_update_delete +BEFORE UPDATE OR DELETE ON assessment_category_openings +FOR EACH ROW EXECUTE FUNCTION assessment_category_openings_refuse_change(); + +CREATE TRIGGER assessment_category_openings_refuse_truncate +BEFORE TRUNCATE ON assessment_category_openings +FOR EACH STATEMENT EXECUTE FUNCTION assessment_category_openings_refuse_change(); + +-- +goose Down +DROP TABLE assessment_category_openings; +DROP FUNCTION assessment_category_openings_refuse_change(); +DROP FUNCTION assessment_category_openings_stamp(); +DROP TABLE assessment_families; +DROP FUNCTION assessment_families_refuse_removal(); +DROP FUNCTION assessment_families_guard_update(); +DROP FUNCTION assessment_families_stamp_creation(); diff --git a/backend/db/migrations/00012_add_delivery_sending.sql b/backend/db/migrations/00012_add_delivery_sending.sql new file mode 100644 index 0000000..104338f --- /dev/null +++ b/backend/db/migrations/00012_add_delivery_sending.sql @@ -0,0 +1,283 @@ +-- +goose Up +-- Sending of service identity mail. The sending worker claims a +-- due delivery under a lease, checks that the token and the account behind +-- it are still current, and ends a delivery that must not be sent in a +-- terminal non-sent status with a reason. +-- +-- Everything is additive: existing rows stay valid. Every new column is +-- nullable except failure_count, which is NOT NULL DEFAULT 0. No column holds +-- personal data or a secret. + +-- A reset token is a second purpose of the same table. The purpose names +-- what the token authorizes, and the worker compares it with the kind of the +-- delivery that carries it. +ALTER TABLE email_tokens DROP CONSTRAINT email_tokens_purpose_known; +ALTER TABLE email_tokens ADD CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification', 'password_reset') +); + +ALTER TABLE deliveries +ADD COLUMN email_token_id uuid, +ADD COLUMN cancel_reason text, +ADD COLUMN claim_owner uuid, +ADD COLUMN claimed_until timestamptz, +ADD COLUMN first_send_started_at timestamptz, +ADD COLUMN failure_count integer NOT NULL DEFAULT 0, +ADD COLUMN body_redacted_at timestamptz; + +COMMENT ON COLUMN deliveries.email_token_id IS +'The token whose link the body carries; set for verification and password reset mail, NULL for notifications. The worker checks the token before it sends.'; +COMMENT ON COLUMN deliveries.cancel_reason IS +'Why a cancelled delivery was not sent; set exactly when the status is cancelled.'; +COMMENT ON COLUMN deliveries.claim_owner IS +'Lease owner of the sending worker that claimed the delivery; NULL when no worker holds it.'; +COMMENT ON COLUMN deliveries.first_send_started_at IS +'When the first request of this delivery was started, by the database clock; the provider keeps the idempotency key for a window counted from here.'; +COMMENT ON COLUMN deliveries.failure_count IS +'Consecutive failures of the sending worker on this row (not provider answers); reset by a recorded attempt.'; +COMMENT ON COLUMN deliveries.body_redacted_at IS +'Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token.'; +COMMENT ON COLUMN deliveries.claimed_until IS +'When the lease of claim_owner expires; another worker may claim the delivery after it.'; + +-- The binding is by ID only. Deleting an account deletes its tokens and its +-- deliveries in one statement, so the reference needs no cascade of its own. +ALTER TABLE deliveries ADD CONSTRAINT deliveries_email_token_id_fkey +FOREIGN KEY (email_token_id) REFERENCES email_tokens (id); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_status_known; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_status_known CHECK ( + status IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota', + 'cancelled' + ) +); + +-- cancelled is terminal like accepted and rejected: no next attempt. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_next_attempt_matches_status; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_next_attempt_matches_status CHECK ( + (status = 'pending' AND next_attempt_at IS NOT NULL) + OR (status IN ('accepted', 'rejected', 'cancelled') AND next_attempt_at IS NULL) + OR status IN ('unknown', 'waiting_quota') +); + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_cancel_reason_matches_status CHECK ( + (status = 'cancelled') = (cancel_reason IS NOT NULL) + AND ( + cancel_reason IS NULL + OR cancel_reason IN ( + 'token_missing', + 'token_purpose_mismatch', + 'token_owner_mismatch', + 'token_consumed', + 'token_revoked', + 'token_expired', + 'account_not_current', + 'recipient_mismatch', + 'content_invalid', + 'processing_failed' + ) + ) +); + +-- A lease has an owner and a deadline together, and only a delivery that a +-- worker may still send holds one. +ALTER TABLE deliveries ADD CONSTRAINT deliveries_claim_complete CHECK ( + (claim_owner IS NULL) = (claimed_until IS NULL) + AND ( + claim_owner IS NULL + OR status IN ('pending', 'waiting_quota', 'unknown') + ) +); + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_token_only_for_token_kinds CHECK ( + email_token_id IS NULL OR kind IN ('verification', 'password_reset') +); + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_failure_count_not_negative CHECK ( + failure_count >= 0 +); + +-- A redacted token mail has no bodies; any other delivery has at least one. +-- Only a terminal token mail may be redacted. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( + (body_redacted_at IS NULL AND (text_body <> '' OR html_body <> '')) + OR ( + body_redacted_at IS NOT NULL + AND text_body = '' AND html_body = '' + AND kind IN ('verification', 'password_reset') + AND status IN ('accepted', 'rejected', 'cancelled') + ) +); + +-- Serves the claim of due service mail. The predicate names the kinds the +-- sending worker handles, so rows of other kinds (product notifications) +-- never enter the index and an idle poll does not scan them. +-- The claim query repeats the kind literals so the planner can use it. +CREATE INDEX deliveries_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota') + AND next_attempt_at IS NOT NULL + AND kind IN ('verification', 'password_reset'); + +-- Serves the foreign key check when a token is deleted. +CREATE INDEX deliveries_email_token_id_idx +ON deliveries (email_token_id) +WHERE email_token_id IS NOT NULL; + +-- The token a delivery is bound to never changes, like the rest of what the +-- delivery sends. The attempt state, the cancel reason, and the lease stay +-- updatable. The bodies of a token mail change in exactly one way: once, to +-- empty, together with body_redacted_at, when the delivery is terminal, so +-- no token outlives its mail. Errors are the same as in migration 00006. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.content_sha256, + NEW.idempotency_key, NEW.created_at, NEW.email_token_id + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.content_sha256, + OLD.idempotency_key, OLD.created_at, OLD.email_token_id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF (NEW.text_body, NEW.html_body) IS DISTINCT FROM (OLD.text_body, OLD.html_body) THEN + IF NOT ( + OLD.body_redacted_at IS NULL AND NEW.body_redacted_at IS NOT NULL + AND NEW.text_body = '' AND NEW.html_body = '' + AND NEW.status IN ('accepted', 'rejected', 'cancelled') + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + ELSIF OLD.body_redacted_at IS DISTINCT FROM NEW.body_redacted_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +-- +goose Down +-- A cancelled delivery becomes rejected, the closest status of the earlier +-- schema, and reset tokens are removed with the purpose that no longer +-- exists. The checks that tie a reason to the cancelled status go first, so +-- the status can change. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_token_only_for_token_kinds; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_claim_complete; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status; + +UPDATE deliveries SET status = 'rejected' WHERE status = 'cancelled'; + +-- Redacted bodies cannot come back; a placeholder keeps the earlier schema's +-- body check satisfied. The placeholder no longer matches content_sha256, so +-- code of the earlier schema cannot restore such a row as content: it reads +-- terminal rows only through the status reader, which selects no body, and +-- never sends them. The content trigger is lifted for this one statement. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present; +ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change; +UPDATE deliveries SET text_body = 'redacted' WHERE body_redacted_at IS NOT NULL; +ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change; + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.text_body, NEW.html_body, NEW.content_sha256, + NEW.idempotency_key, NEW.created_at + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.text_body, OLD.html_body, OLD.content_sha256, + OLD.idempotency_key, OLD.created_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +DROP INDEX deliveries_email_token_id_idx; +DROP INDEX deliveries_due_idx; + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_failure_count_not_negative; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( + text_body <> '' OR html_body <> '' +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_next_attempt_matches_status; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_next_attempt_matches_status CHECK ( + (status = 'pending' AND next_attempt_at IS NOT NULL) + OR (status IN ('accepted', 'rejected') AND next_attempt_at IS NULL) + OR status IN ('unknown', 'waiting_quota') +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_status_known; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_status_known CHECK ( + status IN ( + 'pending', 'accepted', 'rejected', 'unknown', 'waiting_quota' + ) +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_email_token_id_fkey; +ALTER TABLE deliveries +DROP COLUMN body_redacted_at, +DROP COLUMN failure_count, +DROP COLUMN first_send_started_at, +DROP COLUMN claimed_until, +DROP COLUMN claim_owner, +DROP COLUMN cancel_reason, +DROP COLUMN email_token_id; + +DELETE FROM email_tokens WHERE purpose = 'password_reset'; +ALTER TABLE email_tokens DROP CONSTRAINT email_tokens_purpose_known; +ALTER TABLE email_tokens ADD CONSTRAINT email_tokens_purpose_known CHECK ( + purpose IN ('email_verification') +); diff --git a/backend/db/migrations/00013_create_candidate_profiles.sql b/backend/db/migrations/00013_create_candidate_profiles.sql new file mode 100644 index 0000000..eed7c09 --- /dev/null +++ b/backend/db/migrations/00013_create_candidate_profiles.sql @@ -0,0 +1,311 @@ +-- +goose Up +-- The manual candidate profile (PRD FR02): full name and contacts, +-- stack, roles, work experience, soft skills, and desired terms, each value +-- with its confirmation state and provenance. Enum-like columns are text with +-- CHECK constraints, as in the identity tables. +-- +-- The rows are personal data of the candidate (names, contacts, work +-- history, the lowest salary), so the application never copies a value into +-- logs, metrics, events, or URLs. Only the owning account reads them; no +-- organization-visible query selects from these tables. +-- +-- The profile stands on its own. Nothing here references a resume file, the +-- object storage, the ML service, or an FSP account: a profile that was typed +-- by hand is complete, and a later import adds its own columns or tables +-- (additively) instead of changing the meaning of these. +-- +-- A confirmed grade or category is deliberately not stored here. It comes +-- from assessment results, and the self-assessed grade of a role is only a +-- claim inside the value of a role claim, so no statement against these +-- tables can write a confirmed category. +CREATE TABLE candidate_profiles ( + -- The account that owns the profile. One profile per candidate; the + -- profile is created by the first save and the app never reads another + -- account's row. + user_id uuid NOT NULL, + -- Optimistic concurrency version, advanced by every save that changes the + -- profile. A first save creates version 1; the contract's version 0 is + -- the absence of a row. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_profiles_pkey PRIMARY KEY (user_id), + -- The profile is personal data of the account and goes with it when the + -- account is erased. The retention rules are an open legal question. + CONSTRAINT candidate_profiles_user_id_fkey FOREIGN KEY ( + user_id + ) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_profiles_version_positive CHECK (version > 0), + CONSTRAINT candidate_profiles_updated_after_creation CHECK ( + updated_at >= created_at + ) +); + +-- One row per stored claim: a single field (kind full_name, contact_*, +-- terms_*, at ordinal 0) or one item of a list (stack, role, experience, +-- soft_skill, at its position). A field without a value has no row, so the +-- contract's `unknown` state is the absence of the row, and every row holds a +-- value with a status of confirmed or extracted. The whole set of a profile is +-- replaced in one transaction with the version bump. +-- +-- The value is jsonb because the kinds have different shapes (a string, a +-- boolean, or an object). Each kind has its own CHECK for the shape and the +-- bounds of the contract, and the domain validates the value in full before +-- it is stored. +CREATE TABLE candidate_profile_claims ( + user_id uuid NOT NULL, + kind text NOT NULL, + -- Position in a list, from 0; always 0 for a single field. + ordinal smallint NOT NULL, + value jsonb NOT NULL, + -- confirmed: the candidate typed or confirmed the value. extracted: a + -- suggestion from an imported source that nobody confirmed. + status text NOT NULL, + -- manual, or an import origin (planned: extracted_from_resume, imported). + origin text NOT NULL, + -- Every claim of the profile has trust level 0 whatever its origin; + -- higher levels belong to evidence, which is stored elsewhere. The column + -- states the rule in the schema, so an import can never store a claim + -- with a higher level. + trust_level smallint NOT NULL, + -- Excerpt of the imported document that the value came from. It can hold + -- personal data. NULL for a manual value. + quote text, + -- Opaque label of the extractor version. NULL for a manual value. + extraction_version text, + -- When the candidate typed or confirmed the value; NULL while it is an + -- unconfirmed suggestion. + confirmed_at timestamptz, + CONSTRAINT candidate_profile_claims_pkey PRIMARY KEY ( + user_id, kind, ordinal + ), + -- The claims belong to the profile row and go with it. + CONSTRAINT candidate_profile_claims_user_id_fkey FOREIGN KEY ( + user_id + ) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE, + CONSTRAINT candidate_profile_claims_kind_ordinal CHECK ( + ( + kind IN ( + 'full_name', + 'contact_email', + 'contact_phone', + 'contact_telegram', + 'terms_location', + 'terms_relocation', + 'terms_salary_minimum' + ) + AND ordinal = 0 + ) + OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29) + OR (kind = 'role' AND ordinal BETWEEN 0 AND 8) + OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19) + OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9) + ), + CONSTRAINT candidate_profile_claims_status_known CHECK ( + status IN ('confirmed', 'extracted') + ), + CONSTRAINT candidate_profile_claims_origin_known CHECK ( + origin IN ('manual', 'extracted_from_resume', 'imported') + ), + CONSTRAINT candidate_profile_claims_trust_level_zero CHECK ( + trust_level = 0 + ), + -- A confirmed value says when; a suggestion does not. + CONSTRAINT candidate_profile_claims_confirmation CHECK ( + (status = 'confirmed' AND confirmed_at IS NOT NULL) + OR (status = 'extracted' AND confirmed_at IS NULL) + ), + -- A manual value is confirmed by definition and has no import data. An + -- imported value names its extractor, and an unconfirmed one is always + -- an import. + CONSTRAINT candidate_profile_claims_origin_provenance CHECK ( + ( + origin = 'manual' + AND status = 'confirmed' + AND quote IS NULL + AND extraction_version IS NULL + ) + OR (origin <> 'manual' AND extraction_version IS NOT NULL) + ), + CONSTRAINT candidate_profile_claims_quote_format CHECK ( + quote IS NULL OR ( + char_length(quote) BETWEEN 1 AND 300 + AND translate(quote, E'\n', '') !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT candidate_profile_claims_extraction_version_format CHECK ( + extraction_version IS NULL + OR extraction_version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + -- Value shapes. The bounds repeat the schemas of the public contract. + CONSTRAINT candidate_profile_claims_full_name_value CHECK ( + kind <> 'full_name' OR ( + jsonb_typeof(value) = 'string' + AND char_length(value #>> '{}') BETWEEN 1 AND 200 + AND value #>> '{}' !~ '^\s|\s$' + AND value #>> '{}' !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT candidate_profile_claims_contact_email_value CHECK ( + kind <> 'contact_email' OR ( + jsonb_typeof(value) = 'string' + AND char_length(value #>> '{}') BETWEEN 3 AND 254 + AND value #>> '{}' ~ '^[^@\s]+@[^@\s]+$' + ) + ), + -- E.164, the format of the contact disclosure. + CONSTRAINT candidate_profile_claims_contact_phone_value CHECK ( + kind <> 'contact_phone' OR ( + jsonb_typeof(value) = 'string' + AND value #>> '{}' ~ '^\+[1-9][0-9]{6,14}$' + ) + ), + CONSTRAINT candidate_profile_claims_contact_telegram_value CHECK ( + kind <> 'contact_telegram' OR ( + jsonb_typeof(value) = 'string' + AND value #>> '{}' ~ '^@[A-Za-z0-9_]{5,32}$' + ) + ), + CONSTRAINT candidate_profile_claims_stack_value CHECK ( + kind <> 'stack' OR ( + jsonb_typeof(value) = 'string' + AND char_length(value #>> '{}') BETWEEN 1 AND 50 + AND value #>> '{}' !~ '^\s|\s$' + AND value #>> '{}' !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT candidate_profile_claims_soft_skill_value CHECK ( + kind <> 'soft_skill' OR ( + jsonb_typeof(value) = 'string' + AND char_length(value #>> '{}') BETWEEN 1 AND 50 + AND value #>> '{}' !~ '^\s|\s$' + AND value #>> '{}' !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT candidate_profile_claims_terms_location_value CHECK ( + kind <> 'terms_location' OR ( + jsonb_typeof(value) = 'string' + AND char_length(value #>> '{}') BETWEEN 1 AND 100 + AND value #>> '{}' !~ '^\s|\s$' + AND value #>> '{}' !~ '[[:cntrl:]]' + ) + ), + CONSTRAINT candidate_profile_claims_terms_relocation_value CHECK ( + kind <> 'terms_relocation' OR jsonb_typeof(value) = 'boolean' + ), + -- A positive multiple of 1000 up to 100 000 000, in the only currency, + -- period, and tax bases of the MVP. + CONSTRAINT candidate_profile_claims_terms_salary_minimum_value CHECK ( + kind <> 'terms_salary_minimum' OR ( + jsonb_typeof(value) = 'object' + AND value ?& ARRAY['amount', 'currency', 'period', 'tax_basis'] + AND value - 'amount' - 'currency' - 'period' - 'tax_basis' + = '{}'::jsonb + AND jsonb_typeof(value -> 'amount') = 'number' + AND value ->> 'amount' ~ '^([1-9][0-9]{0,4}000|100000000)$' + AND value -> 'currency' = '"RUB"'::jsonb + AND value -> 'period' = '"month"'::jsonb + AND value ->> 'tax_basis' IN ('net', 'gross') + ) + ), + -- The self-assessed grade is a claim of the role. A confirmed grade is not + -- a key of the value. + CONSTRAINT candidate_profile_claims_role_value CHECK ( + kind <> 'role' OR ( + jsonb_typeof(value) = 'object' + AND value ?& ARRAY['specialization', 'self_assessed_grade'] + AND value - 'specialization' - 'self_assessed_grade' = '{}'::jsonb + AND value ->> 'specialization' IN ( + 'backend', + 'frontend', + 'mobile', + 'network_engineer', + 'devops_sre', + 'data_analyst', + 'ds_ml', + 'information_security', + 'qa' + ) + AND ( + jsonb_typeof(value -> 'self_assessed_grade') = 'null' + OR value ->> 'self_assessed_grade' IN ( + 'intern', 'junior', 'middle', 'senior' + ) + ) + ) + ), + CONSTRAINT candidate_profile_claims_experience_value CHECK ( + kind <> 'experience' OR ( + jsonb_typeof(value) = 'object' + AND value ?& ARRAY[ + 'employer_name', + 'specialization', + 'started_on', + 'ended_on', + 'summary' + ] + AND value - 'employer_name' - 'specialization' - 'started_on' + - 'ended_on' - 'summary' = '{}'::jsonb + AND value ->> 'specialization' IN ( + 'backend', + 'frontend', + 'mobile', + 'network_engineer', + 'devops_sre', + 'data_analyst', + 'ds_ml', + 'information_security', + 'qa' + ) + AND jsonb_typeof(value -> 'started_on') = 'string' + AND value ->> 'started_on' ~ '^[0-9]{4}-(0[1-9]|1[0-2])$' + AND ( + jsonb_typeof(value -> 'ended_on') = 'null' + OR ( + jsonb_typeof(value -> 'ended_on') = 'string' + AND value ->> 'ended_on' ~ '^[0-9]{4}-(0[1-9]|1[0-2])$' + AND value ->> 'ended_on' >= value ->> 'started_on' + ) + ) + AND ( + jsonb_typeof(value -> 'employer_name') = 'null' + OR ( + jsonb_typeof(value -> 'employer_name') = 'string' + AND char_length(value ->> 'employer_name') BETWEEN 1 AND 200 + AND value ->> 'employer_name' !~ '^\s|\s$' + AND value ->> 'employer_name' !~ '[[:cntrl:]]' + ) + ) + AND ( + jsonb_typeof(value -> 'summary') = 'null' + OR ( + jsonb_typeof(value -> 'summary') = 'string' + AND char_length(value ->> 'summary') BETWEEN 1 AND 1000 + AND value ->> 'summary' !~ '^\s|\s$' + AND translate(value ->> 'summary', E'\n', '') + !~ '[[:cntrl:]]' + ) + ) + ) + ) +); + +-- A tag or a skill appears once and a specialization appears in one role. The +-- indexes compare the stored text exactly; the case-insensitive comparison +-- of the contract belongs to the domain, because PostgreSQL lower() depends +-- on the collation. +CREATE UNIQUE INDEX candidate_profile_claims_stack_key +ON candidate_profile_claims (user_id, (value #>> '{}')) +WHERE kind = 'stack'; + +CREATE UNIQUE INDEX candidate_profile_claims_soft_skill_key +ON candidate_profile_claims (user_id, (value #>> '{}')) +WHERE kind = 'soft_skill'; + +CREATE UNIQUE INDEX candidate_profile_claims_role_specialization_key +ON candidate_profile_claims (user_id, (value ->> 'specialization')) +WHERE kind = 'role'; + +-- +goose Down +DROP TABLE candidate_profile_claims; +DROP TABLE candidate_profiles; diff --git a/backend/db/migrations/00014_create_idempotency_records.sql b/backend/db/migrations/00014_create_idempotency_records.sql new file mode 100644 index 0000000..c648c98 --- /dev/null +++ b/backend/db/migrations/00014_create_idempotency_records.sql @@ -0,0 +1,84 @@ +-- +goose Up +-- Replay records of anonymous commands that carry an Idempotency-Key, first +-- of all the registration. A record is written in the same transaction as +-- the effect it guards, so a record that is visible always belongs to a +-- committed command: a running command is represented by the uncommitted row +-- itself, on which a concurrent request with the same scope waits. +-- +-- Nothing here identifies a person or reveals a credential. scope_hash is an +-- HMAC-SHA-256 with a server secret over the operation, the key, and the +-- normalized email, and fingerprint is an HMAC-SHA-256 with a server secret +-- over the canonical request body; without the secret neither can be used to +-- confirm an email address or to test a password offline. +CREATE TABLE idempotency_records ( + scope_hash bytea NOT NULL, + fingerprint bytea NOT NULL, + created_at timestamptz NOT NULL, + -- The key may be accepted as new once this time has passed. + expires_at timestamptz NOT NULL, + CONSTRAINT idempotency_records_pkey PRIMARY KEY (scope_hash), + CONSTRAINT idempotency_records_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT idempotency_records_fingerprint_sha256 CHECK ( + octet_length(fingerprint) = 32 + ), + CONSTRAINT idempotency_records_expiry_after_creation CHECK ( + expires_at > created_at + ) +); + +-- Serves the bounded purge of expired records. +CREATE INDEX idempotency_records_expires_at_idx +ON idempotency_records (expires_at); + +-- Pending credentials of a registration, bound to the verification token +-- issued for it. A registration of an unverified address never changes the +-- credentials of the account row: it issues a token that carries its own +-- password hash and scenario. Confirming a token applies the credentials of +-- that token, so whoever registered an address first or last cannot make the +-- owner of the address adopt a password the owner did not choose. NULL for +-- tokens that carry none (a resend copies them from the registration's +-- latest token; password reset tokens carry none). +ALTER TABLE email_tokens +ADD COLUMN pending_password_hash text, +ADD COLUMN pending_scenario text, +ADD COLUMN pending_onboarding_step text, +ADD CONSTRAINT email_tokens_pending_all_or_none CHECK ( + (pending_password_hash IS NULL) = (pending_scenario IS NULL) + AND (pending_scenario IS NULL) = (pending_onboarding_step IS NULL) +), +ADD CONSTRAINT email_tokens_invalidated_keeps_no_pending CHECK ( + invalidated_at IS NULL OR pending_password_hash IS NULL +), +ADD CONSTRAINT email_tokens_pending_password_hash_format CHECK ( + pending_password_hash IS NULL + OR ( + char_length(pending_password_hash) <= 512 + AND pending_password_hash + ~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ) +), +ADD CONSTRAINT email_tokens_pending_scenario_step CHECK ( + pending_scenario IS NULL + OR ( + pending_scenario = 'candidate' + AND pending_onboarding_step = 'candidate_consents' + ) + OR ( + pending_scenario = 'employer' + AND pending_onboarding_step = 'employer_company' + ) +); + +-- +goose Down +ALTER TABLE email_tokens +DROP CONSTRAINT email_tokens_pending_scenario_step, +DROP CONSTRAINT email_tokens_invalidated_keeps_no_pending, +DROP CONSTRAINT email_tokens_pending_password_hash_format, +DROP CONSTRAINT email_tokens_pending_all_or_none, +DROP COLUMN pending_onboarding_step, +DROP COLUMN pending_scenario, +DROP COLUMN pending_password_hash; + +DROP TABLE idempotency_records; diff --git a/backend/db/migrations/00015_create_candidate_privacy.sql b/backend/db/migrations/00015_create_candidate_privacy.sql new file mode 100644 index 0000000..04d61d7 --- /dev/null +++ b/backend/db/migrations/00015_create_candidate_privacy.sql @@ -0,0 +1,440 @@ +-- +goose Up +-- Visibility of the candidate card (PRD FR02 and FR12): the +-- publication, the search status, the organizations the candidate hides the +-- profile from, and the history of these settings. Enum-like columns are text +-- with CHECK constraints, as in the other tables. +-- +-- A profile is closed by default: nothing here is created with the profile +-- or with the account, and a missing row means "closed", "not looking", or +-- "not hidden". Every row is written by an explicit act of the candidate. +-- +-- The three settings are separate tables on purpose. The consent C2 stays in +-- the consent ledger and proves that the candidate accepted the publication +-- text; candidate_publications refers to that record and records what the +-- ledger deliberately does not (which fields, and when). The search status is +-- a statement of the candidate, never a consent, so it has no consent column +-- and no statement of one table writes another table. No row stores a +-- profile value, a name, or a contact: the rows hold card field codes, +-- identifiers, and times. + +-- Card field codes in the canonical form of the stored sets: distinct, +-- without NULLs, known, in ascending byte order. A canonical form makes equal +-- sets equal arrays. The set is empty for a closed publication. The codes +-- are the contract's CardField, which never includes the name, a contact, or +-- the lowest salary. +-- +goose StatementBegin +CREATE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 6 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'soft_skills', 'stack' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- A composite foreign key below needs a unique key over the ledger columns +-- it names. The record id is already unique, so this adds no restriction; it +-- lets a publication refer to a C2 record of its own account and no other. +CREATE UNIQUE INDEX consent_records_id_subject_purpose_key +ON consent_records (id, subject_id, purpose); + +-- One row per candidate, created by the first explicit publication. A row +-- exists only after the candidate published once, so a new profile has no +-- row and is closed. state is the stored setting; the effective state also +-- needs the referenced C2 record to be unrevoked, which the read query joins +-- from the ledger. A revocation therefore closes the card at once without any +-- write here, and a later C2 grant opens nothing: a publication is bound to +-- the record that backed it, and republishing binds it to the new one. +CREATE TABLE candidate_publications ( + user_id uuid NOT NULL, + -- published: organizations may read the fields. closed: the candidate + -- closed the publication; the row keeps the last published time and the + -- C2 record as evidence. + state text NOT NULL, + -- Card field codes in canonical order; empty exactly when closed. + fields text [] NOT NULL, + -- The C2 record that backed the latest publication. Always the C2 of this + -- account: the foreign key names the subject and the purpose. + consent_record_id uuid NOT NULL, + consent_purpose text GENERATED ALWAYS AS ('c2') STORED, + -- The time of the latest change that published or republished the card. + published_at timestamptz NOT NULL, + -- The time the candidate closed the publication; NULL while published. + closed_at timestamptz, + -- Optimistic concurrency version; the first publication creates 1 and + -- the contract's version 0 is the absence of a row. + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_publications_pkey PRIMARY KEY (user_id), + CONSTRAINT candidate_publications_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + -- Consent evidence outlives a careless delete of the setting: the record + -- cannot be deleted while a publication refers to it. + CONSTRAINT candidate_publications_consent_fkey FOREIGN KEY ( + consent_record_id, user_id, consent_purpose + ) REFERENCES consent_records (id, subject_id, purpose) ON DELETE RESTRICT, + CONSTRAINT candidate_publications_state_known CHECK ( + state IN ('published', 'closed') + ), + CONSTRAINT candidate_publications_fields_canonical CHECK ( + candidate_card_fields_are_canonical(fields) + ), + CONSTRAINT candidate_publications_state_shape CHECK ( + ( + state = 'published' + AND cardinality(fields) > 0 + AND closed_at IS NULL + ) + OR ( + state = 'closed' + AND cardinality(fields) = 0 + AND closed_at IS NOT NULL + AND closed_at >= published_at + ) + ), + CONSTRAINT candidate_publications_version_positive CHECK (version > 0), + CONSTRAINT candidate_publications_updated_after_creation CHECK ( + updated_at >= created_at + ) +); + +-- The search status of the candidate. A status that was never set has no row +-- (not_looking). looking stores the confirmation time and the lapse time, +-- which the application fixes from the search_status section of the product +-- policy version in force at the confirmation, and the version it used. The +-- lapse itself is computed by comparing lapses_at with the clock and is never +-- written: no process turns an expired status into a more public state. +-- Nothing here refers to a consent, the publication, or the hidden +-- organizations. +CREATE TABLE candidate_search_statuses ( + user_id uuid NOT NULL, + status text NOT NULL, + -- The latest confirmation of looking; NULL for not_looking. + confirmed_at timestamptz, + -- When the confirmed status lapses; NULL for not_looking. + lapses_at timestamptz, + -- The policy version whose interval produced lapses_at; NULL for + -- not_looking. Policy versions are immutable and never deleted. A trigger + -- below checks the reference instead of a foreign key, because a foreign + -- key would make PostgreSQL refuse TRUNCATE of policy_versions before its + -- own immutability trigger could answer. + policy_version_id uuid, + version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_search_statuses_pkey PRIMARY KEY (user_id), + CONSTRAINT candidate_search_statuses_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_search_statuses_status_known CHECK ( + status IN ('looking', 'not_looking') + ), + -- looking always carries its confirmation, lapse, and policy version; + -- not_looking carries none of them. + CONSTRAINT candidate_search_statuses_confirmation CHECK ( + ( + status = 'looking' + AND confirmed_at IS NOT NULL + AND lapses_at IS NOT NULL + AND policy_version_id IS NOT NULL + AND lapses_at > confirmed_at + ) + OR ( + status = 'not_looking' + AND confirmed_at IS NULL + AND lapses_at IS NULL + AND policy_version_id IS NULL + ) + ), + CONSTRAINT candidate_search_statuses_version_positive CHECK (version > 0), + CONSTRAINT candidate_search_statuses_updated_after_creation CHECK ( + updated_at >= created_at + ) +); + +-- Stands in for a foreign key to policy_versions: an unknown policy version +-- raises SQLSTATE 23503 under the constraint name that the foreign key would +-- have had. Policy versions are immutable and cannot be deleted, so checking +-- when the reference is written is enough. +-- +goose StatementBegin +CREATE FUNCTION candidate_search_statuses_check_policy() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.policy_version_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM policy_versions WHERE id = NEW.policy_version_id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'foreign_key_violation', + CONSTRAINT = 'candidate_search_statuses_policy_fkey', + TABLE = 'candidate_search_statuses', + MESSAGE = 'search status references an unknown policy version'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_search_statuses_check_policy +BEFORE INSERT OR UPDATE OF policy_version_id ON candidate_search_statuses +FOR EACH ROW EXECUTE FUNCTION candidate_search_statuses_check_policy(); + +-- The organizations a candidate hides the profile from. The record belongs to +-- the candidate and references the organization; no organization reads it. +-- One record per pair, so a hiding is unique. The primary key starts with the +-- candidate, which serves every candidate-scoped read. Organizations are never +-- deleted by the application, so RESTRICT keeps a hiding from silently +-- disappearing with one. +CREATE TABLE candidate_hidden_organizations ( + user_id uuid NOT NULL, + organization_id uuid NOT NULL, + hidden_at timestamptz NOT NULL, + CONSTRAINT candidate_hidden_organizations_pkey PRIMARY KEY ( + user_id, organization_id + ), + CONSTRAINT candidate_hidden_organizations_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_hidden_organizations_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT +); + +-- Serves the candidate's list, newest first. +CREATE INDEX candidate_hidden_organizations_listing_idx +ON candidate_hidden_organizations (user_id, hidden_at DESC, organization_id DESC); + +-- Serves the organization side, which has to exclude hidden candidates from +-- its reads without learning who hid it. +CREATE INDEX candidate_hidden_organizations_organization_idx +ON candidate_hidden_organizations (organization_id, user_id); + +-- Bounds the hidden list of one candidate. The trigger serializes the inserts +-- of one candidate through a lock on the account row (a no-key update lock, +-- which does not block other readers of the account), counts the committed +-- rows, and refuses the insert over the bound with SQLSTATE 23514 and the +-- constraint name candidate_hidden_organizations_limit, which the adapter +-- maps to a port sentinel without reading the message. Raising the bound +-- also raises the maximum of the contract's hidden_organizations_total. +-- +goose StatementBegin +CREATE FUNCTION candidate_hidden_organizations_enforce_limit() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM 1 FROM users WHERE id = NEW.user_id FOR NO KEY UPDATE; + IF ( + SELECT count(*) FROM candidate_hidden_organizations + WHERE user_id = NEW.user_id + ) >= 1000 THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'candidate_hidden_organizations_limit', + TABLE = 'candidate_hidden_organizations', + MESSAGE = 'a candidate hides at most 1000 organizations'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_hidden_organizations_enforce_limit +BEFORE INSERT ON candidate_hidden_organizations +FOR EACH ROW EXECUTE FUNCTION candidate_hidden_organizations_enforce_limit(); + +-- The append-only history of the settings: what the candidate published, +-- announced, and hid, and when. It keeps the published field set and its +-- changes with their times, which the C2 record of the ledger does not carry. +-- A revocation of C2 and a lapse of the search status are computed and are not +-- events. The rows hold identifiers, card field codes, and times; never a +-- profile value or a name. The hide and unhide records are sensitive: they say +-- which employer a candidate avoids. +-- +-- It is evidence like the consent ledger. A trigger refuses every UPDATE, and +-- refuses DELETE while the account is confirmed (the same condition as +-- consent_records_refuse_delete, which the retention rule and the account +-- deletion procedure extend in their own migration). The account reference +-- cascades, so the unverified account cleanup removes the rows of an account +-- it deletes and a confirmed account is protected by the trigger. +-- TRUNCATE stays allowed for test isolation. +CREATE TABLE candidate_privacy_events ( + -- UUIDv7 generated in Go. + id uuid NOT NULL, + user_id uuid NOT NULL, + kind text NOT NULL, + occurred_at timestamptz NOT NULL, + -- The published field set after a publication event; empty for a closing; + -- NULL for every other kind. + fields text [], + -- The C2 record behind a publication or republication; NULL otherwise. + consent_record_id uuid, + consent_purpose text GENERATED ALWAYS AS ( + CASE WHEN consent_record_id IS NOT NULL THEN 'c2' END + ) STORED, + -- The organization of a hiding event. Only the identifier is kept: the + -- candidate's read resolves the current name, so the history holds no + -- text about an organization. + organization_id uuid, + CONSTRAINT candidate_privacy_events_pkey PRIMARY KEY (id), + CONSTRAINT candidate_privacy_events_user_id_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + -- MATCH SIMPLE skips the check while consent_purpose is NULL. + CONSTRAINT candidate_privacy_events_consent_fkey FOREIGN KEY ( + consent_record_id, user_id, consent_purpose + ) REFERENCES consent_records (id, subject_id, purpose) ON DELETE RESTRICT, + CONSTRAINT candidate_privacy_events_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT candidate_privacy_events_kind_known CHECK ( + kind IN ( + 'publication_opened', 'publication_changed', 'publication_closed', + 'search_status_confirmed', 'search_status_cleared', + 'organization_hidden', 'organization_unhidden' + ) + ), + CONSTRAINT candidate_privacy_events_shape CHECK ( + ( + kind IN ('publication_opened', 'publication_changed') + AND fields IS NOT NULL + AND cardinality(fields) > 0 + AND candidate_card_fields_are_canonical(fields) + AND consent_record_id IS NOT NULL + AND organization_id IS NULL + ) + OR ( + kind = 'publication_closed' + AND fields IS NOT NULL + AND cardinality(fields) = 0 + AND consent_record_id IS NULL + AND organization_id IS NULL + ) + OR ( + kind IN ('search_status_confirmed', 'search_status_cleared') + AND fields IS NULL + AND consent_record_id IS NULL + AND organization_id IS NULL + ) + OR ( + kind IN ('organization_hidden', 'organization_unhidden') + AND fields IS NULL + AND consent_record_id IS NULL + AND organization_id IS NOT NULL + ) + ) +); + +-- Serves the candidate's history, newest first. +CREATE INDEX candidate_privacy_events_user_occurred_idx +ON candidate_privacy_events (user_id, occurred_at DESC, id DESC); + +-- Refuses every UPDATE of an event with SQLSTATE 23000 and the constraint +-- name candidate_privacy_events_immutable. The message quotes no row value. +-- +goose StatementBegin +CREATE FUNCTION candidate_privacy_events_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_privacy_events_immutable', + TABLE = 'candidate_privacy_events', + MESSAGE = 'privacy events are append-only: record a new event instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_privacy_events_refuse_update +BEFORE UPDATE ON candidate_privacy_events +FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_refuse_update(); + +-- Allows deleting an event only while its account is not confirmed: the +-- unverified account cleanup. The history of a confirmed account is evidence +-- and stays (SQLSTATE 23000, constraint candidate_privacy_events_retained). +-- The retention rule and the right to erasure extend this condition in their +-- own migration. +-- +goose StatementBegin +CREATE FUNCTION candidate_privacy_events_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM users + WHERE users.id = OLD.user_id AND users.email_verified_at IS NOT NULL + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_privacy_events_retained', + TABLE = 'candidate_privacy_events', + MESSAGE = 'privacy events of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_privacy_events_refuse_delete +BEFORE DELETE ON candidate_privacy_events +FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_refuse_delete(); + +-- The cascade of the account deletion runs after the account row is gone, so +-- the delete trigger above cannot see that the account was confirmed. This +-- trigger on users refuses deleting a confirmed account that has history, with +-- the same constraint name, before the cascade starts. +-- +goose StatementBegin +CREATE FUNCTION candidate_privacy_events_protect_account() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.email_verified_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM candidate_privacy_events WHERE user_id = OLD.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_privacy_events_retained', + TABLE = 'candidate_privacy_events', + MESSAGE = 'privacy events of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_privacy_events_protect_account +BEFORE DELETE ON users +FOR EACH ROW EXECUTE FUNCTION candidate_privacy_events_protect_account(); + +-- The only way an organization-facing read may see a publication: published +-- by the candidate AND backed by a C2 record that is not revoked. Every read +-- on behalf of an organization (the search, the card, the contact read) must +-- select from this view and must add NOT EXISTS over +-- candidate_hidden_organizations for the reading organization. Reading +-- candidate_publications directly is reserved for the candidate's own +-- settings queries; a test over db/queries enforces the list. +CREATE VIEW candidate_effective_publications +WITH (security_invoker = true) AS +SELECT + publication.user_id, + publication.fields, + publication.published_at, + publication.version +FROM candidate_publications AS publication +INNER JOIN consent_records AS consent + ON consent.id = publication.consent_record_id +WHERE publication.state = 'published' AND consent.revoked_at IS NULL; + +-- +goose Down +DROP VIEW candidate_effective_publications; +DROP TRIGGER candidate_privacy_events_protect_account ON users; +DROP FUNCTION candidate_privacy_events_protect_account(); +DROP TABLE candidate_privacy_events; +DROP FUNCTION candidate_privacy_events_refuse_delete(); +DROP FUNCTION candidate_privacy_events_refuse_update(); +DROP TABLE candidate_hidden_organizations; +DROP FUNCTION candidate_hidden_organizations_enforce_limit(); +DROP TABLE candidate_search_statuses; +DROP FUNCTION candidate_search_statuses_check_policy(); +DROP TABLE candidate_publications; +DROP INDEX consent_records_id_subject_purpose_key; +DROP FUNCTION candidate_card_fields_are_canonical(text []); diff --git a/backend/db/migrations/00016_bind_registration_consent.sql b/backend/db/migrations/00016_bind_registration_consent.sql new file mode 100644 index 0000000..8caa991 --- /dev/null +++ b/backend/db/migrations/00016_bind_registration_consent.sql @@ -0,0 +1,192 @@ +-- Bind the registration C1 to the registration whose pending credentials are +-- held by its verification token. Older registration code omits this column; +-- the insert trigger below fills it from the account row, which the +-- registration transaction updates before it grants C1. +-- +goose Up +ALTER TABLE consent_records +ADD COLUMN registration_version bigint; + +-- Registration and re-registration delete the earlier registration C1 in +-- the same transaction that advances users.registration_version. The new C1 +-- is granted after that update, so the current account version is the only +-- version an existing registration C1 can belong to. Refuse to guess if a +-- row predates the account's latest registration or its account is missing. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM consent_records AS consent + LEFT JOIN users AS account ON account.id = consent.subject_id + WHERE consent.source = 'registration' + AND consent.purpose = 'c1' + AND ( + account.id IS NULL + OR consent.granted_at < account.last_registered_at + ) + ) THEN + RAISE EXCEPTION 'registration C1 cannot be tied to the current account registration'; + END IF; + IF EXISTS ( + SELECT 1 + FROM consent_records + WHERE source = 'registration' AND purpose = 'c1' + GROUP BY subject_id + HAVING count(*) FILTER (WHERE revoked_at IS NULL) > 1 + ) THEN + RAISE EXCEPTION 'account has more than one current registration C1'; + END IF; +END; +$$; +-- +goose StatementEnd + +-- Consent records are append-only. Temporarily remove the update guard only +-- for this one-time binding, then restore it with the new column protected. +DROP TRIGGER consent_records_refuse_change ON consent_records; + +UPDATE consent_records AS consent +SET registration_version = account.registration_version +FROM users AS account +WHERE + consent.subject_id = account.id + AND consent.source = 'registration' + AND consent.purpose = 'c1'; + +ALTER TABLE consent_records +ADD CONSTRAINT consent_records_registration_version CHECK ( + ( + source = 'registration' + AND purpose = 'c1' + AND registration_version IS NOT NULL + AND registration_version > 0 + ) + OR ( + source <> 'registration' + AND registration_version IS NULL + ) +); + +CREATE UNIQUE INDEX consent_records_registration_version_key +ON consent_records (subject_id, registration_version) +WHERE + source = 'registration' + AND purpose = 'c1' + AND revoked_at IS NULL; + +-- The existing immutable trigger permits only a one-time revocation. It now +-- also protects registration_version from being changed with that stamp. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION consent_records_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.revoked_at IS NOT NULL + OR NEW.revoked_at IS NULL + OR ( + NEW.id, NEW.subject_id, NEW.purpose, NEW.text_version, + NEW.text_hash, NEW.source, NEW.registration_version, + NEW.organization_id, NEW.organization_name, NEW.field_set, + NEW.invitation_id, NEW.invitation_terms_version, NEW.granted_at + ) IS DISTINCT FROM ( + OLD.id, OLD.subject_id, OLD.purpose, OLD.text_version, + OLD.text_hash, OLD.source, OLD.registration_version, + OLD.organization_id, OLD.organization_name, OLD.field_set, + OLD.invitation_id, OLD.invitation_terms_version, OLD.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_records_immutable', + TABLE = 'consent_records', + MESSAGE = 'consent records are append-only: only an unrevoked record can be revoked, once'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_refuse_change +BEFORE UPDATE ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_change(); + +-- Fills the registration version for an older application binary and checks +-- values supplied by the new binary. The registration transaction updates +-- the account before it inserts C1, so this is the current version even when +-- the account row is already locked by that transaction. +-- +goose StatementBegin +CREATE FUNCTION consent_records_bind_registration_version() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + current_version bigint; +BEGIN + IF NEW.source <> 'registration' OR NEW.purpose <> 'c1' THEN + RETURN NEW; + END IF; + + SELECT registration_version + INTO current_version + FROM users + WHERE id = NEW.subject_id; + + IF NOT FOUND THEN + RETURN NEW; + END IF; + + IF NEW.registration_version IS NULL THEN + NEW.registration_version := current_version; + ELSIF NEW.registration_version <> current_version THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'consent_records_registration_version_matches_user', + TABLE = 'consent_records', + MESSAGE = 'registration C1 must match the current account registration'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_bind_registration_version +BEFORE INSERT ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_bind_registration_version(); + +-- +goose Down +DROP TRIGGER consent_records_bind_registration_version ON consent_records; +DROP FUNCTION consent_records_bind_registration_version(); +DROP INDEX consent_records_registration_version_key; +DROP TRIGGER consent_records_refuse_change ON consent_records; + +-- Restore the prior immutability check before removing its column. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION consent_records_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.revoked_at IS NOT NULL + OR NEW.revoked_at IS NULL + OR ( + NEW.id, NEW.subject_id, NEW.purpose, NEW.text_version, + NEW.text_hash, NEW.source, NEW.organization_id, + NEW.organization_name, NEW.field_set, + NEW.invitation_id, NEW.invitation_terms_version, NEW.granted_at + ) IS DISTINCT FROM ( + OLD.id, OLD.subject_id, OLD.purpose, OLD.text_version, + OLD.text_hash, OLD.source, OLD.organization_id, + OLD.organization_name, OLD.field_set, + OLD.invitation_id, OLD.invitation_terms_version, OLD.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'consent_records_immutable', + TABLE = 'consent_records', + MESSAGE = 'consent records are append-only: only an unrevoked record can be revoked, once'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER consent_records_refuse_change +BEFORE UPDATE ON consent_records +FOR EACH ROW EXECUTE FUNCTION consent_records_refuse_change(); + +ALTER TABLE consent_records +DROP CONSTRAINT consent_records_registration_version, +DROP COLUMN registration_version; diff --git a/backend/db/migrations/00017_retry_unknown_mail.sql b/backend/db/migrations/00017_retry_unknown_mail.sql new file mode 100644 index 0000000..3a583e2 --- /dev/null +++ b/backend/db/migrations/00017_retry_unknown_mail.sql @@ -0,0 +1,115 @@ +-- +goose Up +-- Resend may accept a request even when the caller loses the response. Keep +-- that delivery unknown, but schedule bounded retries while its provider key +-- is still inside the deduplication window. An operator decision after the +-- automatic cutoff is append-only and single-use; manual send markers never +-- reset the provider's idempotency window. + +ALTER TABLE deliveries +ADD COLUMN manual_retry_authorized_at timestamptz, +ADD COLUMN manual_retry_started_at timestamptz, +ADD COLUMN send_started_attempt_count integer; + +COMMENT ON COLUMN deliveries.manual_retry_authorized_at IS +'Database time of the latest audited operator authorization to retry a terminal unknown delivery; it does not replace the original send history.'; +COMMENT ON COLUMN deliveries.manual_retry_started_at IS +'Database time when the first provider call of the latest manual authorization started; this is a single-use/recovery marker and never resets the provider deduplication window.'; +COMMENT ON COLUMN deliveries.send_started_attempt_count IS +'Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.'; + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_manual_retry_cycle_complete CHECK ( + manual_retry_started_at IS NULL OR manual_retry_authorized_at IS NOT NULL +); +ALTER TABLE deliveries ADD CONSTRAINT deliveries_send_started_attempt_count_valid CHECK ( + send_started_attempt_count IS NULL + OR (send_started_attempt_count >= 0 AND send_started_attempt_count <= attempt_count) +); + +-- Keep the decision after a delivery or account is deleted. This table holds +-- only an opaque delivery ID, attempt number, operator handle, acknowledgement +-- and decision time; it never stores recipient data or message content. +CREATE TABLE delivery_retry_decisions ( + decision_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + delivery_id uuid NOT NULL, + attempt_count integer NOT NULL CHECK (attempt_count > 0), + actor text NOT NULL CHECK ( + length(actor) <= 128 + AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ), + duplicate_risk_acknowledged boolean NOT NULL CHECK (duplicate_risk_acknowledged), + previous_lease_expired boolean NOT NULL, + decided_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE INDEX delivery_retry_decisions_delivery_idx +ON delivery_retry_decisions (delivery_id, decision_id); + +COMMENT ON TABLE delivery_retry_decisions IS +'Append-only record of an operator decision to retry a terminal unknown mail delivery after its provider deduplication window. No foreign key so history survives account deletion.'; +COMMENT ON COLUMN delivery_retry_decisions.delivery_id IS +'Opaque ID of the delivery whose current unknown attempt was authorized for another send cycle.'; +COMMENT ON COLUMN delivery_retry_decisions.actor IS +'Operator handle in the form operator:; never an email address or credential.'; +COMMENT ON COLUMN delivery_retry_decisions.duplicate_risk_acknowledged IS +'Must be true: after the provider key expires, reusing it does not guarantee deduplication.'; +COMMENT ON COLUMN delivery_retry_decisions.previous_lease_expired IS +'True when this decision also cleared an expired worker lease after a manual send began but its result was not recorded.'; + +-- +goose StatementBegin +CREATE FUNCTION delivery_retry_decisions_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'delivery_retry_decisions_immutable', + TABLE = 'delivery_retry_decisions', + MESSAGE = 'mail retry decisions are append-only'; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'delivery_retry_decisions_immutable', + TABLE = 'delivery_retry_decisions', + MESSAGE = 'mail retry decisions are append-only'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER delivery_retry_decisions_refuse_update_delete +BEFORE UPDATE OR DELETE ON delivery_retry_decisions +FOR EACH ROW EXECUTE FUNCTION delivery_retry_decisions_refuse_change(); + +CREATE TRIGGER delivery_retry_decisions_refuse_truncate +BEFORE TRUNCATE ON delivery_retry_decisions +FOR EACH STATEMENT EXECUTE FUNCTION delivery_retry_decisions_refuse_change(); + +-- A due unknown row is claimable only when the retry policy gave it a due +-- time. Keep the worker's single indexed queue broad enough for all due +-- service-mail statuses. +DROP INDEX deliveries_due_idx; +CREATE INDEX deliveries_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota', 'unknown') + AND next_attempt_at IS NOT NULL + AND kind IN ('verification', 'password_reset'); + +-- +goose Down +-- Rolling back this migration removes its append-only operator decision +-- history. Export or preserve that audit data before an intentional rollback. +DROP INDEX deliveries_due_idx; +CREATE INDEX deliveries_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota') + AND next_attempt_at IS NOT NULL + AND kind IN ('verification', 'password_reset'); + +DROP TRIGGER delivery_retry_decisions_refuse_update_delete ON delivery_retry_decisions; +DROP TRIGGER delivery_retry_decisions_refuse_truncate ON delivery_retry_decisions; +DROP FUNCTION delivery_retry_decisions_refuse_change(); +DROP INDEX delivery_retry_decisions_delivery_idx; +DROP TABLE delivery_retry_decisions; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_manual_retry_cycle_complete; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_send_started_attempt_count_valid; +ALTER TABLE deliveries DROP COLUMN send_started_attempt_count, DROP COLUMN manual_retry_started_at, DROP COLUMN manual_retry_authorized_at; diff --git a/backend/db/migrations/00018_create_account_deletion_requests.sql b/backend/db/migrations/00018_create_account_deletion_requests.sql new file mode 100644 index 0000000..d993021 --- /dev/null +++ b/backend/db/migrations/00018_create_account_deletion_requests.sql @@ -0,0 +1,37 @@ +-- A C1 revocation creates a durable request for the account-deletion workflow. +-- The API records the request and its outbox intent atomically; processing and +-- deleting the account are separate operations. +-- +goose Up +CREATE TABLE account_deletion_requests ( + id uuid NOT NULL, + subject_id uuid, + status text NOT NULL, + requested_at timestamptz NOT NULL, + completed_at timestamptz, + CONSTRAINT account_deletion_requests_pkey PRIMARY KEY (id), + CONSTRAINT account_deletion_requests_subject_id_fkey FOREIGN KEY (subject_id) + REFERENCES users (id) ON DELETE SET NULL, + CONSTRAINT account_deletion_requests_status_known CHECK ( + status IN ('requested', 'processing', 'completed') + ), + CONSTRAINT account_deletion_requests_state_shape CHECK ( + (status = 'completed') = (completed_at IS NOT NULL) + ), + CONSTRAINT account_deletion_requests_subject_retained_until_complete CHECK ( + subject_id IS NOT NULL OR status = 'completed' + ), + CONSTRAINT account_deletion_requests_completed_after_request CHECK ( + completed_at IS NULL OR completed_at >= requested_at + ) +); + +CREATE UNIQUE INDEX account_deletion_requests_one_active_per_subject +ON account_deletion_requests (subject_id) +WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing'); + +CREATE INDEX account_deletion_requests_processing_idx +ON account_deletion_requests (requested_at, id) +WHERE status IN ('requested', 'processing'); + +-- +goose Down +DROP TABLE account_deletion_requests; diff --git a/backend/db/migrations/00019_create_organization_creation_results.sql b/backend/db/migrations/00019_create_organization_creation_results.sql new file mode 100644 index 0000000..69aeaf8 --- /dev/null +++ b/backend/db/migrations/00019_create_organization_creation_results.sql @@ -0,0 +1,25 @@ +-- +goose Up +-- Replay follows the generic record's 24-hour retention. Expired records are +-- removed by bounded opportunistic purges, so physical deletion may happen +-- later; this foreign key removes the snapshot with its record. The snapshot +-- is separate from the live organization so later profile edits cannot change +-- a replay. It contains bounded profile and owner-membership data, never a +-- request key. +CREATE TABLE organization_creation_results ( + scope_hash bytea NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT organization_creation_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT organization_creation_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT organization_creation_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT organization_creation_results_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 65536 + ) +); + +-- +goose Down +DROP TABLE organization_creation_results; diff --git a/backend/db/migrations/00020_create_candidate_profile_history.sql b/backend/db/migrations/00020_create_candidate_profile_history.sql new file mode 100644 index 0000000..202b973 --- /dev/null +++ b/backend/db/migrations/00020_create_candidate_profile_history.sql @@ -0,0 +1,74 @@ +-- +goose Up +-- Each row in candidate_profile_overlap_confirmations represents the +-- candidate's acknowledgement of one exact pair of periods in the current +-- profile. Replacing a profile replaces these rows in the same transaction. +CREATE TABLE candidate_profile_overlap_confirmations ( + user_id uuid NOT NULL, + first_index smallint NOT NULL, + second_index smallint NOT NULL, + first_started_on text NOT NULL, + first_ended_on text, + second_started_on text NOT NULL, + second_ended_on text, + CONSTRAINT candidate_profile_overlap_confirmations_pkey PRIMARY KEY ( + user_id, first_index, second_index + ), + CONSTRAINT candidate_profile_overlap_confirmations_profile_fkey FOREIGN KEY ( + user_id + ) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE, + CONSTRAINT candidate_profile_overlap_confirmations_indices CHECK ( + first_index BETWEEN 0 AND 18 + AND second_index > first_index + AND second_index BETWEEN 1 AND 19 + ), + CONSTRAINT candidate_profile_overlap_confirmations_months CHECK ( + first_started_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$' + AND (first_ended_on IS NULL OR first_ended_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$') + AND second_started_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$' + AND (second_ended_on IS NULL OR second_ended_on ~ '^[0-9]{4}-(0[1-9]|1[0-2])$') + AND (first_ended_on IS NULL OR first_ended_on >= first_started_on) + AND (second_ended_on IS NULL OR second_ended_on >= second_started_on) + AND (first_ended_on IS NULL OR second_started_on <= first_ended_on) + AND (second_ended_on IS NULL OR first_started_on <= second_ended_on) + ) +); + +-- The snapshots are private, append-only application records of every +-- changed profile version. They go with the owning account and have no +-- automatic retention limit. Each individual snapshot is bounded by the +-- complete public profile schema. +CREATE TABLE candidate_profile_history ( + user_id uuid NOT NULL, + version bigint NOT NULL, + changed_at timestamptz NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT candidate_profile_history_pkey PRIMARY KEY (user_id, version), + CONSTRAINT candidate_profile_history_profile_fkey FOREIGN KEY ( + user_id + ) REFERENCES candidate_profiles (user_id) ON DELETE CASCADE, + CONSTRAINT candidate_profile_history_version_positive CHECK (version > 0), + CONSTRAINT candidate_profile_history_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 262144 + ) +); + +-- +goose StatementBegin +CREATE FUNCTION reject_candidate_profile_history_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'candidate profile history does not allow updates' + USING ERRCODE = 'integrity_constraint_violation'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_profile_history_no_update +BEFORE UPDATE ON candidate_profile_history +FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_history_update(); + +-- +goose Down +DROP TRIGGER candidate_profile_history_no_update ON candidate_profile_history; +DROP FUNCTION reject_candidate_profile_history_update(); +DROP TABLE candidate_profile_history; +DROP TABLE candidate_profile_overlap_confirmations; diff --git a/backend/db/migrations/00021_create_candidate_questionnaires.sql b/backend/db/migrations/00021_create_candidate_questionnaires.sql new file mode 100644 index 0000000..1fef013 --- /dev/null +++ b/backend/db/migrations/00021_create_candidate_questionnaires.sql @@ -0,0 +1,228 @@ +-- +goose Up +-- Candidate questionnaire answers and reviewed assessment catalog bindings. +-- Questionnaire values are private, self-reported data; they never contain +-- a confirmed grade or category. + +-- The same small array checks are used by the contract tables below. Null +-- elements are refused because COUNT(DISTINCT ...) excludes them. +-- +goose StatementBegin +CREATE FUNCTION candidate_questionnaire_unique_text_array(input_values text[]) RETURNS boolean +LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$ + SELECT cardinality(input_values) = count(DISTINCT value) + FROM unnest(input_values) AS values_list(value) +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE FUNCTION candidate_questionnaire_unique_lower_text_array(input_values text[]) RETURNS boolean +LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$ + SELECT cardinality(input_values) = count(DISTINCT lower(value)) + FROM unnest(input_values) AS values_list(value) +$$; +-- +goose StatementEnd + +-- The aggregate row owns the optimistic-concurrency version and work context. +CREATE TABLE candidate_questionnaires ( + user_id uuid NOT NULL, + version bigint NOT NULL, + work_formats text[] NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_questionnaires_pkey PRIMARY KEY (user_id), + CONSTRAINT candidate_questionnaires_user_fkey FOREIGN KEY (user_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_questionnaires_version_positive CHECK (version > 0), + CONSTRAINT candidate_questionnaires_work_formats CHECK ( + cardinality(work_formats) BETWEEN 1 AND 3 + AND work_formats <@ ARRAY['remote', 'office', 'hybrid']::text[] + AND candidate_questionnaire_unique_text_array(work_formats) + ), + CONSTRAINT candidate_questionnaires_times_ordered CHECK (updated_at >= created_at) +); + +-- Stores the unique, ordered specialization answers separately from the +-- candidate's assessment result and confirmed category. +CREATE TABLE candidate_questionnaire_specializations ( + user_id uuid NOT NULL, + ordinal smallint NOT NULL, + specialization text NOT NULL, + self_assessed_grade text NOT NULL, + task_languages text[] NOT NULL, + stack text[] NOT NULL, + commercial_months integer, + academic_months integer, + CONSTRAINT candidate_questionnaire_specializations_pkey PRIMARY KEY (user_id, ordinal), + CONSTRAINT candidate_questionnaire_specializations_user_fkey FOREIGN KEY (user_id) + REFERENCES candidate_questionnaires (user_id) ON DELETE CASCADE, + CONSTRAINT candidate_questionnaire_specializations_unique_code UNIQUE (user_id, specialization), + CONSTRAINT candidate_questionnaire_specializations_ordinal CHECK (ordinal BETWEEN 0 AND 1), + CONSTRAINT candidate_questionnaire_specializations_code CHECK ( + specialization IN ( + 'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa' + ) + ), + CONSTRAINT candidate_questionnaire_specializations_grade CHECK ( + self_assessed_grade IN ('intern', 'junior', 'middle', 'senior') + ), + CONSTRAINT candidate_questionnaire_specializations_languages CHECK ( + cardinality(task_languages) <= 2 + AND task_languages <@ ARRAY['python', 'go']::text[] + AND candidate_questionnaire_unique_text_array(task_languages) + ), + CONSTRAINT candidate_questionnaire_specializations_stack CHECK ( + cardinality(stack) <= 20 + AND candidate_questionnaire_unique_lower_text_array(stack) + ), + CONSTRAINT candidate_questionnaire_specializations_experience CHECK ( + (commercial_months IS NULL AND academic_months IS NULL) + OR ( + commercial_months IS NOT NULL + AND academic_months IS NOT NULL + AND commercial_months BETWEEN 0 AND 600 + AND academic_months BETWEEN 0 AND 600 + ) + ) +); + +-- A catalog binding is an explicit operator-reviewed mapping for one immutable +-- opening. The fingerprint pins it to the exact published family set present +-- when the opening is made. Legacy openings have no row and stay unavailable +-- in the public catalog. +CREATE TABLE assessment_category_catalog_bindings ( + opening_id uuid NOT NULL, + specialization text NOT NULL, + grade text NOT NULL, + task_languages text[] NOT NULL, + published_manifest_sha256 bytea NOT NULL, + reviewed_by text NOT NULL, + reviewed_at timestamptz NOT NULL, + CONSTRAINT assessment_category_catalog_bindings_pkey PRIMARY KEY (opening_id), + CONSTRAINT assessment_category_catalog_bindings_opening_fkey FOREIGN KEY (opening_id) + REFERENCES assessment_category_openings (id), + CONSTRAINT assessment_category_catalog_bindings_specialization CHECK ( + specialization IN ( + 'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa' + ) + ), + CONSTRAINT assessment_category_catalog_bindings_grade CHECK ( + grade IN ('intern', 'junior', 'middle', 'senior') + ), + CONSTRAINT assessment_category_catalog_bindings_languages CHECK ( + cardinality(task_languages) <= 2 + AND task_languages <@ ARRAY['python', 'go']::text[] + AND candidate_questionnaire_unique_text_array(task_languages) + ), + CONSTRAINT assessment_category_catalog_bindings_manifest_hash CHECK ( + octet_length(published_manifest_sha256) = 32 + ), + CONSTRAINT assessment_category_catalog_bindings_reviewer CHECK ( + char_length(reviewed_by) <= 128 + AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) +); + +-- Openings and published families are already immutable. Refuse a catalog +-- mapping unless it names the current opening and the full reviewed bank still +-- meets that opening's coverage and policy requirements. +-- +goose StatementBegin +CREATE FUNCTION assessment_category_catalog_bindings_validate() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + opening assessment_category_openings%ROWTYPE; + current_policy_id uuid; + published_count integer; +BEGIN + SELECT * INTO opening + FROM assessment_category_openings AS candidate + WHERE candidate.id = NEW.opening_id; + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = 'foreign_key_violation', + CONSTRAINT = 'assessment_category_catalog_bindings_opening', + TABLE = 'assessment_category_catalog_bindings', + MESSAGE = 'catalog binding references an unknown opening'; + END IF; + IF opening.opened_by <> NEW.reviewed_by THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'assessment_category_catalog_bindings_reviewer', + TABLE = 'assessment_category_catalog_bindings', + MESSAGE = 'catalog binding reviewer must match the category opener'; + END IF; + IF EXISTS ( + SELECT 1 + FROM assessment_category_openings AS newer + WHERE newer.category = opening.category + AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'assessment_category_catalog_bindings_current_opening', + TABLE = 'assessment_category_catalog_bindings', + MESSAGE = 'catalog binding must reference the current opening'; + END IF; + SELECT policy.id INTO current_policy_id + FROM policy_versions AS policy + WHERE policy.policy_key = 'product' AND policy.effective_at <= clock_timestamp() + ORDER BY policy.version DESC + LIMIT 1; + IF current_policy_id IS DISTINCT FROM opening.policy_version_id THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'assessment_category_catalog_bindings_policy_current', + TABLE = 'assessment_category_catalog_bindings', + MESSAGE = 'catalog binding opening does not use the current policy'; + END IF; + SELECT count(DISTINCT family.family_key)::integer INTO published_count + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published'; + IF published_count < opening.required_families THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', + CONSTRAINT = 'assessment_category_catalog_bindings_coverage', + TABLE = 'assessment_category_catalog_bindings', + MESSAGE = 'catalog binding bank no longer meets its opening coverage'; + END IF; + NEW.reviewed_at := clock_timestamp(); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_category_catalog_bindings_validate +BEFORE INSERT ON assessment_category_catalog_bindings +FOR EACH ROW EXECUTE FUNCTION assessment_category_catalog_bindings_validate(); + +-- A binding is an immutable review decision. It is replaced only by a new +-- opening and a new binding, never edited in place. +-- +goose StatementBegin +CREATE FUNCTION assessment_category_catalog_bindings_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_category_catalog_bindings_immutable', + TABLE = 'assessment_category_catalog_bindings', + MESSAGE = 'catalog bindings are immutable: create a new category opening'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_category_catalog_bindings_refuse_update_delete +BEFORE UPDATE OR DELETE ON assessment_category_catalog_bindings +FOR EACH ROW EXECUTE FUNCTION assessment_category_catalog_bindings_refuse_change(); + +CREATE TRIGGER assessment_category_catalog_bindings_refuse_truncate +BEFORE TRUNCATE ON assessment_category_catalog_bindings +FOR EACH STATEMENT EXECUTE FUNCTION assessment_category_catalog_bindings_refuse_change(); + +-- +goose Down +DROP TABLE assessment_category_catalog_bindings; +DROP FUNCTION assessment_category_catalog_bindings_refuse_change(); +DROP FUNCTION assessment_category_catalog_bindings_validate(); +DROP TABLE candidate_questionnaire_specializations; +DROP TABLE candidate_questionnaires; +DROP FUNCTION candidate_questionnaire_unique_lower_text_array(text[]); +DROP FUNCTION candidate_questionnaire_unique_text_array(text[]); diff --git a/backend/db/migrations/00022_create_company_quota_usage.sql b/backend/db/migrations/00022_create_company_quota_usage.sql new file mode 100644 index 0000000..a9a0ad1 --- /dev/null +++ b/backend/db/migrations/00022_create_company_quota_usage.sql @@ -0,0 +1,106 @@ +-- +goose Up +-- Invitation usage remains keyed by its stable invitation ID for the +-- organization's lifetime, so a retry cannot count it again after the +-- rolling window. The policy and trust columns record the basis of the +-- original reservation. +CREATE TABLE company_invitation_quota_usage ( + organization_id uuid NOT NULL, + invitation_id uuid NOT NULL, + reserved_at timestamptz NOT NULL, + policy_version_id uuid NOT NULL, + verification_level text NOT NULL, + verification_basis text NOT NULL, + verification_changed_at timestamptz NOT NULL, + quota_tier text NOT NULL, + CONSTRAINT company_invitation_quota_usage_pkey PRIMARY KEY ( + organization_id, invitation_id + ), + CONSTRAINT company_invitation_quota_usage_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE CASCADE, + CONSTRAINT company_invitation_quota_usage_policy_version_id_fkey FOREIGN KEY ( + policy_version_id + ) REFERENCES policy_versions (id) ON DELETE RESTRICT, + CONSTRAINT company_invitation_quota_usage_verification_evidence CHECK ( + ( + verification_level = 'e0' + AND verification_basis = 'confirmed_email' + ) OR ( + verification_level = 'e1' + AND verification_basis = 'corporate_domain' + ) OR ( + verification_level = 'e2' + AND verification_basis = 'requisites_and_authority' + ) + ), + CONSTRAINT company_invitation_quota_usage_tier_known CHECK ( + quota_tier IN ('e0', 'e1', 'e2') + ), + CONSTRAINT company_invitation_quota_usage_tier_matches_verification CHECK ( + quota_tier = verification_level + ), + CONSTRAINT company_invitation_quota_usage_verification_not_future CHECK ( + verification_changed_at <= reserved_at + ) +); + +CREATE INDEX company_invitation_quota_usage_window_idx +ON company_invitation_quota_usage (organization_id, reserved_at, invitation_id); + +-- Card-view rows are a rolling-window counter, not a full access history. +-- Repeats update last_seen_at; expired rows may be deleted in bounded batches +-- only after a successful reservation. This is logical window expiry, not a +-- promise of deletion at an exact wall-clock time. +CREATE TABLE company_card_view_quota_usage ( + organization_id uuid NOT NULL, + candidate_id uuid NOT NULL, + last_seen_at timestamptz NOT NULL, + policy_version_id uuid NOT NULL, + verification_level text NOT NULL, + verification_basis text NOT NULL, + verification_changed_at timestamptz NOT NULL, + quota_tier text NOT NULL, + CONSTRAINT company_card_view_quota_usage_pkey PRIMARY KEY ( + organization_id, candidate_id + ), + CONSTRAINT company_card_view_quota_usage_organization_id_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE CASCADE, + CONSTRAINT company_card_view_quota_usage_candidate_id_fkey FOREIGN KEY ( + candidate_id + ) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT company_card_view_quota_usage_policy_version_id_fkey FOREIGN KEY ( + policy_version_id + ) REFERENCES policy_versions (id) ON DELETE RESTRICT, + CONSTRAINT company_card_view_quota_usage_verification_evidence CHECK ( + ( + verification_level = 'e0' + AND verification_basis = 'confirmed_email' + ) OR ( + verification_level = 'e1' + AND verification_basis = 'corporate_domain' + ) OR ( + verification_level = 'e2' + AND verification_basis = 'requisites_and_authority' + ) + ), + CONSTRAINT company_card_view_quota_usage_tier_known CHECK ( + quota_tier IN ('e0', 'e1', 'e2') + ), + CONSTRAINT company_card_view_quota_usage_tier_matches_verification CHECK ( + quota_tier = verification_level + ), + CONSTRAINT company_card_view_quota_usage_verification_not_future CHECK ( + verification_changed_at <= last_seen_at + ) +); + +CREATE INDEX company_card_view_quota_usage_window_idx +ON company_card_view_quota_usage (organization_id, last_seen_at, candidate_id); + +CREATE INDEX company_card_view_quota_usage_candidate_idx +ON company_card_view_quota_usage (candidate_id); + +-- +goose Down +DROP TABLE company_card_view_quota_usage; +DROP TABLE company_invitation_quota_usage; diff --git a/backend/db/migrations/00023_create_organization_needs.sql b/backend/db/migrations/00023_create_organization_needs.sql new file mode 100644 index 0000000..4392c00 --- /dev/null +++ b/backend/db/migrations/00023_create_organization_needs.sql @@ -0,0 +1,98 @@ +-- +goose Up +-- Organization needs keep a current version pointer and one bounded, +-- immutable JSON snapshot for every committed version. Readiness and +-- recommendations are derived from requirements and are not frozen here. +CREATE TABLE organization_needs ( + id uuid NOT NULL, + organization_id uuid NOT NULL, + current_version bigint NOT NULL, + requirements_version bigint NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT organization_needs_pkey PRIMARY KEY (id), + CONSTRAINT organization_needs_organization_id_id_key UNIQUE (organization_id, id), + CONSTRAINT organization_needs_organization_fkey FOREIGN KEY (organization_id) + REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT organization_needs_current_version_positive CHECK (current_version > 0), + CONSTRAINT organization_needs_requirements_version CHECK ( + requirements_version > 0 AND requirements_version <= current_version + ), + CONSTRAINT organization_needs_timestamps CHECK (updated_at >= created_at) +); + +-- Every version is tied to its organization-scoped need identity. The full +-- public requirement data and provenance fit under the 256 KiB snapshot cap; +-- the source text itself is bounded by the contract at 10,000 characters. +CREATE TABLE organization_need_versions ( + organization_id uuid NOT NULL, + need_id uuid NOT NULL, + version bigint NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT organization_need_versions_pkey PRIMARY KEY (organization_id, need_id, version), + CONSTRAINT organization_need_versions_need_fkey FOREIGN KEY (organization_id, need_id) + REFERENCES organization_needs (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT organization_need_versions_version_positive CHECK (version > 0), + CONSTRAINT organization_need_versions_snapshot_shape CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version'] + AND jsonb_typeof(snapshot -> 'id') = 'string' + AND snapshot ->> 'id' = need_id::text + AND jsonb_typeof(snapshot -> 'organization_id') = 'string' + AND snapshot ->> 'organization_id' = organization_id::text + AND jsonb_typeof(snapshot -> 'version') = 'number' + AND snapshot ->> 'version' = version::text + AND jsonb_typeof(snapshot -> 'requirements_version') = 'number' + AND CASE + WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$' + THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version + ELSE FALSE + END + AND octet_length(snapshot::text) <= 262144 + ) +); + +-- The current and requirements versions must both name snapshots belonging +-- to this same organization and need. Deferral lets creation insert the +-- parent and version 1 in one transaction. +ALTER TABLE organization_needs + ADD CONSTRAINT organization_needs_current_snapshot_fkey + FOREIGN KEY (organization_id, id, current_version) + REFERENCES organization_need_versions (organization_id, need_id, version) + DEFERRABLE INITIALLY DEFERRED, + ADD CONSTRAINT organization_needs_requirements_snapshot_fkey + FOREIGN KEY (organization_id, id, requirements_version) + REFERENCES organization_need_versions (organization_id, need_id, version) + DEFERRABLE INITIALLY DEFERRED; + +-- Application writes append versions only. Old snapshots remain available +-- for future history reads and cannot be edited or deleted by ordinary SQL. +-- TRUNCATE remains available to reset isolated integration databases. +-- +goose StatementBegin +CREATE FUNCTION reject_organization_need_version_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'organization_need_versions_immutable', + TABLE = 'organization_need_versions', + MESSAGE = 'need versions are immutable: append a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER organization_need_versions_immutable +BEFORE UPDATE OR DELETE ON organization_need_versions +FOR EACH ROW EXECUTE FUNCTION reject_organization_need_version_change(); + +CREATE INDEX organization_needs_org_created_idx +ON organization_needs (organization_id, created_at DESC, id DESC); + +-- +goose Down +DROP INDEX organization_needs_org_created_idx; +DROP TRIGGER organization_need_versions_immutable ON organization_need_versions; +DROP FUNCTION reject_organization_need_version_change(); +ALTER TABLE organization_needs + DROP CONSTRAINT organization_needs_requirements_snapshot_fkey, + DROP CONSTRAINT organization_needs_current_snapshot_fkey; +DROP TABLE organization_need_versions; +DROP TABLE organization_needs; diff --git a/backend/db/migrations/00024_create_assessment_attempts.sql b/backend/db/migrations/00024_create_assessment_attempts.sql new file mode 100644 index 0000000..fe719be --- /dev/null +++ b/backend/db/migrations/00024_create_assessment_attempts.sql @@ -0,0 +1,719 @@ +-- +goose Up +-- Assessment attempts pin their product policy, category opening or separate +-- training source, and generated item variants. Candidate answers are stored +-- separately from the immutable variant and never appear in idempotency rows. + +CREATE TABLE assessment_training_bank_bindings ( + id uuid NOT NULL, + category text NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + item_count integer NOT NULL, + manifest_sha256 bytea NOT NULL, + family_manifest jsonb NOT NULL, + reviewed_by text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT assessment_training_bank_bindings_pkey PRIMARY KEY (id), + CONSTRAINT assessment_training_bank_bindings_policy_manifest_key UNIQUE ( + category, product_policy_version_id, manifest_sha256 + ), + CONSTRAINT assessment_training_bank_bindings_category_format CHECK ( + category ~ '^[a-z][a-z0-9-]{1,47}$' + ), + CONSTRAINT assessment_training_bank_bindings_item_count CHECK ( + item_count BETWEEN 1 AND 20 + ), + CONSTRAINT assessment_training_bank_bindings_manifest_hash CHECK ( + octet_length(manifest_sha256) = 32 + ), + CONSTRAINT assessment_training_bank_bindings_manifest_object CHECK ( + jsonb_typeof(family_manifest) = 'array' + ), + CONSTRAINT assessment_training_bank_bindings_reviewer CHECK ( + char_length(reviewed_by) <= 128 + AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) +); + +CREATE TABLE assessment_training_bank_binding_families ( + binding_id uuid NOT NULL REFERENCES assessment_training_bank_bindings (id), + ordinal integer NOT NULL, + family_id uuid NOT NULL REFERENCES assessment_families (id), + family_key text NOT NULL, + family_version integer NOT NULL, + content_sha256 bytea NOT NULL, + CONSTRAINT assessment_training_bank_binding_families_pkey PRIMARY KEY (binding_id, ordinal), + CONSTRAINT assessment_training_bank_binding_families_family_key UNIQUE (binding_id, family_key), + CONSTRAINT assessment_training_bank_binding_families_ordinal CHECK (ordinal > 0), + CONSTRAINT assessment_training_bank_binding_families_version CHECK (family_version > 0), + CONSTRAINT assessment_training_bank_binding_families_hash CHECK (octet_length(content_sha256) = 32) +); + +-- A binding is accepted only for an explicit training policy and a category +-- not already opened for real assessments. The category advisory lock is the +-- same lock taken by the bank's publish, retire, and opening operations. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + policy_item_count integer; + current_product_policy_id uuid; +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || NEW.category, 0) + ); + + SELECT (document #>> '{assessment,training,demo_express_item_count}')::integer + INTO policy_item_count + FROM policy_versions + WHERE id = NEW.product_policy_version_id + AND policy_key = 'product'; + + IF policy_item_count IS NULL OR policy_item_count <> NEW.item_count THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_policy', + MESSAGE = 'training binding does not match explicit product policy'; + END IF; + + SELECT id INTO current_product_policy_id + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= clock_timestamp() + ORDER BY version DESC + LIMIT 1; + IF current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_current_policy', + MESSAGE = 'training binding must pin the current product policy'; + END IF; + + IF EXISTS ( + SELECT 1 FROM assessment_category_openings WHERE category = NEW.category + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint', + MESSAGE = 'training category already has a real opening'; + END IF; + + NEW.created_at := clock_timestamp(); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_training_binding_guard +BEFORE INSERT ON assessment_training_bank_bindings +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_guard(); + +-- A real opening cannot consume a category reserved for training. Taking the +-- same lock in both directions closes the race between binding and opening. +-- +goose StatementBegin +CREATE FUNCTION assessment_real_opening_rejects_training_category() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || NEW.category, 0) + ); + + IF EXISTS ( + SELECT 1 FROM assessment_training_bank_bindings WHERE category = NEW.category + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint', + MESSAGE = 'real opening cannot use a training category'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_real_opening_rejects_training_category +BEFORE INSERT ON assessment_category_openings +FOR EACH ROW EXECUTE FUNCTION assessment_real_opening_rejects_training_category(); + +-- Each pinned training family must be reviewed, published, and in the +-- category reserved by its binding. No family row can later be replaced. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_family_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + binding assessment_training_bank_bindings%ROWTYPE; + family assessment_families%ROWTYPE; +BEGIN + SELECT * INTO STRICT binding + FROM assessment_training_bank_bindings + WHERE id = NEW.binding_id; + + SELECT * INTO STRICT family + FROM assessment_families + WHERE id = NEW.family_id; + + IF family.category <> binding.category OR family.family_key <> NEW.family_key OR + family.version <> NEW.family_version OR family.content_sha256 <> NEW.content_sha256 OR + family.lifecycle <> 'published' OR family.review_status <> 'approved' OR + family.reviewer IS NULL OR family.author = family.reviewer THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_family_reviewed', + MESSAGE = 'training family is not an approved published member of the binding'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_training_binding_family_guard +BEFORE INSERT ON assessment_training_bank_binding_families +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_guard(); + +-- The family rows and canonical manifest must agree when the transaction +-- commits; inserts may arrive after the binding header in the same unit. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_complete() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + binding_id_value uuid; +BEGIN + binding_id_value := NEW.id; + PERFORM assessment_training_binding_assert_complete(binding_id_value); + + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_assert_complete(binding_id_value uuid) RETURNS void +LANGUAGE plpgsql AS $$ +DECLARE + expected_count integer; + actual_count integer; + actual_manifest jsonb; + family_manifest_value jsonb; +BEGIN + SELECT item_count, family_manifest INTO expected_count, family_manifest_value + FROM assessment_training_bank_bindings + WHERE id = binding_id_value; + + SELECT count(*)::integer INTO actual_count + FROM assessment_training_bank_binding_families + WHERE binding_id = binding_id_value; + + IF actual_count <> expected_count OR jsonb_array_length(family_manifest_value) <> expected_count THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_complete', + MESSAGE = 'training binding family count is incomplete'; + END IF; + + SELECT COALESCE(jsonb_agg( + jsonb_build_object( + 'family_key', family_key, + 'version', family_version, + 'content_sha256', encode(content_sha256, 'hex') + ) ORDER BY family_key, family_version + ), '[]'::jsonb) INTO actual_manifest + FROM assessment_training_bank_binding_families + WHERE binding_id = binding_id_value; + + IF actual_manifest <> family_manifest_value THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_manifest', + MESSAGE = 'training binding manifest does not match its families'; + END IF; +END; +$$; +-- +goose StatementEnd + +-- The deferred child trigger prevents an extra family from being appended +-- after the header's own deferred completeness check was queued. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_family_complete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM assessment_training_binding_assert_complete(NEW.binding_id); + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER assessment_training_binding_complete +AFTER INSERT ON assessment_training_bank_bindings +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_complete(); + +CREATE CONSTRAINT TRIGGER assessment_training_binding_family_complete +AFTER INSERT ON assessment_training_bank_binding_families +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_complete(); + +-- Bindings and their family manifest are immutable once stored. +-- +goose StatementBegin +CREATE FUNCTION assessment_training_binding_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_training_binding_immutable', + MESSAGE = 'training bank bindings are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_training_binding_refuse_update_delete +BEFORE UPDATE OR DELETE ON assessment_training_bank_bindings +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change(); + +CREATE TRIGGER assessment_training_binding_family_refuse_update_delete +BEFORE UPDATE OR DELETE ON assessment_training_bank_binding_families +FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change(); + +CREATE TABLE assessment_attempts ( + id uuid NOT NULL, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + kind text NOT NULL, + mode text NOT NULL, + state text NOT NULL, + outcome text, + bank_category text NOT NULL, + specialization text, + target_grade text, + task_language text, + root_attempt_id uuid NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + grading_policy_version_id uuid REFERENCES policy_versions (id), + opening_id uuid REFERENCES assessment_category_openings (id), + opening_manifest_sha256 bytea, + training_binding_id uuid REFERENCES assessment_training_bank_bindings (id), + training_manifest_sha256 bytea, + bank_version text NOT NULL, + algorithm_version text NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + expires_at timestamptz NOT NULL, + chain_deadline timestamptz, + idle_timeout_seconds integer NOT NULL, + max_sessions integer NOT NULL, + sessions_used integer NOT NULL, + session_started_at timestamptz NOT NULL, + last_activity_at timestamptz NOT NULL, + version bigint NOT NULL, + ended_at timestamptz, + CONSTRAINT assessment_attempts_pkey PRIMARY KEY (id), + CONSTRAINT assessment_attempts_id_owner_key UNIQUE (id, user_id), + CONSTRAINT assessment_attempts_owner_root_fk FOREIGN KEY (root_attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) DEFERRABLE INITIALLY DEFERRED, + CONSTRAINT assessment_attempts_kind CHECK (kind IN ('root', 'corrective', 'demo_express')), + CONSTRAINT assessment_attempts_mode CHECK (mode IN ('demo_basic', 'adaptive', 'demo_express')), + CONSTRAINT assessment_attempts_state CHECK ( + state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize', + 'completed', 'expired', 'insufficient_bank') + ), + CONSTRAINT assessment_attempts_outcome CHECK ( + outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined') + ), + CONSTRAINT assessment_attempts_track CHECK ( + ( + kind IN ('root', 'corrective') + AND mode IN ('demo_basic', 'adaptive') + AND specialization IS NOT NULL + AND specialization ~ '^[a-z][a-z0-9_-]{1,47}$' + AND target_grade IS NOT NULL + AND target_grade IN ('intern', 'junior', 'middle', 'senior') + AND (task_language IS NULL OR task_language IN ('go', 'python')) + AND grading_policy_version_id IS NOT NULL + AND opening_id IS NOT NULL + AND opening_manifest_sha256 IS NOT NULL + AND octet_length(opening_manifest_sha256) = 32 + AND training_binding_id IS NULL + AND training_manifest_sha256 IS NULL + AND chain_deadline IS NOT NULL + AND ( + (kind = 'root' AND root_attempt_id = id) + OR (kind = 'corrective' AND root_attempt_id <> id) + ) + ) OR ( + kind = 'demo_express' + AND mode = 'demo_express' + AND specialization IS NULL AND target_grade IS NULL AND task_language IS NULL + AND root_attempt_id = id + AND grading_policy_version_id IS NULL + AND opening_id IS NULL AND opening_manifest_sha256 IS NULL + AND training_binding_id IS NOT NULL + AND training_manifest_sha256 IS NOT NULL + AND octet_length(training_manifest_sha256) = 32 + AND chain_deadline IS NULL + ) + ), + CONSTRAINT assessment_attempts_policy_version_positive CHECK (product_policy_version > 0), + CONSTRAINT assessment_attempts_version_positive CHECK (version > 0), + CONSTRAINT assessment_attempts_session_limits CHECK ( + idle_timeout_seconds BETWEEN 60 AND 86400 + AND max_sessions BETWEEN 1 AND 10 + AND sessions_used BETWEEN 1 AND max_sessions + ), + CONSTRAINT assessment_attempts_timestamps CHECK ( + created_at <= updated_at + AND created_at <= session_started_at + AND session_started_at <= last_activity_at + AND last_activity_at <= updated_at + AND expires_at > created_at + AND (chain_deadline IS NULL OR (chain_deadline > created_at AND expires_at <= chain_deadline)) + AND (ended_at IS NULL OR (ended_at >= created_at AND ended_at >= last_activity_at AND ended_at <= updated_at)) + ), + CONSTRAINT assessment_attempts_state_stamp CHECK ( + (state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') + AND outcome IS NULL AND ended_at IS NULL) + OR (state IN ('expired', 'insufficient_bank') AND outcome IS NULL AND ended_at IS NOT NULL) + OR (state = 'completed' AND outcome IS NOT NULL AND ended_at IS NOT NULL) + ) +); + +-- A corrective attempt can only attach to an eligible terminal root owned by +-- the same candidate and for the same specialization. The application still +-- validates the full chain order and descending grades inside its transaction. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_root_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + root_attempt assessment_attempts%ROWTYPE; +BEGIN + IF NEW.kind <> 'corrective' THEN + RETURN NEW; + END IF; + + SELECT * INTO root_attempt + FROM assessment_attempts + WHERE id = NEW.root_attempt_id + FOR SHARE; + + IF NOT FOUND OR root_attempt.kind <> 'root' OR root_attempt.user_id <> NEW.user_id OR + root_attempt.specialization <> NEW.specialization OR + root_attempt.state NOT IN ('expired', 'completed') OR + (root_attempt.state = 'completed' AND root_attempt.outcome NOT IN ('not_confirmed', 'not_determined')) OR + root_attempt.chain_deadline IS NULL OR root_attempt.chain_deadline <= NEW.created_at OR + NEW.chain_deadline <> root_attempt.chain_deadline THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_root_eligibility', + MESSAGE = 'corrective attempt does not continue an eligible root'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_root_guard +BEFORE INSERT OR UPDATE ON assessment_attempts +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_root_guard(); + +-- Verify the row refers to the exact current, reviewed opening or separately +-- reviewed training binding chosen by the transaction-bound bank service. +-- The caller holds the category advisory lock while it resolves and inserts. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_bank_pin_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + pinned_category text; + pinned_product_policy_id uuid; + pinned_grading_policy_id uuid; + pinned_manifest_sha256 bytea; + current_product_policy_id uuid; + current_product_policy_version integer; +BEGIN + PERFORM pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || NEW.bank_category, 0) + ); + + SELECT id, version INTO current_product_policy_id, current_product_policy_version + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= NEW.created_at + ORDER BY version DESC + LIMIT 1; + IF NOT FOUND OR current_product_policy_id <> NEW.product_policy_version_id OR + current_product_policy_version <> NEW.product_policy_version THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_product_policy_pin', + MESSAGE = 'attempt must pin the effective product policy'; + END IF; + + IF NEW.kind = 'demo_express' THEN + SELECT category, product_policy_version_id, manifest_sha256 + INTO pinned_category, pinned_product_policy_id, pinned_manifest_sha256 + FROM assessment_training_bank_bindings + WHERE id = NEW.training_binding_id; + + IF NOT FOUND OR pinned_category <> NEW.bank_category OR + pinned_product_policy_id <> NEW.product_policy_version_id OR + pinned_manifest_sha256 <> NEW.training_manifest_sha256 THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_training_binding_pin', + MESSAGE = 'training attempt does not match its reviewed binding'; + END IF; + ELSE + SELECT opening.category, opening.policy_version_id, catalog.published_manifest_sha256 + INTO pinned_category, pinned_grading_policy_id, pinned_manifest_sha256 + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS catalog ON catalog.opening_id = opening.id + WHERE opening.id = NEW.opening_id + AND NOT EXISTS ( + SELECT 1 FROM assessment_category_openings AS newer + WHERE newer.category = opening.category + AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id) + ); + + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin', + MESSAGE = 'real attempt opening is not current and reviewed'; + END IF; + + IF pinned_category <> NEW.bank_category OR + pinned_grading_policy_id <> NEW.grading_policy_version_id OR + pinned_manifest_sha256 <> NEW.opening_manifest_sha256 OR + current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin', + MESSAGE = 'real attempt does not match its current reviewed opening'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_bank_pin_guard +BEFORE INSERT ON assessment_attempts +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_bank_pin_guard(); + +-- Commands may update lifecycle and session fields, but an attempt's owner, +-- selection, policy/bank pins, and deadlines never change after creation. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_immutable_pins_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (to_jsonb(NEW) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' - + 'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') IS DISTINCT FROM + (to_jsonb(OLD) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' - + 'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') OR + NEW.version <> OLD.version + 1 OR NEW.updated_at < OLD.updated_at THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_pins_immutable', + MESSAGE = 'assessment attempt pins are immutable and every transition increments version'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_immutable_pins_guard +BEFORE UPDATE ON assessment_attempts +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_immutable_pins_guard(); + +CREATE INDEX assessment_attempts_candidate_created_idx +ON assessment_attempts (user_id, created_at DESC, id DESC); + +-- Corrective attempts belong to their root chain and share its specialization. +CREATE INDEX assessment_attempts_root_chain_idx +ON assessment_attempts (root_attempt_id, created_at, id); + +-- Active work is unique per candidate and real specialization. All nonterminal +-- lifecycle states stay in the index as later commands add them. +CREATE UNIQUE INDEX assessment_attempts_one_active_real_specialization +ON assessment_attempts (user_id, specialization) +WHERE kind IN ('root', 'corrective') + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize'); + +CREATE UNIQUE INDEX assessment_attempts_one_active_training +ON assessment_attempts (user_id) +WHERE kind = 'demo_express' + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize'); + +CREATE TABLE assessment_attempt_items ( + id uuid NOT NULL, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + ordinal integer NOT NULL, + family_id uuid NOT NULL REFERENCES assessment_families (id), + family_key text NOT NULL, + family_version integer NOT NULL, + family_content_sha256 bytea NOT NULL, + variant jsonb NOT NULL, + -- Keep canonical UTF-8 JSON bytes so schema-valid strings containing NUL + -- survive PostgreSQL storage; jsonb rejects \u0000 values. + answer bytea, + answered_at timestamptz, + CONSTRAINT assessment_attempt_items_pkey PRIMARY KEY (id), + CONSTRAINT assessment_attempt_items_ordinal_key UNIQUE (attempt_id, ordinal), + CONSTRAINT assessment_attempt_items_family_key UNIQUE (attempt_id, family_key), + CONSTRAINT assessment_attempt_items_ordinal CHECK (ordinal BETWEEN 1 AND 220), + CONSTRAINT assessment_attempt_items_family_version CHECK (family_version > 0), + CONSTRAINT assessment_attempt_items_family_hash CHECK (octet_length(family_content_sha256) = 32), + CONSTRAINT assessment_attempt_items_variant_object CHECK ( + jsonb_typeof(variant) = 'object' AND octet_length(variant::text) <= 1048576 + ), + CONSTRAINT assessment_attempt_items_answer_bound CHECK ( + answer IS NULL OR octet_length(answer) <= 524288 + ), + CONSTRAINT assessment_attempt_items_answer_stamp CHECK ( + (answer IS NULL) = (answered_at IS NULL) + ) +); + +CREATE INDEX assessment_attempt_items_family_usage_idx +ON assessment_attempt_items (family_id, attempt_id); + +-- A variant's identity and content are fixed at creation. Answering is a +-- one-way NULL -> value transition; replay is handled by the attempt outcome. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_item_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + attempt assessment_attempts%ROWTYPE; + family assessment_families%ROWTYPE; +BEGIN + IF TG_OP = 'DELETE' THEN + IF pg_trigger_depth() <= 1 THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_delete_forbidden', + MESSAGE = 'assessment items can be removed only by account or attempt cascade'; + END IF; + RETURN OLD; + END IF; + + SELECT * INTO STRICT attempt + FROM assessment_attempts WHERE id = NEW.attempt_id; + SELECT * INTO STRICT family + FROM assessment_families WHERE id = NEW.family_id; + + IF family.family_key <> NEW.family_key OR family.version <> NEW.family_version OR + family.content_sha256 <> NEW.family_content_sha256 OR family.category <> attempt.bank_category THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_pin', + MESSAGE = 'assessment item family pin is inconsistent'; + END IF; + + IF TG_OP = 'UPDATE' THEN + IF NEW.id <> OLD.id OR NEW.attempt_id <> OLD.attempt_id OR NEW.ordinal <> OLD.ordinal OR + NEW.family_id <> OLD.family_id OR NEW.family_key <> OLD.family_key OR + NEW.family_version <> OLD.family_version OR NEW.family_content_sha256 <> OLD.family_content_sha256 OR + NEW.variant <> OLD.variant OR OLD.answer IS NOT NULL OR NEW.answer IS NULL OR NEW.answered_at IS NULL THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_immutable', + MESSAGE = 'assessment item identity and variant are immutable'; + END IF; + IF NEW.answered_at < attempt.created_at OR NEW.answered_at >= attempt.expires_at THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_time', + MESSAGE = 'assessment answer time is outside the attempt deadline'; + END IF; + ELSIF TG_OP = 'INSERT' THEN + IF family.lifecycle <> 'published' OR family.review_status <> 'approved' OR + family.reviewer IS NULL OR family.author = family.reviewer THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_reviewed', + MESSAGE = 'assessment item family is not approved and published'; + END IF; + IF attempt.kind = 'demo_express' AND NOT EXISTS ( + SELECT 1 + FROM assessment_training_bank_binding_families AS member + WHERE member.binding_id = attempt.training_binding_id + AND member.family_id = NEW.family_id + AND member.family_key = NEW.family_key + AND member.family_version = NEW.family_version + AND member.content_sha256 = NEW.family_content_sha256 + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_training_member', + MESSAGE = 'training attempt item is not in its pinned binding'; + END IF; + IF NEW.answer IS NOT NULL OR NEW.answered_at IS NOT NULL THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_initial', + MESSAGE = 'assessment items start without candidate answers'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_item_guard +BEFORE INSERT OR UPDATE OR DELETE ON assessment_attempt_items +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_item_guard(); + +-- Every idempotent response is a typed, allowlisted public read-model snapshot. +-- It never contains candidate answers, reference answers, seeds, family keys, +-- or private policy and opening identifiers. +CREATE TABLE assessment_attempt_idempotency_outcomes ( + scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + operation text NOT NULL, + status_code smallint NOT NULL, + problem_code text, + response_snapshot jsonb, + response_schema_version smallint NOT NULL DEFAULT 1, + created_at timestamptz NOT NULL, + CONSTRAINT assessment_attempt_idempotency_outcomes_pkey PRIMARY KEY (scope_hash), + CONSTRAINT assessment_attempt_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32), + CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')), + CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK ( + (operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL) + OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + ), + CONSTRAINT assessment_attempt_idempotency_outcomes_response CHECK ( + response_snapshot IS NULL OR ( + jsonb_typeof(response_snapshot) = 'object' + AND octet_length(response_snapshot::text) <= 4194304 + ) + ), + CONSTRAINT assessment_attempt_idempotency_outcomes_schema CHECK (response_schema_version = 1) +); + +-- Keep committed command outcomes immutable; the generic 24-hour idempotency +-- purge may still delete them by cascading from idempotency_records. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_idempotency_outcome_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_idempotency_outcome_immutable', + MESSAGE = 'assessment idempotency outcomes are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_idempotency_outcome_refuse_update +BEFORE UPDATE ON assessment_attempt_idempotency_outcomes +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_idempotency_outcome_refuse_update(); + +-- +goose Down +DROP TRIGGER assessment_attempt_idempotency_outcome_refuse_update ON assessment_attempt_idempotency_outcomes; +DROP FUNCTION assessment_attempt_idempotency_outcome_refuse_update(); +DROP TABLE assessment_attempt_idempotency_outcomes; + +DROP TRIGGER assessment_attempt_item_guard ON assessment_attempt_items; +DROP FUNCTION assessment_attempt_item_guard(); +DROP TABLE assessment_attempt_items; +DROP TRIGGER assessment_attempt_root_guard ON assessment_attempts; +DROP FUNCTION assessment_attempt_root_guard(); +DROP TRIGGER assessment_attempt_bank_pin_guard ON assessment_attempts; +DROP FUNCTION assessment_attempt_bank_pin_guard(); +DROP TRIGGER assessment_attempt_immutable_pins_guard ON assessment_attempts; +DROP FUNCTION assessment_attempt_immutable_pins_guard(); +DROP INDEX assessment_attempts_one_active_training; +DROP INDEX assessment_attempts_one_active_real_specialization; +DROP INDEX assessment_attempts_root_chain_idx; +DROP INDEX assessment_attempts_candidate_created_idx; +DROP TABLE assessment_attempts; + +DROP TRIGGER assessment_training_binding_family_refuse_update_delete ON assessment_training_bank_binding_families; +DROP TRIGGER assessment_training_binding_refuse_update_delete ON assessment_training_bank_bindings; +DROP FUNCTION assessment_training_binding_refuse_change(); +DROP TRIGGER assessment_training_binding_complete ON assessment_training_bank_bindings; +DROP TRIGGER assessment_training_binding_family_complete ON assessment_training_bank_binding_families; +DROP FUNCTION assessment_training_binding_complete(); +DROP FUNCTION assessment_training_binding_family_complete(); +DROP FUNCTION assessment_training_binding_assert_complete(uuid); +DROP TRIGGER assessment_training_binding_family_guard ON assessment_training_bank_binding_families; +DROP FUNCTION assessment_training_binding_family_guard(); +DROP TRIGGER assessment_real_opening_rejects_training_category ON assessment_category_openings; +DROP FUNCTION assessment_real_opening_rejects_training_category(); +DROP TRIGGER assessment_training_binding_guard ON assessment_training_bank_bindings; +DROP FUNCTION assessment_training_binding_guard(); +DROP TABLE assessment_training_bank_binding_families; +DROP TABLE assessment_training_bank_bindings; diff --git a/backend/db/migrations/00025_create_support_cases.sql b/backend/db/migrations/00025_create_support_cases.sql new file mode 100644 index 0000000..b2bf9c1 --- /dev/null +++ b/backend/db/migrations/00025_create_support_cases.sql @@ -0,0 +1,385 @@ +-- +goose Up +-- Account-owned support snapshots store only typed object references. The +-- referenced records stay in their own bounded authorization scopes. +CREATE SEQUENCE support_case_number_seq + AS bigint + MINVALUE 1 + MAXVALUE 9999999999 + NO CYCLE; + +CREATE TABLE support_cases ( + id uuid NOT NULL, + case_number text NOT NULL, + owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + case_type text NOT NULL, + status text NOT NULL, + description text NOT NULL, + object_type text, + object_id uuid, + assessment_specialization text, + assessment_grade text, + complaint_reason text, + rubric_version integer, + rubric_opening_id uuid, + rubric_policy_version_id uuid, + target_business_days integer NOT NULL, + target_due_at timestamptz NOT NULL, + target_answered_at timestamptz, + target_policy_version integer NOT NULL, + target_calendar_version integer NOT NULL, + decision_outcome text, + decision_reason text, + decision_at timestamptz, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT support_cases_pkey PRIMARY KEY (id), + CONSTRAINT support_cases_number_key UNIQUE (case_number), + CONSTRAINT support_cases_number_format CHECK ( + case_number ~ '^SC-[0-9]{4}-[0-9]{6,10}$' + AND substring(case_number FROM 4 FOR 4)::integer = + EXTRACT(YEAR FROM created_at AT TIME ZONE 'UTC')::integer + ), + CONSTRAINT support_cases_case_type CHECK ( + case_type IN ('support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment') + ), + CONSTRAINT support_cases_status CHECK ( + status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed') + ), + CONSTRAINT support_cases_description CHECK ( + char_length(description) BETWEEN 1 AND 4000 + ), + CONSTRAINT support_cases_object_pair CHECK ( + (object_type IS NULL) = (object_id IS NULL) + ), + CONSTRAINT support_cases_object_type CHECK ( + object_type IS NULL OR object_type IN ('assessment_attempt', 'organization', 'invitation', 'support_case') + ), + CONSTRAINT support_cases_assessment_target_pair CHECK ( + (assessment_specialization IS NULL) = (assessment_grade IS NULL) + ), + CONSTRAINT support_cases_assessment_specialization CHECK ( + assessment_specialization IS NULL OR assessment_specialization IN ( + 'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa' + ) + ), + CONSTRAINT support_cases_assessment_grade CHECK ( + assessment_grade IS NULL OR assessment_grade IN ('intern', 'junior', 'middle', 'senior') + ), + CONSTRAINT support_cases_complaint_reason CHECK ( + complaint_reason IS NULL OR complaint_reason IN ( + 'organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other' + ) + ), + CONSTRAINT support_cases_rubric_version CHECK (rubric_version IS NULL OR rubric_version > 0), + CONSTRAINT support_cases_rubric_opening_fkey FOREIGN KEY (rubric_opening_id) + REFERENCES assessment_category_openings (id), + CONSTRAINT support_cases_rubric_policy_version_fkey FOREIGN KEY (rubric_policy_version_id) + REFERENCES policy_versions (id), + CONSTRAINT support_cases_rubric_pin_shape CHECK ( + (rubric_version IS NULL AND rubric_opening_id IS NULL AND rubric_policy_version_id IS NULL) + OR ( + case_type = 'manual_assessment' + AND rubric_version IS NOT NULL + AND rubric_opening_id IS NOT NULL + AND rubric_policy_version_id IS NOT NULL + ) + ), + CONSTRAINT support_cases_target_values CHECK ( + target_business_days BETWEEN 1 AND 60 + AND target_policy_version > 0 + AND target_calendar_version > 0 + AND target_due_at >= created_at + AND (target_answered_at IS NULL OR target_answered_at >= created_at) + ), + CONSTRAINT support_cases_decision_shape CHECK ( + (decision_outcome IS NULL AND decision_reason IS NULL AND decision_at IS NULL) + OR ( + decision_outcome IS NOT NULL + AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed') + AND decision_reason IS NOT NULL + AND char_length(decision_reason) BETWEEN 1 AND 4000 + AND decision_at IS NOT NULL + ) + ), + CONSTRAINT support_cases_timestamps CHECK ( + updated_at >= created_at + AND (target_answered_at IS NULL OR target_answered_at <= updated_at) + AND (decision_at IS NULL OR (decision_at >= created_at AND decision_at <= updated_at)) + ), + CONSTRAINT support_cases_fields_match_type CHECK ( + ( + case_type = 'support' + AND (complaint_reason IS NULL) + AND rubric_version IS NULL + AND assessment_specialization IS NULL + ) + OR ( + case_type = 'complaint' + AND object_type IS NOT NULL + AND object_type IN ('organization', 'invitation') + AND complaint_reason IS NOT NULL + AND assessment_specialization IS NULL + AND rubric_version IS NULL + AND (complaint_reason NOT IN ('offer_content', 'salary_terms_violation') OR object_type = 'invitation') + ) + OR ( + case_type = 'grade_appeal' + AND object_type IS NOT NULL + AND object_type IN ('assessment_attempt', 'support_case') + AND complaint_reason IS NULL + AND assessment_specialization IS NULL + AND rubric_version IS NULL + ) + OR ( + case_type = 'anticheat_appeal' + AND object_type IS NOT NULL + AND object_type = 'assessment_attempt' + AND complaint_reason IS NULL + AND assessment_specialization IS NULL + AND rubric_version IS NULL + ) + OR ( + case_type = 'manual_assessment' + AND assessment_specialization IS NOT NULL + AND complaint_reason IS NULL + AND (object_type IS NULL OR object_type = 'assessment_attempt') + ) + ), + CONSTRAINT support_cases_decision_matches_type CHECK ( + decision_outcome IS NULL + OR (case_type = 'support' AND decision_outcome = 'answered') + OR (case_type = 'manual_assessment' AND decision_outcome = 'assessed') + OR ( + case_type IN ('complaint', 'grade_appeal', 'anticheat_appeal') + AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld') + ) + ), + CONSTRAINT support_cases_status_decision CHECK ( + (status = 'resolved') = (decision_outcome IS NOT NULL) + ) +); + +-- A stored rubric pin must name the immutable current opening for the exact +-- target and the grading-policy version used by automated assessment. +-- +goose StatementBegin +CREATE FUNCTION support_cases_rubric_pin_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + opening_policy_version_id uuid; + pinned_version integer; +BEGIN + IF NEW.rubric_version IS NULL THEN + RETURN NEW; + END IF; + + SELECT opening.policy_version_id, policy.version + INTO opening_policy_version_id, pinned_version + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS binding + ON binding.opening_id = opening.id + JOIN policy_versions AS policy + ON policy.id = opening.policy_version_id + WHERE opening.id = NEW.rubric_opening_id + AND opening.policy_version_id = NEW.rubric_policy_version_id + AND binding.specialization = NEW.assessment_specialization + AND binding.grade = NEW.assessment_grade + AND policy.policy_key = 'product' + AND NOT EXISTS ( + SELECT 1 + FROM assessment_category_openings AS newer + WHERE newer.category = opening.category + AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id) + ) + AND opening.policy_version_id = ( + SELECT current_policy.id + FROM policy_versions AS current_policy + WHERE current_policy.policy_key = 'product' + AND current_policy.effective_at <= statement_timestamp() + ORDER BY current_policy.version DESC + LIMIT 1 + ); + + IF NOT FOUND OR opening_policy_version_id IS DISTINCT FROM NEW.rubric_policy_version_id + OR pinned_version IS DISTINCT FROM NEW.rubric_version THEN + RAISE EXCEPTION USING + ERRCODE = 'check_violation', CONSTRAINT = 'support_cases_rubric_pin_consistency', + MESSAGE = 'support case rubric pin does not match its current reviewed opening'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_cases_rubric_pin_guard +BEFORE INSERT OR UPDATE OF rubric_version, rubric_opening_id, rubric_policy_version_id, + assessment_specialization, assessment_grade, created_at +ON support_cases +FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_guard(); + +-- Rubric evidence is fixed at creation even when case status and history later +-- change. +-- +goose StatementBegin +CREATE FUNCTION support_cases_rubric_pin_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (NEW.rubric_version, NEW.rubric_opening_id, NEW.rubric_policy_version_id) + IS DISTINCT FROM (OLD.rubric_version, OLD.rubric_opening_id, OLD.rubric_policy_version_id) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'support_cases_rubric_pin_immutable', + MESSAGE = 'support case rubric pin is immutable'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_cases_rubric_pin_immutable +BEFORE UPDATE ON support_cases +FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_immutable(); + +CREATE INDEX support_cases_owner_created_idx +ON support_cases (owner_id, created_at DESC, id DESC); + +-- An appeal is once per owner, appeal type, and target regardless of outcome. +CREATE UNIQUE INDEX support_cases_one_appeal_per_target +ON support_cases (owner_id, case_type, object_type, object_id) +WHERE case_type IN ('grade_appeal', 'anticheat_appeal'); + +CREATE UNIQUE INDEX support_cases_one_open_manual_assessment +ON support_cases (owner_id, assessment_specialization) +WHERE case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed'); + +CREATE UNIQUE INDEX support_cases_one_open_complaint_per_object +ON support_cases (owner_id, object_type, object_id) +WHERE case_type = 'complaint' AND status NOT IN ('resolved', 'closed'); + +-- Events are the append-only public history. No staff identity, private note, +-- evidence blob, or copied object data is present in this table. +CREATE TABLE support_case_events ( + case_id uuid NOT NULL REFERENCES support_cases (id) ON DELETE CASCADE, + sequence integer NOT NULL, + event_kind text NOT NULL, + actor_kind text NOT NULL, + occurred_at timestamptz NOT NULL, + status text, + message text, + CONSTRAINT support_case_events_pkey PRIMARY KEY (case_id, sequence), + CONSTRAINT support_case_events_sequence CHECK (sequence BETWEEN 1 AND 200), + CONSTRAINT support_case_events_kind CHECK ( + event_kind IN ('created', 'status_changed', 'reply', 'decision') + ), + CONSTRAINT support_case_events_actor CHECK (actor_kind IN ('user', 'support', 'system')), + CONSTRAINT support_case_events_status CHECK ( + status IS NULL OR status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed') + ), + CONSTRAINT support_case_events_message CHECK ( + message IS NULL OR ( + char_length(message) BETWEEN 1 AND 4000 + ) + ), + CONSTRAINT support_case_events_shape CHECK ( + (event_kind = 'created' AND actor_kind = 'user' AND status = 'submitted' AND message IS NULL) + OR (event_kind = 'status_changed' AND actor_kind IN ('support', 'system') AND status IS NOT NULL) + OR (event_kind = 'reply' AND actor_kind IN ('user', 'support') AND status IS NULL AND message IS NOT NULL) + OR (event_kind = 'decision' AND actor_kind = 'support' AND status = 'resolved' AND message IS NOT NULL) + ), + CONSTRAINT support_case_events_close_reason CHECK ( + status <> 'closed' OR (event_kind = 'status_changed' AND message IS NOT NULL) + ) +); + +-- Prevent rewriting event history while allowing account deletion cascades. +-- +goose StatementBegin +CREATE FUNCTION support_case_events_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'support_case_events_immutable', + MESSAGE = 'support case events are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_case_events_refuse_update_delete +BEFORE UPDATE OR DELETE ON support_case_events +FOR EACH ROW EXECUTE FUNCTION support_case_events_refuse_change(); + +-- The create result lives exactly as long as its generic scoped idempotency +-- record. Its original snapshot and late flag cannot be rewritten on replay. +CREATE TABLE support_case_create_outcomes ( + scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + outcome_kind text NOT NULL, + case_snapshot jsonb, + target_was_late boolean, + created_at timestamptz NOT NULL, + CONSTRAINT support_case_create_outcomes_pkey PRIMARY KEY (scope_hash), + CONSTRAINT support_case_create_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32), + CONSTRAINT support_case_create_outcomes_kind CHECK ( + outcome_kind IN ('created', 'not_found', 'state_conflict') + ), + CONSTRAINT support_case_create_outcomes_snapshot CHECK ( + ( + outcome_kind = 'created' + AND case_snapshot IS NOT NULL + AND jsonb_typeof(case_snapshot) = 'object' + AND octet_length(case_snapshot::text) <= 1048576 + AND target_was_late IS NOT NULL + ) OR ( + outcome_kind IN ('not_found', 'state_conflict') + AND case_snapshot IS NULL + AND target_was_late IS NULL + ) + ) +); + +-- A live idempotent result cannot change between the original response and a +-- replay. Expiry cleanup may still delete it through its parent record. +-- +goose StatementBegin +CREATE FUNCTION support_case_create_outcomes_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'support_case_create_outcomes_immutable', + MESSAGE = 'support case create outcomes are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER support_case_create_outcomes_refuse_update +BEFORE UPDATE ON support_case_create_outcomes +FOR EACH ROW EXECUTE FUNCTION support_case_create_outcomes_refuse_update(); + +-- Request events retain the maximum supported 24-hour window, not merely the +-- current policy's window. Rows are pruned in small batches by each request. +CREATE TABLE support_case_request_events ( + id bigint GENERATED ALWAYS AS IDENTITY, + owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + requested_at timestamptz NOT NULL, + CONSTRAINT support_case_request_events_pkey PRIMARY KEY (id) +); + +CREATE INDEX support_case_request_events_owner_time_idx +ON support_case_request_events (owner_id, requested_at, id); + +-- +goose Down +DROP TABLE support_case_request_events; +DROP TRIGGER support_cases_rubric_pin_immutable ON support_cases; +DROP FUNCTION support_cases_rubric_pin_immutable(); +DROP TRIGGER support_cases_rubric_pin_guard ON support_cases; +DROP FUNCTION support_cases_rubric_pin_guard(); +DROP TRIGGER support_case_create_outcomes_refuse_update ON support_case_create_outcomes; +DROP FUNCTION support_case_create_outcomes_refuse_update(); +DROP TABLE support_case_create_outcomes; +DROP TRIGGER support_case_events_refuse_update_delete ON support_case_events; +DROP FUNCTION support_case_events_refuse_change(); +DROP TABLE support_case_events; +DROP INDEX support_cases_one_open_complaint_per_object; +DROP INDEX support_cases_one_open_manual_assessment; +DROP INDEX support_cases_one_appeal_per_target; +DROP INDEX support_cases_owner_created_idx; +DROP TABLE support_cases; +DROP SEQUENCE support_case_number_seq; diff --git a/backend/db/migrations/00026_create_organization_need_creation_results.sql b/backend/db/migrations/00026_create_organization_need_creation_results.sql new file mode 100644 index 0000000..e3999ef --- /dev/null +++ b/backend/db/migrations/00026_create_organization_need_creation_results.sql @@ -0,0 +1,97 @@ +-- +goose Up +-- Store the original public create response alongside the generic +-- idempotency record. A new reservation may replace this snapshot only after +-- the 24-hour logical replay window expires; bounded purge removes it with +-- the idempotency row. The live need is intentionally not a foreign key. +-- jsonb::text adds structural whitespace, so these checks allow a bounded +-- 8 KiB representation margin after the compact application-level limits. +ALTER TABLE organization_need_versions + DROP CONSTRAINT organization_need_versions_snapshot_shape, + ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version'] + AND jsonb_typeof(snapshot -> 'id') = 'string' + AND snapshot ->> 'id' = need_id::text + AND jsonb_typeof(snapshot -> 'organization_id') = 'string' + AND snapshot ->> 'organization_id' = organization_id::text + AND jsonb_typeof(snapshot -> 'version') = 'number' + AND snapshot ->> 'version' = version::text + AND jsonb_typeof(snapshot -> 'requirements_version') = 'number' + AND CASE + WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$' + THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version + ELSE FALSE + END + AND octet_length(snapshot::text) <= 270336 + ); + +CREATE TABLE organization_need_creation_results ( + scope_hash bytea NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT organization_need_creation_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT organization_need_creation_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT organization_need_creation_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT organization_need_creation_results_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['need', 'readiness', 'recommendations'] + AND octet_length(snapshot::text) <= 532480 + ) +); + +-- +goose Down +-- Rolling back must not invalidate a response replay that is still within its +-- logical window, or remove historical need snapshots that the old bound +-- cannot represent. Expired replay rows may remain until bounded purge runs. +-- The idempotency lock blocks writes across the shared table, so operators +-- run this rollback with writing processes stopped. +LOCK TABLE idempotency_records IN ACCESS EXCLUSIVE MODE; +LOCK TABLE organization_need_versions IN ACCESS EXCLUSIVE MODE; +LOCK TABLE organization_need_creation_results IN ACCESS EXCLUSIVE MODE; + +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM organization_need_creation_results AS result + INNER JOIN idempotency_records AS record USING (scope_hash) + WHERE record.expires_at > clock_timestamp() + ) THEN + RAISE EXCEPTION 'cannot roll back migration 00026 while live need creation replays remain'; + END IF; + + IF EXISTS ( + SELECT 1 + FROM organization_need_versions + WHERE octet_length(snapshot::text) > 262144 + ) THEN + RAISE EXCEPTION 'cannot roll back migration 00026 while need snapshots exceed the prior storage bound'; + END IF; +END +$$; +-- +goose StatementEnd + +DROP TABLE organization_need_creation_results; +ALTER TABLE organization_need_versions + DROP CONSTRAINT organization_need_versions_snapshot_shape, + ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK ( + jsonb_typeof(snapshot) = 'object' + AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version'] + AND jsonb_typeof(snapshot -> 'id') = 'string' + AND snapshot ->> 'id' = need_id::text + AND jsonb_typeof(snapshot -> 'organization_id') = 'string' + AND snapshot ->> 'organization_id' = organization_id::text + AND jsonb_typeof(snapshot -> 'version') = 'number' + AND snapshot ->> 'version' = version::text + AND jsonb_typeof(snapshot -> 'requirements_version') = 'number' + AND CASE + WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$' + THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version + ELSE FALSE + END + AND octet_length(snapshot::text) <= 262144 + ); diff --git a/backend/db/migrations/00027_expand_candidate_card_fields.sql b/backend/db/migrations/00027_expand_candidate_card_fields.sql new file mode 100644 index 0000000..9beaeca --- /dev/null +++ b/backend/db/migrations/00027_expand_candidate_card_fields.sql @@ -0,0 +1,64 @@ +-- +goose Up +-- Add separately chosen opt-in groups to the anonymous card. The +-- publication and event constraints call this function, so replacing it +-- changes the accepted contract without rewriting any saved field set. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 9 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'salary_compatibility', 'self_assessment', 'soft_skills', + 'stack', 'work_formats' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- +goose Down +-- Do not strand stored publication or immutable history rows outside the old +-- contract. An operator must close/remove the newer publications through the +-- normal product workflow before this migration can be rolled back. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM candidate_publications + WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text [] + ) OR EXISTS ( + SELECT 1 + FROM candidate_privacy_events + WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text [] + ) THEN + RAISE EXCEPTION 'candidate card opt-in fields are still referenced by publication history'; + END IF; +END; +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 6 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'soft_skills', 'stack' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd diff --git a/backend/db/migrations/00028_create_assessment_signals.sql b/backend/db/migrations/00028_create_assessment_signals.sql new file mode 100644 index 0000000..9df2463 --- /dev/null +++ b/backend/db/migrations/00028_create_assessment_signals.sql @@ -0,0 +1,186 @@ +-- +goose Up +-- Signal storage is a separate, bounded side channel. It contains only +-- client-reported timing and byte counts, never answer or clipboard content. +-- Writes take the generic idempotency scope, C3 consent row, then attempt row; +-- the event trigger's parent lock is reentrant inside that same transaction. + +ALTER TABLE assessment_attempt_items +ADD CONSTRAINT assessment_attempt_items_attempt_id_id_key UNIQUE (attempt_id, id); + +CREATE TABLE assessment_signal_batches ( + id uuid NOT NULL, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + received_at timestamptz NOT NULL, + event_count integer NOT NULL, + CONSTRAINT assessment_signal_batches_pkey PRIMARY KEY (id), + CONSTRAINT assessment_signal_batches_attempt_id_id_key UNIQUE (attempt_id, id), + CONSTRAINT assessment_signal_batches_event_count CHECK (event_count BETWEEN 1 AND 50) +); + +CREATE INDEX assessment_signal_batches_attempt_received_idx +ON assessment_signal_batches (attempt_id, received_at, id); + +-- Direct edits and deletes would invalidate accepted receipt counts. The +-- nested delete issued by the attempt foreign-key cascade is the only delete +-- path while a batch exists. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_batch_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_batches_immutable', + MESSAGE = 'assessment signal batches are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_batch_immutable +BEFORE UPDATE OR DELETE ON assessment_signal_batches +FOR EACH ROW EXECUTE FUNCTION assessment_signal_batch_immutable(); + +CREATE TABLE assessment_signal_events ( + batch_id uuid NOT NULL, + attempt_id uuid NOT NULL, + ordinal integer NOT NULL, + item_instance_id uuid NOT NULL, + kind text NOT NULL, + occurred_at timestamptz NOT NULL, + duration_ms integer, + size_bytes integer, + CONSTRAINT assessment_signal_events_pkey PRIMARY KEY (batch_id, ordinal), + CONSTRAINT assessment_signal_events_batch_attempt_fk FOREIGN KEY (attempt_id, batch_id) + REFERENCES assessment_signal_batches (attempt_id, id) ON DELETE CASCADE, + CONSTRAINT assessment_signal_events_item_attempt_fk FOREIGN KEY (attempt_id, item_instance_id) + REFERENCES assessment_attempt_items (attempt_id, id) ON DELETE CASCADE, + CONSTRAINT assessment_signal_events_ordinal CHECK (ordinal BETWEEN 1 AND 50), + CONSTRAINT assessment_signal_events_kind CHECK ( + kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit') + ), + CONSTRAINT assessment_signal_events_measurement CHECK ( + (kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL) + OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647) + OR (kind = 'fullscreen_exit' AND duration_ms IS NULL AND size_bytes IS NULL) + ) +); + +CREATE INDEX assessment_signal_events_attempt_idx +ON assessment_signal_events (attempt_id, batch_id, ordinal); + +-- Serialize capacity and lifecycle checks on the same attempt row used by the +-- usecase. The application stores a whole-batch saturated receipt before this +-- trigger is reached; the trigger is a backstop for other database writers. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_event_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + attempt_kind text; + attempt_state text; + attempt_expires_at timestamptz; + existing_count bigint; +BEGIN + SELECT kind, state, expires_at + INTO attempt_kind, attempt_state, attempt_expires_at + FROM assessment_attempts + WHERE id = NEW.attempt_id + FOR UPDATE; + + IF attempt_kind NOT IN ('root', 'corrective') + OR attempt_state NOT IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') + OR attempt_expires_at <= clock_timestamp() THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_active', + MESSAGE = 'assessment attempt cannot accept signal events'; + END IF; + + SELECT count(*) INTO existing_count + FROM assessment_signal_events + WHERE attempt_id = NEW.attempt_id; + + IF existing_count >= 10000 THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_capacity', + MESSAGE = 'assessment attempt signal capacity is full'; + END IF; + + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_event_guard +BEFORE INSERT ON assessment_signal_events +FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_guard(); + +-- Events are immutable. Only nested foreign-key cascades may delete them. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_event_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_events_immutable', + MESSAGE = 'assessment signal events are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_event_immutable +BEFORE UPDATE OR DELETE ON assessment_signal_events +FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_immutable(); + +CREATE TABLE assessment_signal_idempotency_outcomes ( + scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + status text NOT NULL, + accepted_events integer NOT NULL, + received_at timestamptz NOT NULL, + CONSTRAINT assessment_signal_idempotency_outcomes_pkey PRIMARY KEY (scope_hash), + CONSTRAINT assessment_signal_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32), + CONSTRAINT assessment_signal_idempotency_outcomes_status CHECK ( + (status = 'accepted' AND accepted_events BETWEEN 1 AND 50) + OR (status = 'saturated' AND accepted_events = 0) + ) +); + +CREATE INDEX assessment_signal_idempotency_outcomes_attempt_received_idx +ON assessment_signal_idempotency_outcomes (attempt_id, received_at, scope_hash); + +-- Expired scope replacement and idempotency cleanup may delete an outcome, +-- but a live response snapshot cannot be rewritten. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_idempotency_outcome_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_idempotency_outcomes_immutable', + MESSAGE = 'assessment signal outcomes are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_signal_idempotency_outcome_immutable +BEFORE UPDATE ON assessment_signal_idempotency_outcomes +FOR EACH ROW EXECUTE FUNCTION assessment_signal_idempotency_outcome_immutable(); + +-- +goose Down +DROP TRIGGER assessment_signal_idempotency_outcome_immutable ON assessment_signal_idempotency_outcomes; +DROP FUNCTION assessment_signal_idempotency_outcome_immutable(); +DROP INDEX assessment_signal_idempotency_outcomes_attempt_received_idx; +DROP TABLE assessment_signal_idempotency_outcomes; +DROP TRIGGER assessment_signal_event_immutable ON assessment_signal_events; +DROP FUNCTION assessment_signal_event_immutable(); +DROP TRIGGER assessment_signal_event_guard ON assessment_signal_events; +DROP FUNCTION assessment_signal_event_guard(); +DROP INDEX assessment_signal_events_attempt_idx; +DROP TABLE assessment_signal_events; +DROP TRIGGER assessment_signal_batch_immutable ON assessment_signal_batches; +DROP FUNCTION assessment_signal_batch_immutable(); +DROP INDEX assessment_signal_batches_attempt_received_idx; +DROP TABLE assessment_signal_batches; +ALTER TABLE assessment_attempt_items +DROP CONSTRAINT assessment_attempt_items_attempt_id_id_key; diff --git a/backend/db/migrations/00029_expand_assessment_command_outcomes.sql b/backend/db/migrations/00029_expand_assessment_command_outcomes.sql new file mode 100644 index 0000000..17be92f --- /dev/null +++ b/backend/db/migrations/00029_expand_assessment_command_outcomes.sql @@ -0,0 +1,203 @@ +-- +goose Up +-- Assessment completion supports the deliberately separate express outcome, +-- and answers/finalization store immutable public responses for key replay. + +ALTER TABLE assessment_attempts + DROP CONSTRAINT assessment_attempts_outcome, + ADD CONSTRAINT assessment_attempts_outcome CHECK ( + outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined', 'demonstration') + ); + +ALTER TABLE assessment_attempt_idempotency_outcomes + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation, + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status, + ADD COLUMN pending_item_ids uuid[] NOT NULL DEFAULT '{}'::uuid[], + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK ( + operation IN ('create', 'session', 'answer', 'finalize') + ), + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK ( + (operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation = 'create' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL) + OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation IN ('answer', 'finalize') AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation IN ('answer', 'finalize') AND status_code = 404 AND problem_code = 'not_found' AND response_snapshot IS NULL) + OR (operation = 'answer' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL AND cardinality(pending_item_ids) = 0) + OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL) + ), + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items CHECK ( + cardinality(pending_item_ids) <= 220 AND array_position(pending_item_ids, NULL) IS NULL AND + (cardinality(pending_item_ids) = 0 OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict')) + ); + +-- A completed result is stored once with its exact score, rationale, and +-- pinned inputs. The public projection has no answer keys or submitted answers. +CREATE TABLE assessment_attempt_results ( + attempt_id uuid NOT NULL, + user_id uuid NOT NULL, + result_snapshot jsonb NOT NULL, + schema_version smallint NOT NULL DEFAULT 1, + kind text NOT NULL, + mode text NOT NULL, + outcome text NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + grading_policy_version_id uuid REFERENCES policy_versions (id), + opening_id uuid REFERENCES assessment_category_openings (id), + opening_manifest_sha256 bytea, + training_binding_id uuid REFERENCES assessment_training_bank_bindings (id), + training_manifest_sha256 bytea, + bank_version text NOT NULL, + algorithm_version text NOT NULL, + rationale_rule text NOT NULL, + pass_mark_basis_points integer, + scored_items smallint, + raw_score smallint, + pass_points smallint, + decided_at timestamptz NOT NULL, + CONSTRAINT assessment_attempt_results_pkey PRIMARY KEY (attempt_id), + CONSTRAINT assessment_attempt_results_owner_fk FOREIGN KEY (attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_attempt_results_schema CHECK (schema_version = 1), + CONSTRAINT assessment_attempt_results_snapshot CHECK ( + jsonb_typeof(result_snapshot) = 'object' AND octet_length(result_snapshot::text) <= 65536 AND + NOT (result_snapshot ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id']) AND + NOT ((result_snapshot->'attempt') ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id']) + ), + CONSTRAINT assessment_attempt_results_versions CHECK ( + product_policy_version > 0 AND bank_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$' AND + algorithm_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$' + ), + CONSTRAINT assessment_attempt_results_decision CHECK ( + (kind IN ('root', 'corrective') AND mode = 'demo_basic' AND outcome IN ('confirmed', 'not_confirmed') + AND rationale_rule = 'demo_basic_pass_mark' + AND grading_policy_version_id IS NOT NULL AND opening_id IS NOT NULL + AND opening_manifest_sha256 IS NOT NULL AND octet_length(opening_manifest_sha256) = 32 + AND training_binding_id IS NULL AND training_manifest_sha256 IS NULL + AND pass_mark_basis_points BETWEEN 1 AND 10000 + AND scored_items IS NOT NULL AND scored_items BETWEEN 1 AND 100 + AND raw_score IS NOT NULL AND raw_score BETWEEN 0 AND scored_items + AND pass_points IS NOT NULL AND pass_points BETWEEN 1 AND scored_items + AND pass_points = ((scored_items * pass_mark_basis_points + 9999) / 10000) + AND ((outcome = 'confirmed') = (raw_score >= pass_points))) + OR (kind = 'demo_express' AND mode = 'demo_express' AND outcome = 'demonstration' + AND rationale_rule = 'demonstration_only' + AND grading_policy_version_id IS NULL AND opening_id IS NULL AND opening_manifest_sha256 IS NULL + AND training_binding_id IS NOT NULL AND training_manifest_sha256 IS NOT NULL + AND octet_length(training_manifest_sha256) = 32 AND pass_mark_basis_points IS NULL + AND scored_items IS NULL AND raw_score IS NULL AND pass_points IS NULL) + ) +); + +-- Keep the decision row bound to the completed attempt and exact pinned inputs. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_result_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + attempt assessment_attempts%ROWTYPE; +BEGIN + SELECT * INTO attempt + FROM assessment_attempts + WHERE id = NEW.attempt_id AND user_id = NEW.user_id + FOR SHARE; + + IF NOT FOUND OR attempt.state <> 'completed' OR attempt.kind <> NEW.kind OR attempt.mode <> NEW.mode OR + attempt.outcome <> NEW.outcome OR attempt.product_policy_version_id <> NEW.product_policy_version_id OR + attempt.product_policy_version <> NEW.product_policy_version OR attempt.grading_policy_version_id IS DISTINCT FROM NEW.grading_policy_version_id OR + attempt.opening_id IS DISTINCT FROM NEW.opening_id OR attempt.opening_manifest_sha256 IS DISTINCT FROM NEW.opening_manifest_sha256 OR + attempt.training_binding_id IS DISTINCT FROM NEW.training_binding_id OR attempt.training_manifest_sha256 IS DISTINCT FROM NEW.training_manifest_sha256 OR + attempt.bank_version <> NEW.bank_version OR attempt.algorithm_version <> NEW.algorithm_version OR + attempt.ended_at IS DISTINCT FROM NEW.decided_at OR + (NEW.result_snapshot->>'outcome') IS DISTINCT FROM NEW.outcome OR + (NEW.result_snapshot->>'decided_at')::timestamptz IS DISTINCT FROM NEW.decided_at OR + (NEW.result_snapshot->'attempt'->>'id')::uuid IS DISTINCT FROM NEW.attempt_id OR + (NEW.result_snapshot->'attempt'->>'kind') IS DISTINCT FROM NEW.kind OR + (NEW.result_snapshot->'attempt'->>'mode') IS DISTINCT FROM NEW.mode OR + (NEW.result_snapshot->'pins'->>'product_policy_version_id')::uuid IS DISTINCT FROM NEW.product_policy_version_id OR + (NEW.result_snapshot->'pins'->>'product_policy_version')::integer IS DISTINCT FROM NEW.product_policy_version OR + (NEW.result_snapshot->'pins'->>'bank_version') IS DISTINCT FROM NEW.bank_version OR + (NEW.result_snapshot->'pins'->>'algorithm_version') IS DISTINCT FROM NEW.algorithm_version OR + (NEW.result_snapshot->'pins'->>'opening_id')::uuid IS DISTINCT FROM NEW.opening_id OR + decode(NEW.result_snapshot->'pins'->>'opening_manifest_sha256', 'hex') IS DISTINCT FROM NEW.opening_manifest_sha256 OR + (NEW.result_snapshot->'pins'->>'training_binding_id')::uuid IS DISTINCT FROM NEW.training_binding_id OR + decode(NEW.result_snapshot->'pins'->>'training_manifest_sha256', 'hex') IS DISTINCT FROM NEW.training_manifest_sha256 OR + (NEW.result_snapshot->'rationale'->>'rule') IS DISTINCT FROM NEW.rationale_rule OR + (NEW.kind IN ('root', 'corrective') AND ( + (NEW.result_snapshot->'basic_score'->>'points')::smallint IS DISTINCT FROM NEW.raw_score OR + (NEW.result_snapshot->'basic_score'->>'max_points')::smallint IS DISTINCT FROM NEW.scored_items OR + (NEW.result_snapshot->'basic_score'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points OR + (NEW.result_snapshot->'rationale'->>'pass_mark_basis_points')::integer IS DISTINCT FROM NEW.pass_mark_basis_points OR + (NEW.result_snapshot->'rationale'->>'scored_items')::smallint IS DISTINCT FROM NEW.scored_items OR + (NEW.result_snapshot->'rationale'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points)) OR + (NEW.kind = 'demo_express' AND NEW.result_snapshot ? 'basic_score') THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_snapshot_match', + MESSAGE = 'assessment result does not match its completed attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_result_guard +BEFORE INSERT ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_guard(); + +-- Results cannot be overwritten or deleted independently of owner deletion. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_result_refuse_mutation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_result_immutable', + MESSAGE = 'assessment result snapshots are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_result_refuse_mutation +BEFORE UPDATE OR DELETE ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_refuse_mutation(); + +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM assessment_attempts WHERE outcome = 'demonstration' + ) OR EXISTS ( + SELECT 1 FROM assessment_attempt_idempotency_outcomes WHERE operation IN ('answer', 'finalize') + ) OR EXISTS ( + SELECT 1 FROM assessment_attempt_results + ) THEN + RAISE EXCEPTION 'assessment command data uses migration 00029 and must be retained'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER assessment_attempt_result_refuse_mutation ON assessment_attempt_results; +DROP FUNCTION assessment_attempt_result_refuse_mutation(); +DROP TRIGGER assessment_attempt_result_guard ON assessment_attempt_results; +DROP FUNCTION assessment_attempt_result_guard(); +DROP TABLE assessment_attempt_results; + +ALTER TABLE assessment_attempt_idempotency_outcomes + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status, + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation, + DROP CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items, + DROP COLUMN pending_item_ids, + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')), + ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK ( + (operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL) + OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL) + ); + +ALTER TABLE assessment_attempts + DROP CONSTRAINT assessment_attempts_outcome, + ADD CONSTRAINT assessment_attempts_outcome CHECK ( + outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined') + ); diff --git a/backend/db/migrations/00030_create_candidate_card_access_events.sql b/backend/db/migrations/00030_create_candidate_card_access_events.sql new file mode 100644 index 0000000..e3e354a --- /dev/null +++ b/backend/db/migrations/00030_create_candidate_card_access_events.sql @@ -0,0 +1,168 @@ +-- +goose Up +-- Immutable audit records for employer reads of anonymous cards and, when a +-- future grant-backed operation exists, selected contact fields. The table +-- contains identifiers and field codes only, never the viewed content. + +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + cardinality(field_codes) BETWEEN 0 AND 6 + AND array_position(field_codes, NULL) IS NULL + AND field_codes = ARRAY( + SELECT DISTINCT code COLLATE "C" + FROM unnest(field_codes) AS code + ORDER BY code COLLATE "C" + ) + AND ( + ( + kind = 'card_viewed' + AND field_codes <@ ARRAY[ + 'categories', 'experience', 'salary_compatibility', + 'self_assessment', 'stack', 'work_formats' + ]::text [] + ) + OR ( + kind = 'contact_read' + AND cardinality(field_codes) BETWEEN 1 AND 4 + AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text [] + ) + ); +$$; +-- +goose StatementEnd + +CREATE TABLE candidate_card_access_events ( + id uuid NOT NULL, + candidate_id uuid NOT NULL, + organization_id uuid NOT NULL, + actor_id uuid, + kind text NOT NULL, + field_codes text [] NOT NULL, + occurred_at timestamptz NOT NULL, + CONSTRAINT candidate_card_access_events_pkey PRIMARY KEY (id), + CONSTRAINT candidate_card_access_events_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_card_access_events_organization_fkey FOREIGN KEY (organization_id) + REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT candidate_card_access_events_actor_fkey FOREIGN KEY (actor_id) + REFERENCES users (id) ON DELETE SET NULL, + CONSTRAINT candidate_card_access_events_kind_known CHECK ( + kind IN ('card_viewed', 'contact_read') + ), + CONSTRAINT candidate_card_access_events_fields_valid CHECK ( + candidate_card_access_fields_are_valid(kind, field_codes) + ) +); + +CREATE INDEX candidate_card_access_events_candidate_occurred_idx +ON candidate_card_access_events (candidate_id, occurred_at DESC, id DESC); + +CREATE INDEX candidate_card_access_events_organization_occurred_idx +ON candidate_card_access_events (organization_id, occurred_at DESC, id DESC); + +-- Records cannot be altered after insertion. Deletion is allowed only for +-- unverified-account cleanup; confirmed-account history remains evidence. +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_events_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + -- Actor deletion may anonymize the foreign key while preserving every + -- other part of the historical event. + IF pg_trigger_depth() > 1 + AND OLD.actor_id IS NOT NULL + AND NEW.actor_id IS NULL + AND NEW.id IS NOT DISTINCT FROM OLD.id + AND NEW.candidate_id IS NOT DISTINCT FROM OLD.candidate_id + AND NEW.organization_id IS NOT DISTINCT FROM OLD.organization_id + AND NEW.kind IS NOT DISTINCT FROM OLD.kind + AND NEW.field_codes IS NOT DISTINCT FROM OLD.field_codes + AND NEW.occurred_at IS NOT DISTINCT FROM OLD.occurred_at THEN + RETURN NEW; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_immutable', + TABLE = 'candidate_card_access_events', + MESSAGE = 'candidate card access events are append-only'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_card_access_events_refuse_update +BEFORE UPDATE ON candidate_card_access_events +FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_update(); + +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_events_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM users + WHERE users.id = OLD.candidate_id AND users.email_verified_at IS NOT NULL + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_retained', + TABLE = 'candidate_card_access_events', + MESSAGE = 'candidate card access events of a confirmed account are retained'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_card_access_events_refuse_delete +BEFORE DELETE ON candidate_card_access_events +FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_delete(); + +-- Protect a confirmed account from a direct DELETE that would otherwise +-- cascade away its access history. The unverified registration cleanup may +-- still remove those accounts and their records. +-- +goose StatementBegin +CREATE FUNCTION candidate_card_access_events_protect_account() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.email_verified_at IS NOT NULL AND EXISTS ( + SELECT 1 FROM candidate_card_access_events + WHERE candidate_card_access_events.candidate_id = OLD.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_retained', + TABLE = 'users', + MESSAGE = 'confirmed account has retained card access history'; + END IF; + RETURN OLD; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_card_access_events_protect_account +BEFORE DELETE ON users +FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_protect_account(); + +-- +goose Down +-- Do not remove durable access evidence as a side effect of rolling back the +-- schema. Operators must export or explicitly resolve retained history first. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM candidate_card_access_events) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'candidate_card_access_events_retained', + TABLE = 'candidate_card_access_events', + MESSAGE = 'candidate card access history must be retained before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER candidate_card_access_events_protect_account ON users; +DROP FUNCTION candidate_card_access_events_protect_account(); +DROP TRIGGER candidate_card_access_events_refuse_delete ON candidate_card_access_events; +DROP FUNCTION candidate_card_access_events_refuse_delete(); +DROP TRIGGER candidate_card_access_events_refuse_update ON candidate_card_access_events; +DROP FUNCTION candidate_card_access_events_refuse_update(); +DROP TABLE candidate_card_access_events; +DROP FUNCTION candidate_card_access_fields_are_valid(text, text []); diff --git a/backend/db/migrations/00031_assessment_category_results.sql b/backend/db/migrations/00031_assessment_category_results.sql new file mode 100644 index 0000000..b573f9e --- /dev/null +++ b/backend/db/migrations/00031_assessment_category_results.sql @@ -0,0 +1,398 @@ +-- +goose Up +-- Synthetic category decisions extend immutable result rows without changing +-- the existing result_snapshot document. Version 1 rows remain readable as-is. + +ALTER TABLE assessment_attempt_results + DROP CONSTRAINT assessment_attempt_results_schema, + ADD COLUMN category_decision jsonb, + ADD COLUMN current_confirmed_grade text, + ADD CONSTRAINT assessment_attempt_results_schema CHECK (schema_version IN (1, 2)), + ADD CONSTRAINT assessment_attempt_results_category_extension CHECK ( + (schema_version = 1 AND category_decision IS NULL AND current_confirmed_grade IS NULL) + OR ( + schema_version = 2 + AND kind IN ('root', 'corrective') AND mode = 'demo_basic' + AND jsonb_typeof(category_decision) = 'object' + AND category_decision->>'attempt_id' = attempt_id::text + AND category_decision->>'specialization' IS NOT NULL + AND category_decision->>'attempted_grade' IS NOT NULL + AND category_decision->>'product_policy_version_id' = product_policy_version_id::text + AND (category_decision->>'product_policy_version')::integer = product_policy_version + AND category_decision->>'grading_policy_version_id' = grading_policy_version_id::text + AND category_decision->>'opening_id' = opening_id::text + AND category_decision->>'opening_manifest_sha256' = encode(opening_manifest_sha256, 'hex') + AND (category_decision->>'decided_at')::timestamptz = decided_at + AND category_decision->>'status' IN ('not_eligible', 'not_confirmed', 'assigned', 'unchanged') + AND NULLIF(category_decision->>'current_grade', '') IS NOT DISTINCT FROM current_confirmed_grade + AND (current_confirmed_grade IS NULL OR current_confirmed_grade IN ('intern', 'junior', 'middle', 'senior')) + ) + ); + +CREATE UNIQUE INDEX assessment_attempt_results_attempt_owner_key +ON assessment_attempt_results (attempt_id, user_id); + +CREATE INDEX assessment_attempt_results_history_idx +ON assessment_attempt_results (user_id, decided_at DESC, attempt_id DESC) +WHERE kind IN ('root', 'corrective'); + +CREATE TABLE assessment_synthetic_category_reviews ( + id uuid NOT NULL, + opening_id uuid NOT NULL REFERENCES assessment_category_openings (id), + category text NOT NULL, + source text NOT NULL, + opening_manifest_sha256 bytea NOT NULL, + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + reviewed_by text NOT NULL, + reviewed_at timestamptz NOT NULL, + CONSTRAINT assessment_synthetic_category_reviews_pkey PRIMARY KEY (id), + CONSTRAINT assessment_synthetic_category_reviews_exact_source_key UNIQUE ( + opening_id, product_policy_version_id, opening_manifest_sha256, source + ), + CONSTRAINT assessment_synthetic_category_reviews_source CHECK (source = 'synthetic_demo'), + CONSTRAINT assessment_synthetic_category_reviews_hash CHECK (octet_length(opening_manifest_sha256) = 32), + CONSTRAINT assessment_synthetic_category_reviews_policy_version CHECK (product_policy_version > 0), + CONSTRAINT assessment_synthetic_category_reviews_reviewer CHECK ( + char_length(reviewed_by) <= 128 + AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) +); + +-- A review attestation is accepted only for the exact immutable opening and +-- reviewed catalog manifest. The policy is pinned by ID and version; domain +-- validation additionally requires the complete explicit demo V2 policy. +-- +goose StatementBegin +CREATE FUNCTION assessment_synthetic_category_review_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + opening_category text; + opening_policy_id uuid; + manifest_hash bytea; + policy_version integer; +BEGIN + SELECT opening.category, opening.policy_version_id, binding.published_manifest_sha256 + INTO opening_category, opening_policy_id, manifest_hash + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS binding ON binding.opening_id = opening.id + WHERE opening.id = NEW.opening_id; + + IF NOT FOUND OR opening_category <> NEW.category OR + manifest_hash IS DISTINCT FROM NEW.opening_manifest_sha256 THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_source', + MESSAGE = 'synthetic category review does not match its immutable opening and manifest'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM policy_versions AS policy + WHERE policy.id = opening_policy_id AND policy.policy_key = 'product' + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_opening_policy', + MESSAGE = 'synthetic category review opening has no product grading policy'; + END IF; + + SELECT policy.version INTO policy_version + FROM policy_versions AS policy + WHERE policy.id = NEW.product_policy_version_id + AND policy.policy_key = 'product' + AND policy.kind = 'demo' + AND policy.version = NEW.product_policy_version + AND policy.document #>> '{assessment,attempt,real_mode}' = 'demo_basic'; + IF NOT FOUND OR policy_version <> NEW.product_policy_version THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_policy', + MESSAGE = 'synthetic category review policy is not a demo basic policy'; + END IF; + + NEW.reviewed_at := clock_timestamp(); + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_synthetic_category_review_guard +BEFORE INSERT ON assessment_synthetic_category_reviews +FOR EACH ROW EXECUTE FUNCTION assessment_synthetic_category_review_guard(); + +-- Review attestations are provenance records and cannot be rewritten or +-- removed independently of account cleanup. +-- +goose StatementBegin +CREATE FUNCTION assessment_synthetic_category_review_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_synthetic_category_review_immutable', + MESSAGE = 'synthetic category reviews are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_synthetic_category_review_refuse_mutation +BEFORE UPDATE OR DELETE ON assessment_synthetic_category_reviews +FOR EACH ROW EXECUTE FUNCTION assessment_synthetic_category_review_refuse_change(); + +CREATE TABLE candidate_assessment_categories ( + candidate_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + specialization text NOT NULL, + grade text NOT NULL, + source_attempt_id uuid NOT NULL, + source_review_id uuid NOT NULL REFERENCES assessment_synthetic_category_reviews (id), + product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + product_policy_version integer NOT NULL, + grading_policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + opening_id uuid NOT NULL REFERENCES assessment_category_openings (id), + opening_manifest_sha256 bytea NOT NULL, + source text NOT NULL, + calibration_status text NOT NULL, + assigned_at timestamptz NOT NULL, + CONSTRAINT candidate_assessment_categories_pkey PRIMARY KEY (candidate_id, specialization), + CONSTRAINT candidate_assessment_categories_source_attempt_key UNIQUE (source_attempt_id), + CONSTRAINT candidate_assessment_categories_attempt_owner_fk FOREIGN KEY (source_attempt_id, candidate_id) + REFERENCES assessment_attempt_results (attempt_id, user_id) ON DELETE CASCADE, + CONSTRAINT candidate_assessment_categories_specialization CHECK ( + specialization IN ('backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa') + ), + CONSTRAINT candidate_assessment_categories_grade CHECK (grade IN ('intern', 'junior', 'middle', 'senior')), + CONSTRAINT candidate_assessment_categories_source CHECK (source = 'synthetic_demo'), + CONSTRAINT candidate_assessment_categories_calibration CHECK (calibration_status = 'uncalibrated'), + CONSTRAINT candidate_assessment_categories_hash CHECK (octet_length(opening_manifest_sha256) = 32), + CONSTRAINT candidate_assessment_categories_policy_version CHECK (product_policy_version > 0) +); + +-- Current grade rows are derived only from an assigned immutable v2 result. +-- Upgrades are monotonic; a lower passing result remains visible in its own +-- result record and cannot lower the current category. +-- +goose StatementBegin +CREATE FUNCTION candidate_assessment_category_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + decision jsonb; + result_grade text; + result_user_id uuid; + result_at timestamptz; + review assessment_synthetic_category_reviews%ROWTYPE; + prior_rank integer; + next_rank integer; +BEGIN + SELECT result.category_decision, result.user_id, result.decided_at + INTO decision, result_user_id, result_at + FROM assessment_attempt_results AS result + WHERE result.attempt_id = NEW.source_attempt_id AND result.user_id = NEW.candidate_id + AND result.schema_version = 2; + + result_grade := decision->>'current_grade'; + IF NOT FOUND OR decision->>'status' <> 'assigned' OR result_user_id <> NEW.candidate_id OR + result_grade <> NEW.grade OR decision->>'specialization' <> NEW.specialization OR + decision->>'source' <> NEW.source OR decision->>'calibration_status' <> NEW.calibration_status OR + decision->>'review_id' <> NEW.source_review_id::text OR + decision->>'product_policy_version_id' <> NEW.product_policy_version_id::text OR + (decision->>'product_policy_version')::integer <> NEW.product_policy_version OR + decision->>'grading_policy_version_id' <> NEW.grading_policy_version_id::text OR + decision->>'opening_id' <> NEW.opening_id::text OR + decision->>'opening_manifest_sha256' <> encode(NEW.opening_manifest_sha256, 'hex') OR + NEW.assigned_at <> result_at THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'candidate_assessment_categories_result_match', + MESSAGE = 'current category does not match an assigned immutable result'; + END IF; + + SELECT * INTO review + FROM assessment_synthetic_category_reviews AS source + WHERE source.id = NEW.source_review_id + AND source.opening_id = NEW.opening_id + AND source.category = (SELECT attempt.bank_category FROM assessment_attempts AS attempt WHERE attempt.id = NEW.source_attempt_id) + AND source.source = NEW.source + AND source.opening_manifest_sha256 = NEW.opening_manifest_sha256 + AND source.product_policy_version_id = NEW.product_policy_version_id + AND source.product_policy_version = NEW.product_policy_version + AND source.reviewed_at <= result_at; + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'candidate_assessment_categories_review_match', + MESSAGE = 'current category is missing its exact reviewed synthetic source'; + END IF; + + next_rank := CASE NEW.grade WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END; + IF TG_OP = 'UPDATE' THEN + prior_rank := CASE OLD.grade WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END; + IF OLD.candidate_id <> NEW.candidate_id OR OLD.specialization <> NEW.specialization OR next_rank <= prior_rank THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'candidate_assessment_categories_monotonic', + MESSAGE = 'current category updates must be a strict upgrade in the same scope'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_assessment_category_guard +BEFORE INSERT OR UPDATE ON candidate_assessment_categories +FOR EACH ROW EXECUTE FUNCTION candidate_assessment_category_guard(); + +-- Do not permit manual removal of current category state. Account deletion may +-- cascade through the candidate owner row. +-- +goose StatementBegin +CREATE FUNCTION candidate_assessment_category_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'candidate_assessment_categories_delete', + MESSAGE = 'current category can only change through a qualified result'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER candidate_assessment_category_refuse_delete +BEFORE DELETE ON candidate_assessment_categories +FOR EACH ROW EXECUTE FUNCTION candidate_assessment_category_refuse_delete(); + +-- The extension guard ties a typed v2 decision to the row's immutable attempt +-- and exact reviewed source. Legacy v1 rows must keep both new columns NULL. +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_result_category_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + review assessment_synthetic_category_reviews%ROWTYPE; + attempt assessment_attempts%ROWTYPE; + pass_mark_text text; +BEGIN + IF NEW.schema_version = 1 THEN + RETURN NEW; + END IF; + + SELECT * INTO attempt + FROM assessment_attempts + WHERE id = NEW.attempt_id AND user_id = NEW.user_id; + IF NOT FOUND OR NEW.category_decision->>'bank_category' IS DISTINCT FROM attempt.bank_category OR + NEW.category_decision->>'specialization' IS DISTINCT FROM attempt.specialization OR + NEW.category_decision->>'attempted_grade' IS DISTINCT FROM attempt.target_grade OR + NEW.category_decision->>'grading_policy_version_id' IS DISTINCT FROM attempt.grading_policy_version_id::text OR + NEW.category_decision->>'opening_id' IS DISTINCT FROM attempt.opening_id::text OR + NEW.category_decision->>'opening_manifest_sha256' IS DISTINCT FROM encode(attempt.opening_manifest_sha256, 'hex') THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'category decision does not match its attempt'; + END IF; + + IF NEW.category_decision->>'status' = 'not_eligible' THEN + IF NEW.category_decision ? 'review_id' OR NEW.category_decision->>'source' IS NOT NULL OR + NEW.category_decision->>'method' IS NOT NULL OR NEW.category_decision->>'calibration_status' IS NOT NULL OR + NEW.category_decision->>'current_grade' IS DISTINCT FROM NEW.category_decision->>'previous_grade' THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'ineligible category decision contains review or assignment data'; + END IF; + ELSIF NEW.category_decision->>'status' IN ('not_confirmed', 'assigned', 'unchanged') THEN + IF NOT (NEW.category_decision ? 'review_id') OR + NEW.category_decision->>'source' <> 'synthetic_demo' OR + NEW.category_decision->>'calibration_status' <> 'uncalibrated' OR + NEW.category_decision->>'method' <> 'demo_basic_pass_mark' THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'reviewed category decision lacks its synthetic provenance'; + END IF; + ELSE + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_decision', + MESSAGE = 'category decision status is unsupported'; + END IF; + + IF NEW.category_decision ? 'review_id' THEN + SELECT * INTO review + FROM assessment_synthetic_category_reviews AS source + WHERE source.id = (NEW.category_decision->>'review_id')::uuid + AND source.opening_id = NEW.opening_id + AND source.category = NEW.category_decision->>'bank_category' + AND source.source = NEW.category_decision->>'source' + AND source.opening_manifest_sha256 = NEW.opening_manifest_sha256 + AND source.product_policy_version_id = NEW.product_policy_version_id + AND source.product_policy_version = NEW.product_policy_version + AND (SELECT policy_version_id FROM assessment_category_openings WHERE id = source.opening_id) = NEW.grading_policy_version_id + AND source.reviewed_at <= NEW.decided_at; + IF NOT FOUND THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_review', + MESSAGE = 'category decision does not match its exact reviewed source'; + END IF; + ELSIF NEW.category_decision->>'status' <> 'not_eligible' THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_review_required', + MESSAGE = 'reviewed category decisions require an immutable source attestation'; + END IF; + + IF NEW.category_decision->>'status' = 'assigned' AND + (NEW.outcome <> 'confirmed' OR NEW.category_decision->>'source' <> 'synthetic_demo' OR + NEW.category_decision->>'calibration_status' <> 'uncalibrated' OR + NEW.category_decision->>'method' <> 'demo_basic_pass_mark' OR + NEW.current_confirmed_grade IS DISTINCT FROM NEW.category_decision->>'attempted_grade') THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_assignment', + MESSAGE = 'category assignment is not a passing reviewed demo decision'; + END IF; + + -- The threshold that confirmed the result is the pass mark of the policy + -- version pinned to the attempt, read from the stored document and not + -- from a constant. The text is checked before the cast. + IF NEW.category_decision->>'status' = 'assigned' THEN + SELECT policy.document #>> '{assessment,attempt,basic_pass_mark_bp}' INTO pass_mark_text + FROM policy_versions AS policy + WHERE policy.id = NEW.product_policy_version_id AND policy.policy_key = 'product'; + IF NOT FOUND OR pass_mark_text IS NULL OR pass_mark_text !~ '^[0-9]{1,5}$' OR + NEW.pass_mark_basis_points IS DISTINCT FROM pass_mark_text::integer THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_threshold', + MESSAGE = 'category assignment does not use the pass mark of its pinned policy version'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_result_category_guard +BEFORE INSERT ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_category_guard(); + +-- +goose Down +-- Preserve category evidence and v2 result snapshots rather than silently +-- discarding their meanings when this migration is rolled back. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM assessment_attempt_results WHERE schema_version = 2) + OR EXISTS (SELECT 1 FROM assessment_synthetic_category_reviews) + OR EXISTS (SELECT 1 FROM candidate_assessment_categories) THEN + RAISE EXCEPTION 'assessment category data uses migration 00031 and must be retained'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER candidate_assessment_category_refuse_delete ON candidate_assessment_categories; +DROP FUNCTION candidate_assessment_category_refuse_delete(); +DROP TRIGGER candidate_assessment_category_guard ON candidate_assessment_categories; +DROP FUNCTION candidate_assessment_category_guard(); +DROP TABLE candidate_assessment_categories; +DROP TRIGGER assessment_synthetic_category_review_refuse_mutation ON assessment_synthetic_category_reviews; +DROP FUNCTION assessment_synthetic_category_review_refuse_change(); +DROP TRIGGER assessment_synthetic_category_review_guard ON assessment_synthetic_category_reviews; +DROP FUNCTION assessment_synthetic_category_review_guard(); +DROP TABLE assessment_synthetic_category_reviews; +DROP TRIGGER assessment_attempt_result_category_guard ON assessment_attempt_results; +DROP FUNCTION assessment_attempt_result_category_guard(); +DROP INDEX assessment_attempt_results_history_idx; +DROP INDEX assessment_attempt_results_attempt_owner_key; +ALTER TABLE assessment_attempt_results + DROP CONSTRAINT assessment_attempt_results_category_extension, + DROP COLUMN category_decision, + DROP COLUMN current_confirmed_grade, + DROP CONSTRAINT assessment_attempt_results_schema, + ADD CONSTRAINT assessment_attempt_results_schema CHECK (schema_version = 1); diff --git a/backend/db/migrations/00032_create_notification_inbox.sql b/backend/db/migrations/00032_create_notification_inbox.sql new file mode 100644 index 0000000..2ebfcd5 --- /dev/null +++ b/backend/db/migrations/00032_create_notification_inbox.sql @@ -0,0 +1,115 @@ +-- Inbox rows reference current product records instead of copying their +-- content. Recipient deletion removes the private inbox; organization context +-- remains retained while a source event refers to it. +-- +goose Up +CREATE TABLE notification_inbox_events ( + recipient_user_id uuid NOT NULL, + event_id uuid NOT NULL, + organization_id uuid NOT NULL, + event_type text NOT NULL, + schema_version integer NOT NULL, + source_type text NOT NULL, + source_id uuid NOT NULL, + occurred_at timestamptz NOT NULL, + read_at timestamptz, + CONSTRAINT notification_inbox_events_pkey PRIMARY KEY ( + recipient_user_id, event_id + ), + CONSTRAINT notification_inbox_events_recipient_fkey FOREIGN KEY ( + recipient_user_id + ) REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT notification_inbox_events_organization_fkey FOREIGN KEY ( + organization_id + ) REFERENCES organizations (id) ON DELETE RESTRICT, + CONSTRAINT notification_inbox_events_type_known CHECK ( + event_type = 'invitation.delivered' + AND schema_version = 1 + AND source_type = 'invitation' + ) +); + +-- Supports a recipient's chronological inbox and exact organization filters. +CREATE INDEX notification_inbox_events_recipient_occurred_idx +ON notification_inbox_events (recipient_user_id, occurred_at DESC, event_id DESC); + +CREATE INDEX notification_inbox_events_recipient_organization_occurred_idx +ON notification_inbox_events ( + recipient_user_id, organization_id, occurred_at DESC, event_id DESC +); + +-- The event reference is immutable. Only the first read timestamp may be +-- added; repeated mark-read calls may keep that timestamp unchanged. +-- +goose StatementBegin +CREATE FUNCTION notification_inbox_events_refuse_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.recipient_user_id IS NOT DISTINCT FROM OLD.recipient_user_id + AND NEW.event_id IS NOT DISTINCT FROM OLD.event_id + AND NEW.organization_id IS NOT DISTINCT FROM OLD.organization_id + AND NEW.event_type IS NOT DISTINCT FROM OLD.event_type + AND NEW.schema_version IS NOT DISTINCT FROM OLD.schema_version + AND NEW.source_type IS NOT DISTINCT FROM OLD.source_type + AND NEW.source_id IS NOT DISTINCT FROM OLD.source_id + AND NEW.occurred_at IS NOT DISTINCT FROM OLD.occurred_at + AND ( + NEW.read_at IS NOT DISTINCT FROM OLD.read_at + OR (OLD.read_at IS NULL AND NEW.read_at IS NOT NULL) + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_immutable', + TABLE = 'notification_inbox_events', + MESSAGE = 'notification inbox event metadata is immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER notification_inbox_events_refuse_update +BEFORE UPDATE ON notification_inbox_events +FOR EACH ROW EXECUTE FUNCTION notification_inbox_events_refuse_update(); + +-- Prevent clearing a recipient's event marker while allowing account +-- deletion to cascade through private inbox rows. +-- +goose StatementBegin +CREATE FUNCTION notification_inbox_events_refuse_delete() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_retained', + TABLE = 'notification_inbox_events', + MESSAGE = 'notification inbox events cannot be deleted directly'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER notification_inbox_events_refuse_delete +BEFORE DELETE ON notification_inbox_events +FOR EACH ROW EXECUTE FUNCTION notification_inbox_events_refuse_delete(); + +-- A rollback must not silently remove recipient-visible history. +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM notification_inbox_events) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_retained', + TABLE = 'notification_inbox_events', + MESSAGE = 'notification inbox records must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER notification_inbox_events_refuse_update ON notification_inbox_events; +DROP FUNCTION notification_inbox_events_refuse_update(); +DROP TRIGGER notification_inbox_events_refuse_delete ON notification_inbox_events; +DROP FUNCTION notification_inbox_events_refuse_delete(); +DROP TABLE notification_inbox_events; diff --git a/backend/db/migrations/00033_create_assessment_signal_review.sql b/backend/db/migrations/00033_create_assessment_signal_review.sql new file mode 100644 index 0000000..849738e --- /dev/null +++ b/backend/db/migrations/00033_create_assessment_signal_review.sql @@ -0,0 +1,271 @@ +-- +goose Up +-- Server-side signals of a real assessment attempt and the review band built +-- from them. The band is a hint for a manual check by an operator. Nothing here +-- is read by a result, a category, a quota, or any candidate or employer +-- operation, and nothing stores an answer, an address, or a session token: +-- answers become keyed fingerprints, sessions and networks become keyed +-- digests that are bound to one attempt. + +-- One row per accepted answer. The fingerprint is an HMAC of the normalized +-- answer under a server secret, scoped to the family version, so answers of +-- different candidates to different seed variants of one family can be compared +-- without the answer text. +CREATE TABLE assessment_answer_observations ( + attempt_id uuid NOT NULL, + item_instance_id uuid NOT NULL, + user_id uuid NOT NULL, + family_id uuid NOT NULL REFERENCES assessment_families (id), + variant_seed bigint NOT NULL, + answer_format text NOT NULL, + answer_fingerprint bytea NOT NULL, + -- Key generation of the fingerprint. Only fingerprints of one generation + -- are compared, so a future key rotation is an explicit step. + key_version smallint NOT NULL, + -- Server time from the previous answer or session start to this answer. + elapsed_ms integer NOT NULL, + -- True when the time starts at the previous answer, which is when the item + -- was shown. The first item of a work session starts at the session start + -- and is not used for the speed signals. + measured_from_answer boolean NOT NULL, + observed_at timestamptz NOT NULL, + CONSTRAINT assessment_answer_observations_pkey PRIMARY KEY (attempt_id, item_instance_id), + CONSTRAINT assessment_answer_observations_item_fk FOREIGN KEY (attempt_id, item_instance_id) + REFERENCES assessment_attempt_items (attempt_id, id) ON DELETE CASCADE, + CONSTRAINT assessment_answer_observations_owner_fk FOREIGN KEY (attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_answer_observations_format CHECK (answer_format IN ('integer', 'integer_sequence')), + CONSTRAINT assessment_answer_observations_fingerprint CHECK (octet_length(answer_fingerprint) = 32), + CONSTRAINT assessment_answer_observations_key_version CHECK (key_version > 0), + CONSTRAINT assessment_answer_observations_elapsed CHECK (elapsed_ms >= 0) +); + +-- Serves the comparison with other candidates' answers of the same family. +CREATE INDEX assessment_answer_observations_match_idx +ON assessment_answer_observations (family_id, key_version, answer_fingerprint); + +-- Maintained counters of the observations: how many answers hold each +-- fingerprint of a family version, and how many answers the family version has, +-- both per key generation. The share of a value is read from them instead of +-- being counted over the population at every comparison. They are derived +-- caches without foreign keys and are only increased: an answer removed with an +-- account stays counted, which keeps the population estimate and avoids lock +-- contention on the deletion path. +CREATE TABLE assessment_answer_fingerprint_holders ( + family_id uuid NOT NULL, + key_version smallint NOT NULL, + answer_fingerprint bytea NOT NULL, + holders integer NOT NULL, + CONSTRAINT assessment_answer_fingerprint_holders_pkey PRIMARY KEY (family_id, key_version, answer_fingerprint), + CONSTRAINT assessment_answer_fingerprint_holders_fingerprint CHECK (octet_length(answer_fingerprint) = 32), + CONSTRAINT assessment_answer_fingerprint_holders_count CHECK (holders > 0) +); + +CREATE TABLE assessment_answer_family_totals ( + family_id uuid NOT NULL, + key_version smallint NOT NULL, + answer_count integer NOT NULL, + CONSTRAINT assessment_answer_family_totals_pkey PRIMARY KEY (family_id, key_version), + CONSTRAINT assessment_answer_family_totals_count CHECK (answer_count > 0) +); + +-- The counters change in the transaction of the insert. A transaction touches +-- one holders row and one totals row, always in this order, so two answers +-- cannot deadlock on them. +-- +goose StatementBegin +CREATE FUNCTION assessment_answer_observation_count() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + INSERT INTO assessment_answer_fingerprint_holders (family_id, key_version, answer_fingerprint, holders) + VALUES (NEW.family_id, NEW.key_version, NEW.answer_fingerprint, 1) + ON CONFLICT (family_id, key_version, answer_fingerprint) + DO UPDATE SET holders = assessment_answer_fingerprint_holders.holders + 1; + INSERT INTO assessment_answer_family_totals (family_id, key_version, answer_count) + VALUES (NEW.family_id, NEW.key_version, 1) + ON CONFLICT (family_id, key_version) + DO UPDATE SET answer_count = assessment_answer_family_totals.answer_count + 1; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_answer_observation_count +AFTER INSERT ON assessment_answer_observations +FOR EACH ROW EXECUTE FUNCTION assessment_answer_observation_count(); + +-- Written when the session or the network of an attempt changes between two +-- accepted answers or signal batches: which session and which network sent +-- the request, as digests. +CREATE TABLE assessment_attempt_origin_marks ( + id uuid NOT NULL, + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + source text NOT NULL, + observed_at timestamptz NOT NULL, + session_digest bytea NOT NULL, + network_digest bytea, + key_version smallint NOT NULL, + CONSTRAINT assessment_attempt_origin_marks_pkey PRIMARY KEY (id), + CONSTRAINT assessment_attempt_origin_marks_key_version CHECK (key_version > 0), + CONSTRAINT assessment_attempt_origin_marks_source CHECK (source IN ('answer', 'signals')), + CONSTRAINT assessment_attempt_origin_marks_session CHECK (octet_length(session_digest) = 32), + CONSTRAINT assessment_attempt_origin_marks_network CHECK ( + network_digest IS NULL OR octet_length(network_digest) = 32 + ) +); + +CREATE INDEX assessment_attempt_origin_marks_attempt_idx +ON assessment_attempt_origin_marks (attempt_id, observed_at, id); + +-- Observations and marks are facts: only the attempt cascade may remove them. +-- +goose StatementBegin +CREATE FUNCTION assessment_signal_fact_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_signal_fact_immutable', + MESSAGE = 'assessment signal facts are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_answer_observations_immutable +BEFORE UPDATE OR DELETE ON assessment_answer_observations +FOR EACH ROW EXECUTE FUNCTION assessment_signal_fact_immutable(); + +CREATE TRIGGER assessment_attempt_origin_marks_immutable +BEFORE UPDATE OR DELETE ON assessment_attempt_origin_marks +FOR EACH ROW EXECUTE FUNCTION assessment_signal_fact_immutable(); + +-- The review of an attempt. It is recomputed in place when a later attempt +-- matches an answer, but it stays pinned to the product policy version of the +-- attempt that produced it. +CREATE TABLE assessment_attempt_reviews ( + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + policy_version_id uuid NOT NULL REFERENCES policy_versions (id), + band text NOT NULL, + reasons text[] NOT NULL, + answered_items integer NOT NULL, + fast_answers integer NOT NULL, + deviating_answers integer NOT NULL, + parallel_alternations integer NOT NULL, + extra_networks integer NOT NULL, + matched_integer_items integer NOT NULL, + matched_sequence_items integer NOT NULL, + duplicate_evidence_bits integer NOT NULL, + client_focus_loss_ms bigint NOT NULL, + client_clipboard_events integer NOT NULL, + client_fullscreen_exits integer NOT NULL, + evaluated_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT assessment_attempt_reviews_pkey PRIMARY KEY (attempt_id), + CONSTRAINT assessment_attempt_reviews_band CHECK (band IN ('normal', 'attention', 'review')), + CONSTRAINT assessment_attempt_reviews_reasons CHECK ( + reasons <@ ARRAY['fast_answers', 'deviating_answers', 'parallel_sessions', 'extra_networks', + 'duplicate_answers', 'client_signals']::text[] + ), + CONSTRAINT assessment_attempt_reviews_counts CHECK ( + answered_items >= 0 AND fast_answers >= 0 AND deviating_answers >= 0 AND parallel_alternations >= 0 + AND extra_networks >= 0 AND matched_integer_items >= 0 AND matched_sequence_items >= 0 + AND duplicate_evidence_bits >= 0 AND client_focus_loss_ms >= 0 AND client_clipboard_events >= 0 + AND client_fullscreen_exits >= 0 + ), + CONSTRAINT assessment_attempt_reviews_update_order CHECK (updated_at >= evaluated_at) +); + +-- +goose StatementBegin +CREATE FUNCTION assessment_attempt_review_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + ELSIF NEW.attempt_id = OLD.attempt_id AND NEW.policy_version_id = OLD.policy_version_id + AND NEW.evaluated_at = OLD.evaluated_at THEN + RETURN NEW; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_reviews_pinned', + MESSAGE = 'assessment attempt review keeps its attempt, policy version, and first evaluation'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_attempt_review_guard +BEFORE UPDATE OR DELETE ON assessment_attempt_reviews +FOR EACH ROW EXECUTE FUNCTION assessment_attempt_review_guard(); + +-- Every operator read of a review is recorded, whether or not a review exists. +-- The attempt is not a foreign key, so the record outlives an account deletion. +CREATE TABLE assessment_review_reads ( + id uuid NOT NULL, + attempt_id uuid NOT NULL, + actor text NOT NULL, + found boolean NOT NULL, + read_at timestamptz NOT NULL, + CONSTRAINT assessment_review_reads_pkey PRIMARY KEY (id), + CONSTRAINT assessment_review_reads_actor CHECK ( + char_length(actor) <= 128 AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ) +); + +CREATE INDEX assessment_review_reads_attempt_idx +ON assessment_review_reads (attempt_id, read_at); + +-- +goose StatementBegin +CREATE FUNCTION assessment_review_reads_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_review_reads_immutable', + MESSAGE = 'assessment review read records are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_review_reads_immutable +BEFORE UPDATE OR DELETE ON assessment_review_reads +FOR EACH ROW EXECUTE FUNCTION assessment_review_reads_immutable(); + +CREATE TRIGGER assessment_review_reads_no_truncate +BEFORE TRUNCATE ON assessment_review_reads +FOR EACH STATEMENT EXECUTE FUNCTION assessment_review_reads_immutable(); + +-- +goose Down +-- The audit of operator reads is durable evidence. Rolling the schema back must +-- not remove it as a side effect: an operator exports or resolves it first. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM assessment_review_reads) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_review_reads_retained', + TABLE = 'assessment_review_reads', + MESSAGE = 'assessment review read audit must be retained before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER assessment_review_reads_no_truncate ON assessment_review_reads; +DROP TRIGGER assessment_review_reads_immutable ON assessment_review_reads; +DROP FUNCTION assessment_review_reads_immutable(); +DROP INDEX assessment_review_reads_attempt_idx; +DROP TABLE assessment_review_reads; +DROP TRIGGER assessment_attempt_review_guard ON assessment_attempt_reviews; +DROP FUNCTION assessment_attempt_review_guard(); +DROP TABLE assessment_attempt_reviews; +DROP TRIGGER assessment_answer_observation_count ON assessment_answer_observations; +DROP FUNCTION assessment_answer_observation_count(); +DROP TABLE assessment_answer_family_totals; +DROP TABLE assessment_answer_fingerprint_holders; +DROP TRIGGER assessment_attempt_origin_marks_immutable ON assessment_attempt_origin_marks; +DROP TRIGGER assessment_answer_observations_immutable ON assessment_answer_observations; +DROP FUNCTION assessment_signal_fact_immutable(); +DROP INDEX assessment_attempt_origin_marks_attempt_idx; +DROP TABLE assessment_attempt_origin_marks; +DROP INDEX assessment_answer_observations_match_idx; +DROP TABLE assessment_answer_observations; diff --git a/backend/db/migrations/00034_create_assessment_signal_notice_acknowledgements.sql b/backend/db/migrations/00034_create_assessment_signal_notice_acknowledgements.sql new file mode 100644 index 0000000..09e76d6 --- /dev/null +++ b/backend/db/migrations/00034_create_assessment_signal_notice_acknowledgements.sql @@ -0,0 +1,15 @@ +-- +goose Up +-- A record that a candidate was shown the notice about the collected +-- assessment signals. It is not a consent: no operation reads it to allow or +-- refuse signal storage. One row per account and notice version keeps the time +-- of the first acknowledgement; a changed notice text uses a new version. +CREATE TABLE assessment_signal_notice_acknowledgements ( + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + notice_version integer NOT NULL, + acknowledged_at timestamptz NOT NULL, + CONSTRAINT assessment_signal_notice_acknowledgements_pkey PRIMARY KEY (user_id, notice_version), + CONSTRAINT assessment_signal_notice_acknowledgements_version CHECK (notice_version >= 1) +); + +-- +goose Down +DROP TABLE assessment_signal_notice_acknowledgements; diff --git a/backend/db/migrations/00035_create_skill_evidence.sql b/backend/db/migrations/00035_create_skill_evidence.sql new file mode 100644 index 0000000..cd10965 --- /dev/null +++ b/backend/db/migrations/00035_create_skill_evidence.sql @@ -0,0 +1,314 @@ +-- +goose Up +-- Skill evidence is a projection of immutable assessment results. One fact is +-- one source event; the skills of that event are tags of the fact, so several +-- tags never multiply the fact. A fact is written by the database in the same +-- transaction as the result that qualifies it, and migration backfills the +-- results that already exist. The projection holds no answer, score, item, +-- failure, or anti-cheat data: reads of the evidence never touch the result, +-- attempt, or review tables. + +CREATE TABLE skill_evidence_facts ( + id uuid NOT NULL DEFAULT gen_random_uuid(), + candidate_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + -- A claim is a statement that nothing confirmed separately (trust 0); a + -- measurement is an observed result (trust 1 to 3). Only assessments feed + -- this table today, so every stored fact is a measurement. + kind text NOT NULL, + source_type text NOT NULL, + -- The source event and the immutable result of that event. For an + -- assessment both are the attempt, because a result is keyed by its attempt. + event_id uuid NOT NULL, + result_id uuid NOT NULL, + attribution text NOT NULL, + trust smallint NOT NULL, + -- The grade that was passed, the basis of the measurement, and its + -- calibration, copied from the category decision of the result. + grade text NOT NULL, + basis text NOT NULL, + calibration_status text NOT NULL, + occurred_at timestamptz NOT NULL, + -- The candidate may hide a fact; hiding never edits the result. + visibility text NOT NULL DEFAULT 'visible', + recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(), + -- The transaction that created the fact. Tags are added only in that + -- transaction, so a stored fact is never widened afterwards. + created_txid bigint NOT NULL DEFAULT (pg_current_xact_id()::text::bigint), + CONSTRAINT skill_evidence_facts_pkey PRIMARY KEY (id), + CONSTRAINT skill_evidence_facts_event_key UNIQUE (source_type, event_id), + CONSTRAINT skill_evidence_facts_result_fk FOREIGN KEY (result_id, candidate_id) + REFERENCES assessment_attempt_results (attempt_id, user_id) ON DELETE CASCADE, + CONSTRAINT skill_evidence_facts_kind CHECK (kind IN ('claim', 'measurement')), + CONSTRAINT skill_evidence_facts_source CHECK (source_type IN ('assessment_result')), + CONSTRAINT skill_evidence_facts_attribution CHECK (attribution IN ('personal', 'team_role', 'team_unattributed')), + CONSTRAINT skill_evidence_facts_trust CHECK ( + (kind = 'claim' AND trust = 0) OR (kind = 'measurement' AND trust BETWEEN 1 AND 3) + ), + -- An online assessment has no proctoring, so it never reaches the level of + -- an in-person check. Level 1 is the level without a reliable identity + -- confirmation; level 2 is reserved for a result tied to a confirmed identity. + CONSTRAINT skill_evidence_facts_assessment_shape CHECK ( + source_type <> 'assessment_result' + OR (kind = 'measurement' AND trust BETWEEN 1 AND 2 AND attribution = 'personal' AND event_id = result_id) + ), + CONSTRAINT skill_evidence_facts_grade CHECK (grade IN ('intern', 'junior', 'middle', 'senior')), + CONSTRAINT skill_evidence_facts_basis CHECK (basis IN ('synthetic_demo')), + CONSTRAINT skill_evidence_facts_calibration CHECK (calibration_status IN ('uncalibrated')), + CONSTRAINT skill_evidence_facts_visibility CHECK (visibility IN ('visible', 'hidden')) +); + +CREATE INDEX skill_evidence_facts_candidate_idx +ON skill_evidence_facts (candidate_id, occurred_at DESC, id DESC); + +CREATE TABLE skill_evidence_skills ( + fact_id uuid NOT NULL REFERENCES skill_evidence_facts (id) ON DELETE CASCADE, + skill_code text NOT NULL, + CONSTRAINT skill_evidence_skills_pkey PRIMARY KEY (fact_id, skill_code), + -- The specialization codes of the catalog and the closed technology + -- taxonomy of the anonymous card. + CONSTRAINT skill_evidence_skills_code CHECK ( + skill_code IN ( + 'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre', + 'data_analyst', 'ds_ml', 'information_security', 'qa', + 'go', 'postgresql', 'kafka', 'docker' + ) + ) +); + +-- The single rule that decides which result is qualifying evidence: a real +-- (root or corrective) result of the basic mode, confirmed, and carried by a +-- reviewed category decision that either assigned the grade or left a higher +-- one in force. An express training run, a failed attempt, and a result without +-- a reviewed source never qualify. +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_result_qualifies(source_result assessment_attempt_results) RETURNS boolean +LANGUAGE sql IMMUTABLE AS $$ + SELECT source_result.schema_version = 2 + AND source_result.kind IN ('root', 'corrective') + AND source_result.mode = 'demo_basic' + AND source_result.outcome = 'confirmed' + AND source_result.category_decision ->> 'status' IN ('assigned', 'unchanged') +$$; +-- +goose StatementEnd + +-- A fact must match the immutable result it names, so no write path can store +-- evidence for an express run, a failed attempt, or another candidate. +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_facts_guard_insert() RETURNS trigger +LANGUAGE plpgsql AS $$ +DECLARE + source_result assessment_attempt_results%ROWTYPE; +BEGIN + SELECT * INTO source_result + FROM assessment_attempt_results + WHERE attempt_id = NEW.result_id AND user_id = NEW.candidate_id; + + IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) OR + source_result.category_decision ->> 'attempted_grade' IS DISTINCT FROM NEW.grade OR + source_result.category_decision ->> 'source' IS DISTINCT FROM NEW.basis OR + source_result.category_decision ->> 'calibration_status' IS DISTINCT FROM NEW.calibration_status OR + source_result.decided_at <> NEW.occurred_at THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_source_result', + MESSAGE = 'skill evidence does not match a qualifying assessment result'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER skill_evidence_facts_guard_insert +BEFORE INSERT ON skill_evidence_facts +FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_guard_insert(); + +-- A stored fact never changes except its visibility, and is removed only with +-- its owner or its result. +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_facts_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + ELSIF ROW( + NEW.id, NEW.candidate_id, NEW.kind, NEW.source_type, NEW.event_id, NEW.result_id, + NEW.attribution, NEW.trust, NEW.grade, NEW.basis, NEW.calibration_status, + NEW.occurred_at, NEW.recorded_at, NEW.created_txid + ) IS NOT DISTINCT FROM ROW( + OLD.id, OLD.candidate_id, OLD.kind, OLD.source_type, OLD.event_id, OLD.result_id, + OLD.attribution, OLD.trust, OLD.grade, OLD.basis, OLD.calibration_status, + OLD.occurred_at, OLD.recorded_at, OLD.created_txid + ) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'skill_evidence_facts_immutable', + MESSAGE = 'skill evidence facts are immutable except for their visibility'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER skill_evidence_facts_refuse_change +BEFORE UPDATE OR DELETE ON skill_evidence_facts +FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_refuse_change(); + +-- A fact without a skill cannot be read or matched, so the check runs at +-- commit, after the tags of the same transaction are in place. A fact that the +-- same transaction already removed needs no tag. +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_facts_require_skill() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = NEW.id) AND + NOT EXISTS (SELECT 1 FROM skill_evidence_skills WHERE fact_id = NEW.id) THEN + RAISE EXCEPTION USING + ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_require_skill', + MESSAGE = 'skill evidence fact has no skill'; + END IF; + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER skill_evidence_facts_require_skill +AFTER INSERT ON skill_evidence_facts +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_require_skill(); + +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_skills_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_immutable', + MESSAGE = 'skill evidence tags are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER skill_evidence_skills_refuse_change +BEFORE UPDATE OR DELETE ON skill_evidence_skills +FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_refuse_change(); + +-- A tag joins a fact only in the transaction that created the fact: the +-- skills of an event are fixed when the event is recorded, and a later write +-- cannot widen what an organization may read about it. +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_skills_require_new_fact() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM skill_evidence_facts + WHERE id = NEW.fact_id AND created_txid = pg_current_xact_id()::text::bigint + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_fact_sealed', + MESSAGE = 'skills can only be added in the transaction that created the fact'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER skill_evidence_skills_require_new_fact +BEFORE INSERT ON skill_evidence_skills +FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_require_new_fact(); + +-- Projects one stored result. A result that does not qualify writes nothing, +-- and a repeat writes nothing, so the function serves both the trigger and the +-- backfill. Level 1 is the trust of an online result without a reliable +-- identity confirmation. +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_project_assessment_result(projected_attempt_id uuid) RETURNS void +LANGUAGE plpgsql AS $$ +DECLARE + source_result assessment_attempt_results%ROWTYPE; + new_fact_id uuid; +BEGIN + SELECT * INTO source_result + FROM assessment_attempt_results + WHERE attempt_id = projected_attempt_id; + IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) THEN + RETURN; + END IF; + + INSERT INTO skill_evidence_facts ( + candidate_id, kind, source_type, event_id, result_id, attribution, trust, + grade, basis, calibration_status, occurred_at + ) VALUES ( + source_result.user_id, 'measurement', 'assessment_result', source_result.attempt_id, + source_result.attempt_id, 'personal', 1, + source_result.category_decision ->> 'attempted_grade', + source_result.category_decision ->> 'source', + source_result.category_decision ->> 'calibration_status', + source_result.decided_at + ) + ON CONFLICT (source_type, event_id) DO NOTHING + RETURNING id INTO new_fact_id; + + IF new_fact_id IS NOT NULL THEN + INSERT INTO skill_evidence_skills (fact_id, skill_code) + VALUES (new_fact_id, source_result.category_decision ->> 'specialization'); + END IF; +END; +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE FUNCTION skill_evidence_project_result_trigger() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + PERFORM skill_evidence_project_assessment_result(NEW.attempt_id); + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER skill_evidence_project_result +AFTER INSERT ON assessment_attempt_results +FOR EACH ROW EXECUTE FUNCTION skill_evidence_project_result_trigger(); + +SELECT skill_evidence_project_assessment_result(attempt_id) +FROM assessment_attempt_results +ORDER BY decided_at, attempt_id; + +-- +goose Down +-- The facts are a projection: the results they were derived from stay, and the +-- migration projects them again when it is applied again. Hiding a fact is the +-- candidate's own decision and cannot be derived from a result, so a rollback +-- refuses while any such decision, or any source other than an assessment +-- result, would be lost. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM skill_evidence_facts + WHERE visibility = 'hidden' OR source_type <> 'assessment_result' + ) THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'skill_evidence_retained', + MESSAGE = 'skill evidence uses migration 00035 and must be retained'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER skill_evidence_project_result ON assessment_attempt_results; +DROP FUNCTION skill_evidence_project_result_trigger(); +DROP FUNCTION skill_evidence_project_assessment_result(uuid); +DROP TRIGGER skill_evidence_skills_require_new_fact ON skill_evidence_skills; +DROP FUNCTION skill_evidence_skills_require_new_fact(); +DROP TRIGGER skill_evidence_skills_refuse_change ON skill_evidence_skills; +DROP FUNCTION skill_evidence_skills_refuse_change(); +DROP TRIGGER skill_evidence_facts_require_skill ON skill_evidence_facts; +DROP FUNCTION skill_evidence_facts_require_skill(); +DROP TRIGGER skill_evidence_facts_refuse_change ON skill_evidence_facts; +DROP FUNCTION skill_evidence_facts_refuse_change(); +DROP TRIGGER skill_evidence_facts_guard_insert ON skill_evidence_facts; +DROP FUNCTION skill_evidence_facts_guard_insert(); +DROP FUNCTION skill_evidence_result_qualifies(assessment_attempt_results); +DROP TABLE skill_evidence_skills; +DROP TABLE skill_evidence_facts; diff --git a/backend/db/migrations/00036_allow_synthetic_notification_event.sql b/backend/db/migrations/00036_allow_synthetic_notification_event.sql new file mode 100644 index 0000000..a87a8d1 --- /dev/null +++ b/backend/db/migrations/00036_allow_synthetic_notification_event.sql @@ -0,0 +1,48 @@ +-- The inbox allowlist gains a synthetic event type. It carries no product +-- meaning: it lets the consumer, the read-time visibility check, the list, +-- and the read state run end to end before real producers exist. Each event +-- type is bound to the one source type its content is resolved from. +-- +goose Up +ALTER TABLE notification_inbox_events +DROP CONSTRAINT notification_inbox_events_type_known; + +ALTER TABLE notification_inbox_events +ADD CONSTRAINT notification_inbox_events_type_known CHECK ( + schema_version = 1 + AND ( + (event_type = 'invitation.delivered' AND source_type = 'invitation') + OR ( + event_type = 'notification.synthetic_delivered' + AND source_type = 'organization' + ) + ) +); + +-- A rollback must not silently lose or orphan recipient-visible history. +-- +goose Down +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM notification_inbox_events + WHERE event_type <> 'invitation.delivered' + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'notification_inbox_events_type_known', + TABLE = 'notification_inbox_events', + MESSAGE = 'synthetic notification inbox records must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE notification_inbox_events +DROP CONSTRAINT notification_inbox_events_type_known; + +ALTER TABLE notification_inbox_events +ADD CONSTRAINT notification_inbox_events_type_known CHECK ( + event_type = 'invitation.delivered' + AND schema_version = 1 + AND source_type = 'invitation' +); diff --git a/backend/db/migrations/00037_create_invitations.sql b/backend/db/migrations/00037_create_invitations.sql new file mode 100644 index 0000000..43bc5a3 --- /dev/null +++ b/backend/db/migrations/00037_create_invitations.sql @@ -0,0 +1,349 @@ +-- +goose Up +-- Invitation storage. An invitation names one candidate for one organization. +-- Its terms live in immutable numbered versions: every change of the terms +-- appends the next version, and the invitation row only points at the current +-- one. The salary range is kept in typed columns next to the JSON snapshot, so +-- the database itself refuses a range that breaks the money rules. Amounts are +-- whole rubles, as in the API contract; there are no minor units and no +-- floating-point columns. +-- +-- The candidate column is internal. API responses show the candidate only +-- through the organization-scoped alias that the server derives on every read. +CREATE TABLE invitations ( + id uuid NOT NULL, + organization_id uuid NOT NULL, + candidate_id uuid NOT NULL, + need_id uuid, + need_requirements_version bigint, + state text NOT NULL, + expiry_reason text, + version bigint NOT NULL, + terms_version bigint NOT NULL, + response_period_days smallint NOT NULL, + -- The product policy that allowed the chosen response period. + policy_version_id uuid NOT NULL, + response_deadline_at timestamptz, + salary_raise_used boolean NOT NULL DEFAULT FALSE, + created_by uuid NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + delivered_at timestamptz, + viewed_at timestamptz, + responded_at timestamptz, + CONSTRAINT invitations_pkey PRIMARY KEY (id), + CONSTRAINT invitations_organization_id_id_key UNIQUE (organization_id, id), + CONSTRAINT invitations_organization_fkey FOREIGN KEY (organization_id) + REFERENCES organizations (id) ON DELETE RESTRICT, + -- A candidate with invitations cannot be deleted until a deletion + -- procedure settles them, like an account with consent evidence. + CONSTRAINT invitations_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT invitations_created_by_fkey FOREIGN KEY (created_by) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT invitations_policy_version_fkey FOREIGN KEY (policy_version_id) + REFERENCES policy_versions (id) ON DELETE RESTRICT, + -- The need link is informational and must name a requirements version + -- that the need of the same organization has stored. + CONSTRAINT invitations_need_fkey FOREIGN KEY (organization_id, need_id) + REFERENCES organization_needs (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitations_need_version_fkey FOREIGN KEY ( + organization_id, need_id, need_requirements_version + ) REFERENCES organization_need_versions (organization_id, need_id, version) + ON DELETE RESTRICT, + CONSTRAINT invitations_need_pair CHECK ( + (need_id IS NULL) = (need_requirements_version IS NULL) + ), + CONSTRAINT invitations_state_known CHECK ( + state IN ( + 'draft', 'delivered', 'viewed', 'counter', 'accepted', + 'interview_scheduled', 'interviewed', 'negotiation', + 'terms_agreed', 'no_deal', 'declined', 'expired', 'withdrawn', + 'cancelled_by_candidate' + ) + ), + CONSTRAINT invitations_expiry_reason CHECK ( + (state = 'expired') = (expiry_reason IS NOT NULL) + AND ( + expiry_reason IS NULL + OR expiry_reason IN ('invitation_timeout', 'negotiation_timeout') + ) + ), + CONSTRAINT invitations_version_positive CHECK (version > 0), + CONSTRAINT invitations_terms_version_range CHECK ( + terms_version > 0 AND terms_version <= version + ), + CONSTRAINT invitations_response_period CHECK ( + response_period_days IN (3, 7, 14) + ), + -- The deadline starts with the first delivery and is set together with it. + CONSTRAINT invitations_deadline_with_delivery CHECK ( + (response_deadline_at IS NULL) = (delivered_at IS NULL) + AND (response_deadline_at IS NULL OR response_deadline_at > delivered_at) + ), + -- A draft is invisible to the candidate and has no delivery, view, + -- answer, or raise yet. + CONSTRAINT invitations_draft_is_unsent CHECK ( + state <> 'draft' + OR ( + delivered_at IS NULL + AND viewed_at IS NULL + AND responded_at IS NULL + AND NOT salary_raise_used + ) + ), + CONSTRAINT invitations_timestamps CHECK (updated_at >= created_at) +); + +CREATE TABLE invitation_terms_versions ( + invitation_id uuid NOT NULL, + organization_id uuid NOT NULL, + version bigint NOT NULL, + terms jsonb NOT NULL, + salary_from bigint NOT NULL, + salary_to bigint NOT NULL, + salary_currency text NOT NULL, + salary_period text NOT NULL, + salary_tax_basis text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT invitation_terms_versions_pkey PRIMARY KEY (invitation_id, version), + CONSTRAINT invitation_terms_versions_invitation_fkey FOREIGN KEY ( + organization_id, invitation_id + ) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitation_terms_versions_version_positive CHECK (version > 0), + -- Money rules (PRD FR13) in integer arithmetic: positive bounds that are + -- multiples of 1000, A < B, and a width 2 * (B - A) / (A + B) from 10% to + -- 40%, that is 20 * (B - A) >= A + B and 5 * (B - A) <= A + B. The bounds + -- are capped at 100 000 000 rubles, so no product overflows. + CONSTRAINT invitation_terms_versions_salary_bounds CHECK ( + salary_from BETWEEN 1000 AND 100000000 + AND salary_to BETWEEN 1000 AND 100000000 + AND salary_from % 1000 = 0 + AND salary_to % 1000 = 0 + AND salary_from < salary_to + ), + CONSTRAINT invitation_terms_versions_salary_width CHECK ( + 20 * (salary_to - salary_from) >= salary_from + salary_to + AND 5 * (salary_to - salary_from) <= salary_from + salary_to + ), + CONSTRAINT invitation_terms_versions_salary_basis CHECK ( + salary_currency = 'RUB' + AND salary_period = 'month' + AND salary_tax_basis IN ('net', 'gross') + ), + -- The snapshot is a complete object whose salary equals the typed columns. + -- jsonb::text adds structural whitespace, so the size bound leaves room. + CONSTRAINT invitation_terms_versions_snapshot_shape CHECK ( + jsonb_typeof(terms) = 'object' + AND terms ?& ARRAY[ + 'role_title', 'specialization', 'grade', 'offer_type', 'tasks', + 'team', 'tech_stack', 'work_formats', 'location', + 'communication_method', 'salary', 'package' + ] + AND jsonb_typeof(terms -> 'salary') = 'object' + AND CASE + WHEN jsonb_typeof(terms #> '{salary,salary_from}') = 'number' + AND jsonb_typeof(terms #> '{salary,salary_to}') = 'number' + THEN (terms #>> '{salary,salary_from}') = salary_from::text + AND (terms #>> '{salary,salary_to}') = salary_to::text + ELSE FALSE + END + AND (terms #>> '{salary,currency}') = salary_currency + AND (terms #>> '{salary,period}') = salary_period + AND (terms #>> '{salary,tax_basis}') = salary_tax_basis + AND octet_length(terms::text) <= 131072 + ) +); + +-- The current terms version must exist for the same invitation. Deferral lets +-- creation insert the invitation and its first terms in one transaction. +ALTER TABLE invitations + ADD CONSTRAINT invitations_current_terms_fkey + FOREIGN KEY (id, terms_version) + REFERENCES invitation_terms_versions (invitation_id, version) + DEFERRABLE INITIALLY DEFERRED; + +-- The changed fields of an audit event are a duplicate-free subset of the +-- editable parts of a draft. +-- +goose StatementBegin +CREATE FUNCTION invitation_changed_fields_are_valid(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + fields <@ ARRAY['terms', 'need', 'response_period_days']::text [] + AND array_position(fields, NULL) IS NULL + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- One audit event per committed invitation version. The event names the +-- actor and what changed, never the content: the terms are in their own +-- immutable versions. +CREATE TABLE invitation_events ( + id uuid NOT NULL, + invitation_id uuid NOT NULL, + organization_id uuid NOT NULL, + version bigint NOT NULL, + terms_version bigint NOT NULL, + kind text NOT NULL, + actor_id uuid NOT NULL, + changed_fields text [] NOT NULL, + occurred_at timestamptz NOT NULL, + CONSTRAINT invitation_events_pkey PRIMARY KEY (id), + CONSTRAINT invitation_events_version_key UNIQUE (invitation_id, version), + CONSTRAINT invitation_events_invitation_fkey FOREIGN KEY ( + organization_id, invitation_id + ) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitation_events_actor_fkey FOREIGN KEY (actor_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT invitation_events_terms_version_fkey FOREIGN KEY ( + invitation_id, terms_version + ) REFERENCES invitation_terms_versions (invitation_id, version) + ON DELETE RESTRICT, + CONSTRAINT invitation_events_version_positive CHECK ( + version > 0 AND terms_version > 0 AND terms_version <= version + ), + CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated') + ), + CONSTRAINT invitation_events_creation_is_first CHECK ( + (kind = 'draft_created') = (version = 1) + ), + CONSTRAINT invitation_events_changed_fields CHECK ( + invitation_changed_fields_are_valid(changed_fields) + ) +); + +-- Original response of an idempotent create, kept beside the generic +-- idempotency record and removed with it after the 24-hour replay window. +-- The live invitation is intentionally not a foreign key. +CREATE TABLE invitation_creation_results ( + scope_hash bytea NOT NULL, + snapshot jsonb NOT NULL, + CONSTRAINT invitation_creation_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_creation_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_creation_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_creation_results_snapshot_bounded CHECK ( + jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 196608 + ) +); + +-- Newest-first list of one organization. +CREATE INDEX invitations_organization_created_idx +ON invitations (organization_id, created_at DESC, id DESC); + +-- Pair rules of the organization and the candidate, such as the pause after a +-- decline, read the invitations of one pair. +CREATE INDEX invitations_organization_candidate_idx +ON invitations (organization_id, candidate_id, created_at DESC); + +-- The candidate's inbox reads the invitations that were delivered to them. +CREATE INDEX invitations_candidate_delivered_idx +ON invitations (candidate_id, delivered_at DESC, id DESC) +WHERE delivered_at IS NOT NULL; + +-- Identity and history rules. An invitation is never deleted, its identity +-- never changes, every committed change advances the version by one, a terms +-- version advances by at most one, and a raise or a deadline is never undone. +-- TRUNCATE remains available to reset isolated integration databases. +-- +goose StatementBegin +CREATE FUNCTION invitations_guard_update() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.id IS DISTINCT FROM OLD.id + OR NEW.organization_id IS DISTINCT FROM OLD.organization_id + OR NEW.candidate_id IS DISTINCT FROM OLD.candidate_id + OR NEW.created_by IS DISTINCT FROM OLD.created_by + OR NEW.created_at IS DISTINCT FROM OLD.created_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_identity_immutable', + TABLE = 'invitations', + MESSAGE = 'invitation identity is immutable'; + END IF; + IF NEW.version <> OLD.version + 1 + OR (NEW.terms_version <> OLD.terms_version AND NEW.terms_version <> OLD.terms_version + 1) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_version_step', + TABLE = 'invitations', + MESSAGE = 'invitation versions advance by exactly one step'; + END IF; + IF (OLD.salary_raise_used AND NOT NEW.salary_raise_used) + OR (OLD.delivered_at IS NOT NULL AND ( + NEW.delivered_at IS DISTINCT FROM OLD.delivered_at + OR NEW.response_deadline_at IS DISTINCT FROM OLD.response_deadline_at + OR NEW.response_period_days IS DISTINCT FROM OLD.response_period_days + )) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_history_immutable', + TABLE = 'invitations', + MESSAGE = 'a raise, a delivery, and a deadline are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_guard_update +BEFORE UPDATE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_guard_update(); + +-- Terms versions and audit events are append-only. +-- +goose StatementBegin +CREATE FUNCTION invitations_refuse_history_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = TG_TABLE_NAME || '_immutable', + TABLE = TG_TABLE_NAME, + MESSAGE = 'invitation history is append-only: add a new version instead'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_refuse_delete +BEFORE DELETE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +CREATE TRIGGER invitation_terms_versions_immutable +BEFORE UPDATE OR DELETE ON invitation_terms_versions +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +CREATE TRIGGER invitation_events_immutable +BEFORE UPDATE OR DELETE ON invitation_events +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +-- +goose Down +-- A rollback must not silently remove stored invitations or their history. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitations) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_retained', + TABLE = 'invitations', + MESSAGE = 'invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TABLE invitation_creation_results; +DROP TABLE invitation_events; +ALTER TABLE invitations DROP CONSTRAINT invitations_current_terms_fkey; +DROP TABLE invitation_terms_versions; +DROP TABLE invitations; +DROP FUNCTION invitation_changed_fields_are_valid(text []); +DROP FUNCTION invitations_refuse_history_change(); +DROP FUNCTION invitations_guard_update(); diff --git a/backend/db/migrations/00038_send_invitations.sql b/backend/db/migrations/00038_send_invitations.sql new file mode 100644 index 0000000..5913d68 --- /dev/null +++ b/backend/db/migrations/00038_send_invitations.sql @@ -0,0 +1,117 @@ +-- +goose Up +-- Sending an invitation. One transaction moves a draft to `delivered`, starts +-- the response deadline, charges the organization quota, appends the audit +-- event, and writes the outbox events of the notification. The send itself is +-- never a stored state: the audit event of the step is `delivered`, and it +-- changes none of the editable draft fields. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated', 'delivered') +); + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_delivery_changes_no_field CHECK ( + kind <> 'delivered' OR cardinality(changed_fields) = 0 +); + +-- Invitation quota usage now names a stored invitation of the same +-- organization, so a charge cannot exist without the invitation it paid for. +-- Before sending existed nothing in the product wrote this table; a row that +-- names no invitation is reported instead of being dropped. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM company_invitation_quota_usage AS usage + WHERE NOT EXISTS ( + SELECT 1 + FROM invitations + WHERE + invitations.organization_id = usage.organization_id + AND invitations.id = usage.invitation_id + ) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'foreign_key_violation', + CONSTRAINT = 'company_invitation_quota_usage_invitation_fkey', + TABLE = 'company_invitation_quota_usage', + MESSAGE = 'invitation quota usage must name stored invitations'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE company_invitation_quota_usage +ADD CONSTRAINT company_invitation_quota_usage_invitation_fkey +FOREIGN KEY (organization_id, invitation_id) +REFERENCES invitations (organization_id, id) ON DELETE RESTRICT; + +-- Outcome of an idempotent send, kept beside the generic idempotency record +-- and removed with it after the 24-hour replay window. A successful send +-- keeps the original response; a missing invitation and a state conflict +-- keep only the outcome, as the public contract stores them under the key. +-- The invitation is intentionally not a foreign key: the outcome of a missing +-- invitation names an identifier that does not exist. +CREATE TABLE invitation_send_results ( + scope_hash bytea NOT NULL, + organization_id uuid NOT NULL, + invitation_id uuid NOT NULL, + outcome text NOT NULL, + snapshot jsonb, + CONSTRAINT invitation_send_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_send_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_send_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_send_results_outcome CHECK ( + ( + outcome = 'sent' + AND snapshot IS NOT NULL + AND jsonb_typeof(snapshot) = 'object' + AND octet_length(snapshot::text) <= 196608 + ) + OR ( + outcome IN ('not_found', 'state_conflict') + AND snapshot IS NULL + ) + ) +); + +-- +goose Down +-- A rollback must not silently remove delivery history or a stored outcome. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'delivered') + OR EXISTS (SELECT 1 FROM invitation_send_results) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_deliveries_retained', + TABLE = 'invitation_events', + MESSAGE = 'sent invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TABLE invitation_send_results; + +ALTER TABLE company_invitation_quota_usage +DROP CONSTRAINT company_invitation_quota_usage_invitation_fkey; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_delivery_changes_no_field; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated') +); diff --git a/backend/db/migrations/00039_answer_invitations.sql b/backend/db/migrations/00039_answer_invitations.sql new file mode 100644 index 0000000..62c12fb --- /dev/null +++ b/backend/db/migrations/00039_answer_invitations.sql @@ -0,0 +1,216 @@ +-- +goose Up +-- The candidate's view and decline of a delivered invitation. The view moves +-- `delivered` to `viewed` and keeps the deadline. The decline moves +-- `delivered`, `viewed`, or the planned `counter` to the terminal `declined` +-- and stores the structured reason and the optional comment in their own +-- table, which only the candidate reads back. Neither creates a consent or a +-- contact grant. Each appends an audit event that names the version and the +-- actor and holds no reason or comment. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated', 'delivered', 'viewed', 'declined') +); + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK ( + kind NOT IN ('viewed', 'declined') OR cardinality(changed_fields) = 0 +); + +-- A viewed invitation records its view, a declined one its answer, and +-- neither precedes the delivery. A delivered invitation has neither yet. +ALTER TABLE invitations +ADD CONSTRAINT invitations_answer_matches_state CHECK ( + (state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL)) + AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL)) + AND (state <> 'declined' OR responded_at IS NOT NULL) + AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at)) + AND ( + responded_at IS NULL + OR (delivered_at IS NOT NULL AND responded_at >= delivered_at) + ) +); + +-- The structured decline of one invitation. The organization never reads +-- this table: a reason such as `salary` would tell it that the hidden minimum +-- is above the range. The comment is the candidate's private text. +CREATE TABLE invitation_declines ( + invitation_id uuid NOT NULL, + organization_id uuid NOT NULL, + reason text NOT NULL, + comment text, + declined_at timestamptz NOT NULL, + CONSTRAINT invitation_declines_pkey PRIMARY KEY (invitation_id), + CONSTRAINT invitation_declines_invitation_fkey FOREIGN KEY ( + organization_id, invitation_id + ) REFERENCES invitations (organization_id, id) ON DELETE RESTRICT, + CONSTRAINT invitation_declines_reason_known CHECK ( + reason IN ( + 'salary', 'tasks', 'stack', 'work_format', 'package', 'company', + 'not_looking', 'other_offer', 'other' + ) + ), + -- The contract bound of InvitationDeclineComment: 1 to 500 characters, + -- at least one of them not white space. + CONSTRAINT invitation_declines_comment_bounded CHECK ( + comment IS NULL + OR ( + char_length(comment) BETWEEN 1 AND 500 + AND comment ~ '[^[:space:]]' + ) + ) +); + +-- Outcome of an idempotent decline, kept beside the generic idempotency +-- record and removed with it after the 24-hour replay window. It holds no +-- copy of the response: a declined invitation and its decline never change, +-- so a replay rebuilds the same answer, and the comment is stored once. The +-- invitation is intentionally not a foreign key: the outcome of a missing +-- invitation names an identifier that does not exist. +CREATE TABLE invitation_decline_results ( + scope_hash bytea NOT NULL, + invitation_id uuid NOT NULL, + outcome text NOT NULL, + CONSTRAINT invitation_decline_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_decline_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_decline_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_decline_results_outcome CHECK ( + outcome IN ('declined', 'not_found', 'state_conflict') + ) +); + +-- A view and an answer are never undone or moved, and a declined invitation +-- never leaves its terminal state. +-- +goose StatementBegin +CREATE FUNCTION invitations_guard_answer() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at) + OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at) + OR (OLD.state = 'declined' AND NEW.state <> 'declined') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_answer_immutable', + TABLE = 'invitations', + MESSAGE = 'a view, an answer, and a decline are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_guard_answer +BEFORE UPDATE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_guard_answer(); + +-- A decline row describes the declined invitation it belongs to, answered at +-- the moment of the decline. +-- +goose StatementBegin +CREATE FUNCTION invitation_declines_match_invitation() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM invitations + WHERE + invitations.organization_id = NEW.organization_id + AND invitations.id = NEW.invitation_id + AND invitations.state = 'declined' + AND invitations.responded_at = NEW.declined_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_declines_match_invitation', + TABLE = 'invitation_declines', + MESSAGE = 'a decline belongs to a declined invitation'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitation_declines_match_invitation +BEFORE INSERT ON invitation_declines +FOR EACH ROW EXECUTE FUNCTION invitation_declines_match_invitation(); + +CREATE TRIGGER invitation_declines_immutable +BEFORE UPDATE OR DELETE ON invitation_declines +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +-- Every declined invitation has its decline by the end of the transaction +-- that declined it. +-- +goose StatementBegin +CREATE FUNCTION invitations_require_decline() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM invitation_declines + WHERE + invitation_declines.organization_id = NEW.organization_id + AND invitation_declines.invitation_id = NEW.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_decline_recorded', + TABLE = 'invitations', + MESSAGE = 'a declined invitation records its decline'; + END IF; + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER invitations_require_decline +AFTER UPDATE ON invitations +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +WHEN (new.state = 'declined' AND old.state <> 'declined') +EXECUTE FUNCTION invitations_require_decline(); + +-- +goose Down +-- A rollback must not silently remove a view, a decline, or a stored outcome. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind IN ('viewed', 'declined')) + OR EXISTS (SELECT 1 FROM invitations WHERE viewed_at IS NOT NULL OR state = 'declined') + OR EXISTS (SELECT 1 FROM invitation_declines) + OR EXISTS (SELECT 1 FROM invitation_decline_results) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_answers_retained', + TABLE = 'invitation_events', + MESSAGE = 'viewed and declined invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER invitations_require_decline ON invitations; +DROP TRIGGER invitations_guard_answer ON invitations; +DROP TABLE invitation_decline_results; +DROP TABLE invitation_declines; +DROP FUNCTION invitations_require_decline(); +DROP FUNCTION invitation_declines_match_invitation(); +DROP FUNCTION invitations_guard_answer(); + +ALTER TABLE invitations +DROP CONSTRAINT invitations_answer_matches_state; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_answer_changes_no_field; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated', 'delivered') +); diff --git a/backend/db/migrations/00040_accept_invitations.sql b/backend/db/migrations/00040_accept_invitations.sql new file mode 100644 index 0000000..b76f397 --- /dev/null +++ b/backend/db/migrations/00040_accept_invitations.sql @@ -0,0 +1,347 @@ +-- +goose Up +-- The candidate's acceptance of the current terms with the consent C4. One +-- transaction moves a delivered or viewed invitation to `accepted` before its +-- deadline, records the consent C4 in the consent ledger, stores the contact +-- grant that covers exactly the selected fields, and appends the audit event. +-- The acceptance never changes the publication (C2) and never lifts a hiding: +-- a grant alone does not make the contacts readable, and the read model shows +-- whether the organization may read them now. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ( + 'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined', + 'accepted' + ) +); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_answer_changes_no_field; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK ( + kind NOT IN ('viewed', 'declined', 'accepted') OR cardinality(changed_fields) = 0 +); + +-- An accepted invitation records its answer, as a declined one does. The +-- acceptance from `delivered` leaves the view empty. +ALTER TABLE invitations +DROP CONSTRAINT invitations_answer_matches_state; + +ALTER TABLE invitations +ADD CONSTRAINT invitations_answer_matches_state CHECK ( + (state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL)) + AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL)) + AND (state NOT IN ('declined', 'accepted') OR responded_at IS NOT NULL) + AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at)) + AND ( + responded_at IS NULL + OR (delivered_at IS NOT NULL AND responded_at >= delivered_at) + ) +); + +-- The contact grant names the invitation together with its candidate, so the +-- grant can only belong to the candidate the invitation was addressed to. +ALTER TABLE invitations +ADD CONSTRAINT invitations_organization_id_id_candidate_id_key UNIQUE ( + organization_id, id, candidate_id +); + +-- A grant names exactly the C4 record of its acceptance: the same subject, +-- organization, invitation, and terms version. The record stays a ledger row +-- of its own and does not reference the invitation tables, which the ledger +-- migration leaves to a later change. +ALTER TABLE consent_records +ADD CONSTRAINT consent_records_contact_scope_key UNIQUE ( + id, subject_id, organization_id, invitation_id, invitation_terms_version +); + +-- The contact grant of one accepted invitation. It holds kinds only, never +-- contact values. The grant is created by the acceptance next to its C4 record +-- and the accepted state. Its revocation stamp is reserved for the revocation +-- procedure of a later change, and this migration never sets it. +CREATE TABLE contact_grants ( + id uuid NOT NULL, + organization_id uuid NOT NULL, + candidate_id uuid NOT NULL, + source_invitation_id uuid NOT NULL, + consent_record_id uuid NOT NULL, + terms_version bigint NOT NULL, + fields text [] NOT NULL, + consent_text_version text NOT NULL, + granted_at timestamptz NOT NULL, + revoked_at timestamptz, + revocation_reason text, + CONSTRAINT contact_grants_pkey PRIMARY KEY (id), + -- One grant per accepted invitation, and one per consent record. + CONSTRAINT contact_grants_source_invitation_key UNIQUE (source_invitation_id), + CONSTRAINT contact_grants_consent_record_key UNIQUE (consent_record_id), + CONSTRAINT contact_grants_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE RESTRICT, + CONSTRAINT contact_grants_invitation_fkey FOREIGN KEY ( + organization_id, source_invitation_id, candidate_id + ) REFERENCES invitations (organization_id, id, candidate_id) ON DELETE RESTRICT, + CONSTRAINT contact_grants_terms_fkey FOREIGN KEY ( + source_invitation_id, terms_version + ) REFERENCES invitation_terms_versions (invitation_id, version) ON DELETE RESTRICT, + CONSTRAINT contact_grants_consent_fkey FOREIGN KEY ( + consent_record_id, + candidate_id, + organization_id, + source_invitation_id, + terms_version + ) REFERENCES consent_records ( + id, + subject_id, + organization_id, + invitation_id, + invitation_terms_version + ) ON DELETE RESTRICT, + CONSTRAINT contact_grants_terms_version_positive CHECK (terms_version > 0), + CONSTRAINT contact_grants_fields_canonical CHECK ( + consent_field_set_is_canonical(fields) + ), + CONSTRAINT contact_grants_consent_text_version_format CHECK ( + consent_text_version ~ '^[A-Za-z0-9._-]{1,64}$' + ), + CONSTRAINT contact_grants_revocation_stamp CHECK ( + (revoked_at IS NULL) = (revocation_reason IS NULL) + AND ( + revocation_reason IS NULL + OR revocation_reason IN ( + 'consent_revoked', 'participation_cancelled', 'visibility_closed' + ) + ) + AND (revoked_at IS NULL OR revoked_at >= granted_at) + ) +); + +-- The grant of an organization's invitations is read for one candidate while +-- the grant is active. +CREATE INDEX contact_grants_organization_candidate_active_idx +ON contact_grants (organization_id, candidate_id) +WHERE revoked_at IS NULL; + +-- Outcome of an idempotent acceptance, kept beside the generic idempotency +-- record and removed with it after the 24-hour replay window. An accepted +-- invitation keeps its answer and its grant, so a replay rebuilds the response +-- from them and the outcome holds only the invitation and the result. +CREATE TABLE invitation_accept_results ( + scope_hash bytea NOT NULL, + invitation_id uuid NOT NULL, + outcome text NOT NULL, + CONSTRAINT invitation_accept_results_pkey PRIMARY KEY (scope_hash), + CONSTRAINT invitation_accept_results_idempotency_fkey FOREIGN KEY ( + scope_hash + ) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE, + CONSTRAINT invitation_accept_results_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT invitation_accept_results_outcome CHECK ( + outcome IN ('accepted', 'not_found', 'state_conflict') + ) +); + +-- A view, an answer, and an acceptance are never undone, and a declined or +-- accepted invitation never returns to an earlier state. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION invitations_guard_answer() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at) + OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at) + OR (OLD.state = 'declined' AND NEW.state <> 'declined') + OR (OLD.state = 'accepted' AND NEW.state IN ('draft', 'delivered', 'viewed', 'counter', 'declined')) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_answer_immutable', + TABLE = 'invitations', + MESSAGE = 'a view, an answer, a decline, and an acceptance are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +-- The grant must agree with its C4 record: the fields, the text version, and +-- the grant time are the record's own, so a grant cannot cover a field its +-- consent did not name. +-- +goose StatementBegin +CREATE FUNCTION contact_grants_match_consent() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM consent_records AS record + WHERE + record.id = NEW.consent_record_id + AND record.purpose = 'c4' + AND record.field_set = NEW.fields + AND record.text_version = NEW.consent_text_version + AND record.granted_at = NEW.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'contact_grants_match_consent', + TABLE = 'contact_grants', + MESSAGE = 'a contact grant agrees with its consent C4 record'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER contact_grants_match_consent +BEFORE INSERT ON contact_grants +FOR EACH ROW EXECUTE FUNCTION contact_grants_match_consent(); + +-- A grant changes only by its one revocation stamp, which is set once. Every +-- other change, and every delete, is refused. +-- +goose StatementBegin +CREATE FUNCTION contact_grants_guard_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.revoked_at IS NOT NULL + OR NEW.revoked_at IS NULL + OR ( + NEW.id, NEW.organization_id, NEW.candidate_id, NEW.source_invitation_id, + NEW.consent_record_id, NEW.terms_version, NEW.fields, + NEW.consent_text_version, NEW.granted_at + ) IS DISTINCT FROM ( + OLD.id, OLD.organization_id, OLD.candidate_id, OLD.source_invitation_id, + OLD.consent_record_id, OLD.terms_version, OLD.fields, + OLD.consent_text_version, OLD.granted_at + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'contact_grants_immutable', + TABLE = 'contact_grants', + MESSAGE = 'contact grants are append-only: only an active grant can be revoked, once'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER contact_grants_guard_change +BEFORE UPDATE ON contact_grants +FOR EACH ROW EXECUTE FUNCTION contact_grants_guard_change(); + +CREATE TRIGGER contact_grants_refuse_delete +BEFORE DELETE ON contact_grants +FOR EACH ROW EXECUTE FUNCTION invitations_refuse_history_change(); + +-- An accepted invitation has its contact grant by the end of the transaction +-- that accepted it. +-- +goose StatementBegin +CREATE FUNCTION invitations_require_contact_grant() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM contact_grants + WHERE + contact_grants.organization_id = NEW.organization_id + AND contact_grants.source_invitation_id = NEW.id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_acceptance_recorded', + TABLE = 'invitations', + MESSAGE = 'an accepted invitation records its contact grant'; + END IF; + RETURN NULL; +END; +$$; +-- +goose StatementEnd + +CREATE CONSTRAINT TRIGGER invitations_require_contact_grant +AFTER UPDATE ON invitations +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW +WHEN (new.state = 'accepted' AND old.state <> 'accepted') +EXECUTE FUNCTION invitations_require_contact_grant(); + +-- +goose Down +-- A rollback must not silently remove an acceptance, its consent, or its grant. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'accepted') + OR EXISTS (SELECT 1 FROM invitations WHERE state = 'accepted') + OR EXISTS (SELECT 1 FROM contact_grants) + OR EXISTS (SELECT 1 FROM consent_records WHERE purpose = 'c4') + OR EXISTS (SELECT 1 FROM invitation_accept_results) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_acceptances_retained', + TABLE = 'invitation_events', + MESSAGE = 'accepted invitations and their consents must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER invitations_require_contact_grant ON invitations; +DROP FUNCTION invitations_require_contact_grant(); +DROP TABLE invitation_accept_results; +DROP TABLE contact_grants; +DROP FUNCTION contact_grants_guard_change(); +DROP FUNCTION contact_grants_match_consent(); + +ALTER TABLE consent_records +DROP CONSTRAINT consent_records_contact_scope_key; + +ALTER TABLE invitations +DROP CONSTRAINT invitations_organization_id_id_candidate_id_key; + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION invitations_guard_answer() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF (OLD.viewed_at IS NOT NULL AND NEW.viewed_at IS DISTINCT FROM OLD.viewed_at) + OR (OLD.responded_at IS NOT NULL AND NEW.responded_at IS DISTINCT FROM OLD.responded_at) + OR (OLD.state = 'declined' AND NEW.state <> 'declined') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_answer_immutable', + TABLE = 'invitations', + MESSAGE = 'a view, an answer, and a decline are never undone'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE invitations +DROP CONSTRAINT invitations_answer_matches_state; + +ALTER TABLE invitations +ADD CONSTRAINT invitations_answer_matches_state CHECK ( + (state <> 'delivered' OR (viewed_at IS NULL AND responded_at IS NULL)) + AND (state <> 'viewed' OR (viewed_at IS NOT NULL AND responded_at IS NULL)) + AND (state <> 'declined' OR responded_at IS NOT NULL) + AND (viewed_at IS NULL OR (delivered_at IS NOT NULL AND viewed_at >= delivered_at)) + AND ( + responded_at IS NULL + OR (delivered_at IS NOT NULL AND responded_at >= delivered_at) + ) +); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_answer_changes_no_field; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_answer_changes_no_field CHECK ( + kind NOT IN ('viewed', 'declined') OR cardinality(changed_fields) = 0 +); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ('draft_created', 'draft_updated', 'delivered', 'viewed', 'declined') +); diff --git a/backend/db/migrations/00041_create_holdings.sql b/backend/db/migrations/00041_create_holdings.sql new file mode 100644 index 0000000..99aee4a --- /dev/null +++ b/backend/db/migrations/00041_create_holdings.sql @@ -0,0 +1,134 @@ +-- +goose Up +-- Holdings group the organizations that one account founded, the way the +-- divisions of one company belong to one parent. A holding has no profile and +-- grants no right. It only names the scope of the E0 quota pool: the E0 +-- organizations of one holding share one pool, so creating more organizations +-- does not multiply the unverified allowance. An organization at E1 or above +-- keeps its own pool and does not use its holding for quotas. +-- +-- A holding belongs to its founder account, the account that created its first +-- organization. Every organization belongs to exactly one holding. Holdings of +-- different founders are never merged. +CREATE TABLE holdings ( + -- Internal identifier, never shown by the API. The application creates it + -- as UUIDv7; the backfill below uses a random UUID. + id uuid NOT NULL, + founder_account_id uuid NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT holdings_pkey PRIMARY KEY (id), + -- One holding per founder. A second creation of the same account that + -- races the first waits on this key and then reads the stored holding. + CONSTRAINT holdings_founder_account_id_key UNIQUE (founder_account_id), + CONSTRAINT holdings_founder_account_id_fkey FOREIGN KEY ( + founder_account_id + ) REFERENCES users (id) ON DELETE RESTRICT +); + +-- The backfill and the NOT NULL constraint must see every organization and +-- membership. Writers of both tables wait until this migration commits. +LOCK TABLE organizations, memberships IN SHARE ROW EXCLUSIVE MODE; + +-- Refuses an organization without any membership, because its founder cannot +-- be found. Creation stores the owner membership in the same transaction as +-- the organization, and no statement deletes memberships, so an existing +-- database should never reach this check. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM organizations AS organization + WHERE NOT EXISTS ( + SELECT 1 + FROM memberships AS membership + WHERE membership.organization_id = organization.id + ) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'organizations_founder_required', + TABLE = 'organizations', + MESSAGE = 'an organization without a membership has no founder for its holding'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE organizations ADD COLUMN holding_id uuid; + +-- The founder of an organization is the account of its earliest membership. +-- Creation inserts the organization and its owner membership in one +-- transaction, and a membership cannot exist before its organization, so the +-- earliest membership is the creator's. Ties are broken by identifier. A holding +-- is dated by the earliest creation of its founder. +WITH founders AS ( + SELECT DISTINCT ON (membership.organization_id) + membership.organization_id, + membership.user_id + FROM memberships AS membership + ORDER BY membership.organization_id, membership.created_at, membership.id +) + +INSERT INTO holdings (id, founder_account_id, created_at) +SELECT + gen_random_uuid(), + founders.user_id, + min(organization.created_at) +FROM founders +INNER JOIN organizations AS organization ON organization.id = founders.organization_id +GROUP BY founders.user_id; + +WITH founders AS ( + SELECT DISTINCT ON (membership.organization_id) + membership.organization_id, + membership.user_id + FROM memberships AS membership + ORDER BY membership.organization_id, membership.created_at, membership.id +) + +UPDATE organizations AS organization +SET holding_id = holding.id +FROM founders +INNER JOIN holdings AS holding ON holding.founder_account_id = founders.user_id +WHERE founders.organization_id = organization.id; + +ALTER TABLE organizations ALTER COLUMN holding_id SET NOT NULL; + +ALTER TABLE organizations +ADD CONSTRAINT organizations_holding_id_fkey FOREIGN KEY (holding_id) +REFERENCES holdings (id) ON DELETE RESTRICT; + +-- Serves the pool of an E0 organization, which reads the organizations of its +-- holding, and the foreign key. +CREATE INDEX organizations_holding_id_idx ON organizations (holding_id); + +-- +goose Down +-- A rollback removes the grouping of organizations into holdings. It refuses +-- while a holding groups several organizations, because the schema without +-- holdings would count their E0 quotas separately and could not keep the pool +-- they share. The lock stops a concurrent creation from joining a holding +-- between the check and the removal. +LOCK TABLE organizations IN SHARE ROW EXCLUSIVE MODE; + +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM organizations + GROUP BY holding_id + HAVING count(*) > 1 + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'organizations_holding_grouped', + TABLE = 'organizations', + MESSAGE = 'holdings with several organizations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE organizations DROP COLUMN holding_id; + +DROP TABLE holdings; diff --git a/backend/db/migrations/00042_index_contact_grants_by_candidate.sql b/backend/db/migrations/00042_index_contact_grants_by_candidate.sql new file mode 100644 index 0000000..de2ad47 --- /dev/null +++ b/backend/db/migrations/00042_index_contact_grants_by_candidate.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- A visibility change of the whole profile closes every active grant of one +-- candidate: the revocation of C2 and the closing of the publication. The +-- existing active index leads with the organization, so it cannot serve that +-- lookup. The index holds no data and only speeds up the closing statement. +CREATE INDEX contact_grants_candidate_active_idx +ON contact_grants (candidate_id) +WHERE revoked_at IS NULL; + +-- +goose Down +-- The index holds no data, so a rollback drops only the lookup it provides. +DROP INDEX contact_grants_candidate_active_idx; diff --git a/backend/db/migrations/00043_expire_invitations.sql b/backend/db/migrations/00043_expire_invitations.sql new file mode 100644 index 0000000..164c832 --- /dev/null +++ b/backend/db/migrations/00043_expire_invitations.sql @@ -0,0 +1,152 @@ +-- +goose Up +-- The pending limit per need, the pause after a decline, and the expiry at the +-- response deadline. A delivered or viewed invitation whose deadline has passed +-- moves to `expired` with the reason `invitation_timeout`. Nothing else changes +-- with it: no consent, no contact grant, and no organization quota is returned. +-- The expiry is written by a scheduled job, which the send schedules for every +-- delivery at its deadline, and by the candidate commands that find the +-- deadline passed. The system performs the expiry, so its audit event names no +-- actor. +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ( + 'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined', + 'accepted', 'expired' + ) +); + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_expiry_changes_no_field CHECK ( + kind <> 'expired' OR cardinality(changed_fields) = 0 +); + +-- Only the expiry is a server change, so only its event may lack an actor. +ALTER TABLE invitation_events +ALTER COLUMN actor_id DROP NOT NULL; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_system_actor CHECK ( + (kind = 'expired') = (actor_id IS NULL) +); + +-- Only a delivered or viewed invitation expires, and the expiry is not +-- recorded before the deadline it passed. The application compares the clock +-- with the deadline; this trigger keeps a row changed outside the application +-- from skipping either rule. An expiry without its reason is left to the +-- check constraint invitations_expiry_reason, which runs after this trigger. +-- +goose StatementBegin +CREATE FUNCTION invitations_guard_expiry() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.state = 'expired' AND NEW.expiry_reason IS NOT NULL + AND OLD.state IS DISTINCT FROM NEW.state THEN + IF OLD.state NOT IN ('delivered', 'viewed') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_expiry_from_pending', + TABLE = 'invitations', + MESSAGE = 'only a delivered or viewed invitation expires'; + END IF; + IF NEW.updated_at < OLD.response_deadline_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitations_expiry_after_deadline', + TABLE = 'invitations', + MESSAGE = 'an invitation expires at or after its response deadline'; + END IF; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER invitations_guard_expiry +BEFORE UPDATE ON invitations +FOR EACH ROW EXECUTE FUNCTION invitations_guard_expiry(); + +-- The invitations that wait for an answer under one need of an organization: +-- the pending limit counts them. +CREATE INDEX invitations_pending_need_idx +ON invitations (organization_id, need_id) +WHERE need_id IS NOT NULL AND state IN ('delivered', 'viewed', 'counter'); + +-- The latest decline of one candidate by one organization, which starts the +-- pause before the next invitation of that pair. +CREATE INDEX invitations_declined_pair_idx +ON invitations (organization_id, candidate_id, responded_at DESC) +WHERE state = 'declined'; + +-- Invitations delivered before this migration have no deadline job yet. The +-- job's key is the invitation identifier, so the schedule is idempotent, and +-- its due time is the deadline that the invitation already stores. +INSERT INTO scheduled_jobs ( + kind, + dedup_key, + payload, + due_at, + available_at, + status, + attempts +) +SELECT + 'invitation.response_deadline', + invitations.id::text, + jsonb_build_object('invitation_id', invitations.id::text), + invitations.response_deadline_at AS due_at, + invitations.response_deadline_at AS available_at, + 'pending', + 0 +FROM invitations +WHERE + invitations.state IN ('delivered', 'viewed') + AND invitations.response_deadline_at IS NOT NULL +ON CONFLICT (kind, dedup_key) DO NOTHING; + +-- +goose Down +-- A rollback must not hide an expiry that already happened, and it must not +-- leave the deadline jobs without a handler. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM invitation_events WHERE kind = 'expired') + OR EXISTS (SELECT 1 FROM invitations WHERE state = 'expired') THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'invitation_expiries_retained', + TABLE = 'invitation_events', + MESSAGE = 'expired invitations must be resolved before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DELETE FROM scheduled_jobs WHERE kind = 'invitation.response_deadline'; + +DROP INDEX invitations_declined_pair_idx; +DROP INDEX invitations_pending_need_idx; + +DROP TRIGGER invitations_guard_expiry ON invitations; +DROP FUNCTION invitations_guard_expiry(); + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_system_actor; + +ALTER TABLE invitation_events +ALTER COLUMN actor_id SET NOT NULL; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_expiry_changes_no_field; + +ALTER TABLE invitation_events +DROP CONSTRAINT invitation_events_kind_known; + +ALTER TABLE invitation_events +ADD CONSTRAINT invitation_events_kind_known CHECK ( + kind IN ( + 'draft_created', 'draft_updated', 'delivered', 'viewed', 'declined', + 'accepted' + ) +); diff --git a/backend/db/migrations/00044_add_notification_subject.sql b/backend/db/migrations/00044_add_notification_subject.sql new file mode 100644 index 0000000..a185c5e --- /dev/null +++ b/backend/db/migrations/00044_add_notification_subject.sql @@ -0,0 +1,188 @@ +-- +goose Up +-- A notification names the record it is about (its subject), so the sending +-- worker can re-check the rights the notice depends on before it calls the +-- transport. The subject is fixed when the request is stored and is copied to +-- the delivery, where the content trigger keeps it unchanged. The three +-- columns are set together. Only the kind invitation exists so far. A +-- notification without a subject stays valid: the sending worker cancels it +-- with source_closed, because it has no right to check. +-- +-- Everything here is additive: existing rows keep NULL subjects. +ALTER TABLE mail_requests +ADD COLUMN subject_kind text, +ADD COLUMN subject_id uuid, +ADD COLUMN subject_organization_id uuid, +ADD CONSTRAINT mail_requests_subject_complete CHECK ( + (subject_kind IS NULL) = (subject_id IS NULL) + AND (subject_kind IS NULL) = (subject_organization_id IS NULL) + AND (subject_kind IS NULL OR subject_kind IN ('invitation')) +); + +COMMENT ON COLUMN mail_requests.subject_kind IS +'The kind of record the notification is about, NULL when it names none; the sending worker checks the rights of that kind.'; +COMMENT ON COLUMN mail_requests.subject_id IS +'The record the notification is about, for example the invitation; an opaque ID, never an address or a contact.'; +COMMENT ON COLUMN mail_requests.subject_organization_id IS +'The organization the subject record belongs to, for example the organization that sent the invitation.'; + +ALTER TABLE deliveries +ADD COLUMN subject_kind text, +ADD COLUMN subject_id uuid, +ADD COLUMN subject_organization_id uuid, +ADD CONSTRAINT deliveries_subject_complete CHECK ( + (subject_kind IS NULL) = (subject_id IS NULL) + AND (subject_kind IS NULL) = (subject_organization_id IS NULL) + AND (subject_kind IS NULL OR subject_kind IN ('invitation')) + AND (subject_kind IS NULL OR kind = 'notification') +); + +COMMENT ON COLUMN deliveries.subject_kind IS +'The kind of record a notification is about; set only for a notification, NULL when it names none. The product sending worker re-checks its rights before the send.'; +COMMENT ON COLUMN deliveries.subject_id IS +'The record a notification is about; an opaque ID, never an address or a contact.'; +COMMENT ON COLUMN deliveries.subject_organization_id IS +'The organization the subject record belongs to.'; + +-- The subject is part of what the delivery sends and is fixed, like the +-- recipient and the content. This is the function of migration 00012 with the +-- three subject columns added to the unchanged tuple. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.content_sha256, + NEW.idempotency_key, NEW.created_at, NEW.email_token_id, + NEW.subject_kind, NEW.subject_id, NEW.subject_organization_id + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.content_sha256, + OLD.idempotency_key, OLD.created_at, OLD.email_token_id, + OLD.subject_kind, OLD.subject_id, OLD.subject_organization_id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF (NEW.text_body, NEW.html_body) IS DISTINCT FROM (OLD.text_body, OLD.html_body) THEN + IF NOT ( + OLD.body_redacted_at IS NULL AND NEW.body_redacted_at IS NOT NULL + AND NEW.text_body = '' AND NEW.html_body = '' + AND NEW.status IN ('accepted', 'rejected', 'cancelled') + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + ELSIF OLD.body_redacted_at IS DISTINCT FROM NEW.body_redacted_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +-- +goose Down +-- Subjects name records whose rights a later version checks; dropping them +-- would send notices that were not checked. Refuse while any row names one. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM deliveries WHERE subject_kind IS NOT NULL) + OR EXISTS (SELECT 1 FROM mail_requests WHERE subject_kind IS NOT NULL) THEN + RAISE EXCEPTION USING + ERRCODE = 'feature_not_supported', + MESSAGE = 'notification subjects are stored; cancel or export the notifications that name one before this rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +-- The function of migration 00012 without the subject columns. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION deliveries_refuse_content_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF ( + NEW.id, NEW.source_event_id, NEW.recipient_user_id, + NEW.recipient_email, NEW.kind, NEW.template_version, NEW.subject, + NEW.content_sha256, + NEW.idempotency_key, NEW.created_at, NEW.email_token_id + ) IS DISTINCT FROM ( + OLD.id, OLD.source_event_id, OLD.recipient_user_id, + OLD.recipient_email, OLD.kind, OLD.template_version, OLD.subject, + OLD.content_sha256, + OLD.idempotency_key, OLD.created_at, OLD.email_token_id + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF (NEW.text_body, NEW.html_body) IS DISTINCT FROM (OLD.text_body, OLD.html_body) THEN + IF NOT ( + OLD.body_redacted_at IS NULL AND NEW.body_redacted_at IS NOT NULL + AND NEW.text_body = '' AND NEW.html_body = '' + AND NEW.status IN ('accepted', 'rejected', 'cancelled') + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + ELSIF OLD.body_redacted_at IS DISTINCT FROM NEW.body_redacted_at THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_content_immutable', + TABLE = 'deliveries', + MESSAGE = 'delivery content and recipient are immutable'; + END IF; + IF ( + (NEW.provider, NEW.provider_account) + IS DISTINCT FROM (OLD.provider, OLD.provider_account) + ) AND (OLD.attempt_count <> 0 OR NEW.attempt_count <> 0) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'deliveries_provider_pinned', + TABLE = 'deliveries', + MESSAGE = 'the provider account of a delivery is fixed after its first attempt'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_subject_complete; +ALTER TABLE deliveries +DROP COLUMN subject_organization_id, +DROP COLUMN subject_id, +DROP COLUMN subject_kind; + +ALTER TABLE mail_requests DROP CONSTRAINT mail_requests_subject_complete; +ALTER TABLE mail_requests +DROP COLUMN subject_organization_id, +DROP COLUMN subject_id, +DROP COLUMN subject_kind; diff --git a/backend/db/migrations/00045_send_product_notifications.sql b/backend/db/migrations/00045_send_product_notifications.sql new file mode 100644 index 0000000..3b30ee8 --- /dev/null +++ b/backend/db/migrations/00045_send_product_notifications.sql @@ -0,0 +1,111 @@ +-- +goose Up +-- Product notifications get their own sending worker. It claims them through +-- deliveries_product_due_idx, re-checks the rights of their subject before +-- the transport is called, and cancels a notice whose basis no longer holds +-- with one of the reasons below. A cancelled notification loses its bodies, +-- as a token mail does, so a withdrawn notice keeps no text in the table. +-- The service worker and deliveries_due_idx do not change. + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_cancel_reason_matches_status CHECK ( + (status = 'cancelled') = (cancel_reason IS NOT NULL) + AND ( + cancel_reason IS NULL + OR cancel_reason IN ( + 'token_missing', + 'token_purpose_mismatch', + 'token_owner_mismatch', + 'token_consumed', + 'token_revoked', + 'token_expired', + 'account_not_current', + 'recipient_mismatch', + 'content_invalid', + 'processing_failed', + 'rights_revoked', + 'recipient_ineligible', + 'source_closed' + ) + ) +); + +-- A redacted mail has no bodies. A token mail may be redacted once it is +-- terminal; a notification once it is cancelled. +ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( + (body_redacted_at IS NULL AND (text_body <> '' OR html_body <> '')) + OR ( + body_redacted_at IS NOT NULL + AND text_body = '' AND html_body = '' + AND ( + ( + kind IN ('verification', 'password_reset') + AND status IN ('accepted', 'rejected', 'cancelled') + ) + OR (kind = 'notification' AND status = 'cancelled') + ) + ) +); + +-- Serves the claim of due product notifications. The predicate names the +-- kind literal the product claim repeats, so an idle poll of either worker +-- reads only its own index and never the other lane's backlog. +CREATE INDEX deliveries_product_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota', 'unknown') + AND next_attempt_at IS NOT NULL + AND kind = 'notification'; + +-- +goose Down +DROP INDEX deliveries_product_due_idx; + +-- Rows that name the reasons of this version, or redacted notifications, +-- cannot satisfy the checks of the earlier schema. Refuse before changing +-- them, so the rollback never rewrites a cancellation. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM deliveries + WHERE cancel_reason IN ('rights_revoked', 'recipient_ineligible', 'source_closed') + OR (kind = 'notification' AND body_redacted_at IS NOT NULL) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'feature_not_supported', + MESSAGE = 'notifications cancelled by a rights check are stored; export or resend them before this rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_body_present; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_body_present CHECK ( + (body_redacted_at IS NULL AND (text_body <> '' OR html_body <> '')) + OR ( + body_redacted_at IS NOT NULL + AND text_body = '' AND html_body = '' + AND kind IN ('verification', 'password_reset') + AND status IN ('accepted', 'rejected', 'cancelled') + ) +); + +ALTER TABLE deliveries DROP CONSTRAINT deliveries_cancel_reason_matches_status; +ALTER TABLE deliveries ADD CONSTRAINT deliveries_cancel_reason_matches_status CHECK ( + (status = 'cancelled') = (cancel_reason IS NOT NULL) + AND ( + cancel_reason IS NULL + OR cancel_reason IN ( + 'token_missing', + 'token_purpose_mismatch', + 'token_owner_mismatch', + 'token_consumed', + 'token_revoked', + 'token_expired', + 'account_not_current', + 'recipient_mismatch', + 'content_invalid', + 'processing_failed' + ) + ) +); diff --git a/backend/db/migrations/00046_add_email_verification_codes.sql b/backend/db/migrations/00046_add_email_verification_codes.sql new file mode 100644 index 0000000..0b0939a --- /dev/null +++ b/backend/db/migrations/00046_add_email_verification_codes.sql @@ -0,0 +1,70 @@ +-- +goose Up +-- Email verification codes: a six-digit code that travels with each +-- verification message next to the link. The table keeps only a keyed digest +-- of the code, its expiry, and the count of failed attempts. The count is +-- advanced by a single conditional UPDATE, so concurrent wrong attempts cannot +-- exceed the limit and none is lost. Tokens issued before this migration carry +-- no code and keep working by link only. +-- +-- The three columns are set together for a token that carries a code. The +-- application sets the code expiry to the earlier of the token expiry and the +-- code lifetime, and checks both at every use. +ALTER TABLE email_tokens +ADD COLUMN code_hash bytea, +ADD COLUMN code_expires_at timestamptz, +ADD COLUMN code_failed_attempts smallint NOT NULL DEFAULT 0, +ADD CONSTRAINT email_tokens_code_pair CHECK ( + (code_hash IS NULL) = (code_expires_at IS NULL) +), +ADD CONSTRAINT email_tokens_code_hash_length CHECK ( + code_hash IS NULL OR octet_length(code_hash) = 32 +), +ADD CONSTRAINT email_tokens_code_expiry CHECK ( + code_expires_at IS NULL OR code_expires_at > created_at +), +ADD CONSTRAINT email_tokens_code_purpose CHECK ( + code_hash IS NULL OR purpose = 'email_verification' +), +ADD CONSTRAINT email_tokens_code_attempts_range CHECK ( + code_failed_attempts BETWEEN 0 AND 5 +); + +COMMENT ON COLUMN email_tokens.code_hash IS +'HMAC-SHA-256 of the six-digit verification code under a server-side key; NULL when the token carries no code or the code has ended. The code itself is never stored.'; +COMMENT ON COLUMN email_tokens.code_expires_at IS +'End of the code validity: the earlier of the token expiry and the code lifetime. NULL together with code_hash.'; +COMMENT ON COLUMN email_tokens.code_failed_attempts IS +'Wrong code or password attempts counted against the open code; the token is invalidated when the count reaches the limit of five.'; + +-- +goose Down +-- A rollback removes the codes, so it refuses while a code is still usable. +-- A code expires within its 30-minute lifetime, so waiting for expiry is enough. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM email_tokens + WHERE code_hash IS NOT NULL + AND consumed_at IS NULL + AND invalidated_at IS NULL + AND code_expires_at > now() + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'object_not_in_prerequisite_state', + MESSAGE = 'email verification codes are still usable', + HINT = 'Wait until the open codes expire, then roll back again.'; + END IF; +END +$$; +-- +goose StatementEnd + +ALTER TABLE email_tokens +DROP CONSTRAINT email_tokens_code_attempts_range, +DROP CONSTRAINT email_tokens_code_purpose, +DROP CONSTRAINT email_tokens_code_expiry, +DROP CONSTRAINT email_tokens_code_hash_length, +DROP CONSTRAINT email_tokens_code_pair, +DROP COLUMN code_failed_attempts, +DROP COLUMN code_expires_at, +DROP COLUMN code_hash; diff --git a/backend/db/migrations/00047_allow_table_hash_scheme.sql b/backend/db/migrations/00047_allow_table_hash_scheme.sql new file mode 100644 index 0000000..a03e03c --- /dev/null +++ b/backend/db/migrations/00047_allow_table_hash_scheme.sql @@ -0,0 +1,37 @@ +-- +goose Up +-- Content hash scheme 2 is the layout of a table generator: a family whose +-- variants are rows of a table, with the answers written in the rows. A new +-- version of such a family is stored with scheme 2. Scheme 1 stays the layout +-- of an algorithmic generator, so existing rows and the hash of every +-- algorithmic version are unchanged, and importing one of them again is still +-- recognized as the same version. +-- +-- Only the list of known schemes changes. hash_scheme stays one of the +-- immutable columns that the guard trigger protects. +ALTER TABLE assessment_families +DROP CONSTRAINT assessment_families_hash_scheme_known, +ADD CONSTRAINT assessment_families_hash_scheme_known CHECK ( + hash_scheme IN (1, 2) +); + +-- +goose Down +-- A stored version never changes and is never removed, so a row of scheme 2 +-- cannot be given another scheme. The down step refuses while one exists. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM assessment_families WHERE hash_scheme = 2) THEN + RAISE EXCEPTION USING + ERRCODE = 'object_not_in_prerequisite_state', + MESSAGE = 'table generator families are stored', + HINT = 'A stored family version cannot be removed or rehashed; keep migration 00047 applied.'; + END IF; +END +$$; +-- +goose StatementEnd + +ALTER TABLE assessment_families +DROP CONSTRAINT assessment_families_hash_scheme_known, +ADD CONSTRAINT assessment_families_hash_scheme_known CHECK ( + hash_scheme IN (1) +); diff --git a/backend/db/migrations/00048_add_candidate_projects.sql b/backend/db/migrations/00048_add_candidate_projects.sql new file mode 100644 index 0000000..bc18c70 --- /dev/null +++ b/backend/db/migrations/00048_add_candidate_projects.sql @@ -0,0 +1,265 @@ +-- +goose Up +-- Candidate projects: a new list kind of profile claims, a publishable card +-- field `projects`, and the stored server check of each linked GitHub +-- repository. A project is a claim of trust level 0 like every other; the +-- repository check is separate evidence and never changes the claim. + +ALTER TABLE candidate_profile_claims +DROP CONSTRAINT candidate_profile_claims_kind_ordinal, +ADD CONSTRAINT candidate_profile_claims_kind_ordinal CHECK ( + ( + kind IN ( + 'full_name', + 'contact_email', + 'contact_phone', + 'contact_telegram', + 'terms_location', + 'terms_relocation', + 'terms_salary_minimum' + ) + AND ordinal = 0 + ) + OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29) + OR (kind = 'role' AND ordinal BETWEEN 0 AND 8) + OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19) + OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9) + OR (kind = 'project' AND ordinal BETWEEN 0 AND 9) +), +-- The bounds repeat ProfileProjectItem of the public contract. The address +-- is the canonical https://github.com// that the domain stores. +ADD CONSTRAINT candidate_profile_claims_project_value CHECK ( + kind <> 'project' OR ( + jsonb_typeof(value) = 'object' + AND value ?& ARRAY['title', 'description', 'stack', 'repository_url'] + AND value - 'title' - 'description' - 'stack' - 'repository_url' = '{}'::jsonb + AND jsonb_typeof(value -> 'title') = 'string' + AND char_length(value ->> 'title') BETWEEN 1 AND 100 + AND value ->> 'title' !~ '^\s|\s$' + AND value ->> 'title' !~ '[[:cntrl:]]' + AND ( + jsonb_typeof(value -> 'description') = 'null' + OR ( + jsonb_typeof(value -> 'description') = 'string' + AND char_length(value ->> 'description') BETWEEN 1 AND 500 + AND value ->> 'description' !~ '^\s|\s$' + AND translate(value ->> 'description', E'\n', '') !~ '[[:cntrl:]]' + ) + ) + AND jsonb_typeof(value -> 'stack') = 'array' + AND jsonb_array_length(value -> 'stack') <= 10 + AND ( + jsonb_typeof(value -> 'repository_url') = 'null' + OR ( + jsonb_typeof(value -> 'repository_url') = 'string' + AND value ->> 'repository_url' + ~ '^https://github\.com/[A-Za-z0-9][A-Za-z0-9-]{0,38}/[A-Za-z0-9._-]{1,100}$' + ) + ) + ) +); + +-- The publishable card fields gain `projects`; saved sets stay valid. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 10 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'projects', 'relocation', + 'salary_compatibility', 'self_assessment', 'soft_skills', + 'stack', 'work_formats' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +-- A card view can now return the published projects. +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + cardinality(field_codes) BETWEEN 0 AND 7 + AND array_position(field_codes, NULL) IS NULL + AND field_codes = ARRAY( + SELECT DISTINCT code COLLATE "C" + FROM unnest(field_codes) AS code + ORDER BY code COLLATE "C" + ) + AND ( + ( + kind = 'card_viewed' + AND field_codes <@ ARRAY[ + 'categories', 'experience', 'projects', 'salary_compatibility', + 'self_assessment', 'stack', 'work_formats' + ]::text [] + ) + OR ( + kind = 'contact_read' + AND cardinality(field_codes) BETWEEN 1 AND 4 + AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text [] + ) + ); +$$; +-- +goose StatementEnd + +-- The latest server check of each repository that a candidate's projects +-- link. The key is "/" in lower case. Fetched metadata is kept +-- only while the repository is verified public and is used for ranking only; +-- the API never returns it. No token, header, or response body other than the +-- bounded fields below is stored. +CREATE TABLE candidate_project_repositories ( + candidate_id uuid NOT NULL, + repository_key text NOT NULL, + state text NOT NULL, + github_id bigint, + description text, + topics text [] NOT NULL DEFAULT '{}', + languages text [] NOT NULL DEFAULT '{}', + readme_excerpt text, + repository_etag text, + readme_etag text, + failure_class text, + checked_at timestamptz, + requested_at timestamptz NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT candidate_project_repositories_pkey PRIMARY KEY (candidate_id, repository_key), + CONSTRAINT candidate_project_repositories_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT candidate_project_repositories_key_format CHECK ( + repository_key ~ '^[a-z0-9][a-z0-9-]{0,38}/[a-z0-9._-]{1,100}$' + ), + CONSTRAINT candidate_project_repositories_state_known CHECK ( + state IN ('pending', 'verified', 'not_found', 'unavailable') + ), + CONSTRAINT candidate_project_repositories_failure_known CHECK ( + failure_class IS NULL OR failure_class IN ( + 'rate_limited', 'server_error', 'network', 'invalid_response' + ) + ), + CONSTRAINT candidate_project_repositories_failure_state CHECK ( + (state = 'unavailable') = (failure_class IS NOT NULL) + ), + CONSTRAINT candidate_project_repositories_checked CHECK ( + state = 'pending' OR checked_at IS NOT NULL + ), + -- Metadata exists only for a verified public repository. + CONSTRAINT candidate_project_repositories_evidence_verified CHECK ( + state = 'verified' OR ( + github_id IS NULL + AND description IS NULL + AND readme_excerpt IS NULL + AND cardinality(topics) = 0 + AND cardinality(languages) = 0 + ) + ), + CONSTRAINT candidate_project_repositories_github_id CHECK ( + github_id IS NULL OR github_id > 0 + ), + CONSTRAINT candidate_project_repositories_bounds CHECK ( + (description IS NULL OR char_length(description) <= 1000) + AND (readme_excerpt IS NULL OR char_length(readme_excerpt) <= 4000) + AND cardinality(topics) <= 20 + AND cardinality(languages) <= 10 + AND (repository_etag IS NULL OR char_length(repository_etag) <= 200) + AND (readme_etag IS NULL OR char_length(readme_etag) <= 200) + ), + CONSTRAINT candidate_project_repositories_times CHECK ( + updated_at >= created_at + ) +); + +-- +goose Down +-- Refuse to strand stored projects or published project fields outside the +-- older contract; remove them through the product first. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM candidate_profile_claims WHERE kind = 'project') + OR EXISTS (SELECT 1 FROM candidate_publications WHERE 'projects' = ANY (fields)) + OR EXISTS (SELECT 1 FROM candidate_privacy_events WHERE 'projects' = ANY (fields)) + OR EXISTS (SELECT 1 FROM candidate_card_access_events WHERE 'projects' = ANY (field_codes)) + THEN + RAISE EXCEPTION 'candidate projects are still stored or published'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TABLE candidate_project_repositories; + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + cardinality(field_codes) BETWEEN 0 AND 6 + AND array_position(field_codes, NULL) IS NULL + AND field_codes = ARRAY( + SELECT DISTINCT code COLLATE "C" + FROM unnest(field_codes) AS code + ORDER BY code COLLATE "C" + ) + AND ( + ( + kind = 'card_viewed' + AND field_codes <@ ARRAY[ + 'categories', 'experience', 'salary_compatibility', + 'self_assessment', 'stack', 'work_formats' + ]::text [] + ) + OR ( + kind = 'contact_read' + AND cardinality(field_codes) BETWEEN 1 AND 4 + AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text [] + ) + ); +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean +LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$ + SELECT + (cardinality(fields) = 0 OR array_ndims(fields) = 1) + AND cardinality(fields) BETWEEN 0 AND 9 + AND array_position(fields, NULL) IS NULL + AND fields <@ ARRAY[ + 'categories', 'experience', 'location', 'relocation', + 'salary_compatibility', 'self_assessment', 'soft_skills', + 'stack', 'work_formats' + ]::text [] + AND fields = ARRAY( + SELECT DISTINCT field COLLATE "C" + FROM unnest(fields) AS field + ORDER BY field COLLATE "C" + ); +$$; +-- +goose StatementEnd + +ALTER TABLE candidate_profile_claims +DROP CONSTRAINT candidate_profile_claims_project_value, +DROP CONSTRAINT candidate_profile_claims_kind_ordinal, +ADD CONSTRAINT candidate_profile_claims_kind_ordinal CHECK ( + ( + kind IN ( + 'full_name', + 'contact_email', + 'contact_phone', + 'contact_telegram', + 'terms_location', + 'terms_relocation', + 'terms_salary_minimum' + ) + AND ordinal = 0 + ) + OR (kind = 'stack' AND ordinal BETWEEN 0 AND 29) + OR (kind = 'role' AND ordinal BETWEEN 0 AND 8) + OR (kind = 'experience' AND ordinal BETWEEN 0 AND 19) + OR (kind = 'soft_skill' AND ordinal BETWEEN 0 AND 9) +); diff --git a/backend/db/migrations/00049_create_semantic_vectors.sql b/backend/db/migrations/00049_create_semantic_vectors.sql new file mode 100644 index 0000000..bfc8bf3 --- /dev/null +++ b/backend/db/migrations/00049_create_semantic_vectors.sql @@ -0,0 +1,64 @@ +-- +goose Up +-- Stored embedding vectors of candidate cards and need snapshots. A row is +-- one text of a subject (the whole view or one item) encoded by one model, +-- revision, and prompt recipe; content_sha256 is the digest of the rendered +-- text, so a stale row is never mistaken for the current one. The vector is +-- little-endian float32: exact, platform independent, 4 KiB for 1024 +-- dimensions. Derived data follows its subject: an account or a need that +-- is deleted takes its vectors with it. +CREATE TABLE semantic_vectors ( + subject_kind text NOT NULL, + subject_id uuid NOT NULL, + candidate_id uuid, + need_id uuid, + model_id text NOT NULL, + model_revision text NOT NULL, + prompt_version text NOT NULL, + item_key text NOT NULL, + content_sha256 bytea NOT NULL, + label_sha256 bytea, + dimension integer NOT NULL, + vector bytea NOT NULL, + computed_at timestamptz NOT NULL, + CONSTRAINT semantic_vectors_pkey PRIMARY KEY ( + subject_kind, subject_id, model_id, model_revision, prompt_version, item_key, content_sha256 + ), + CONSTRAINT semantic_vectors_candidate_fkey FOREIGN KEY (candidate_id) + REFERENCES users (id) ON DELETE CASCADE, + CONSTRAINT semantic_vectors_need_fkey FOREIGN KEY (need_id) + REFERENCES organization_needs (id) ON DELETE CASCADE, + CONSTRAINT semantic_vectors_subject CHECK ( + (subject_kind = 'candidate' AND candidate_id = subject_id AND need_id IS NULL) + OR (subject_kind = 'need' AND need_id = subject_id AND candidate_id IS NULL) + ), + CONSTRAINT semantic_vectors_model_format CHECK ( + model_id ~ '^[A-Za-z0-9._/-]{1,200}$' + AND model_revision ~ '^[A-Za-z0-9._/-]{1,200}$' + AND prompt_version ~ '^[A-Za-z0-9._/-]{1,200}$' + ), + CONSTRAINT semantic_vectors_item_key_format CHECK ( + item_key ~ '^[a-z_]{1,32}(:[0-9]{1,3})?$' + ), + CONSTRAINT semantic_vectors_digests CHECK ( + octet_length(content_sha256) = 32 + AND (label_sha256 IS NULL OR octet_length(label_sha256) = 32) + ), + CONSTRAINT semantic_vectors_dimension CHECK ( + dimension BETWEEN 1 AND 4096 AND octet_length(vector) = 4 * dimension + ) +); + +-- The search reads the whole-view vector of many candidates for one model. +CREATE INDEX semantic_vectors_candidate_whole_idx +ON semantic_vectors (model_id, model_revision, prompt_version, candidate_id) +WHERE subject_kind = 'candidate' AND item_key = 'whole'; + +-- Account and need deletion find the rows of their subject through these. +CREATE INDEX semantic_vectors_candidate_idx ON semantic_vectors (candidate_id) +WHERE candidate_id IS NOT NULL; +CREATE INDEX semantic_vectors_need_idx ON semantic_vectors (need_id) +WHERE need_id IS NOT NULL; + +-- +goose Down +-- The vectors are derived data: the backfill command computes them again. +DROP TABLE semantic_vectors; diff --git a/backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql b/backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql new file mode 100644 index 0000000..bc992ca --- /dev/null +++ b/backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql @@ -0,0 +1,145 @@ +-- +goose Up +-- Three additive pieces of the attempt proctoring that needs no camera: +-- +-- 1. The hold of the single active work session of a real attempt. One open +-- page at a time holds it; the holder is a keyed digest of an identifier the +-- page generated, never the identifier. The row is one per attempt and is +-- changed in place under the attempt row lock that the usecase already takes. +-- 2. Two weak client signals: a screenshot key and open developer tools. They +-- carry no measurement. +-- 3. A keyed digest of the User-Agent in the origin marks and three counters in +-- the review. The raw User-Agent is never stored. + +CREATE TABLE assessment_attempt_work_leases ( + attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE, + holder_digest bytea NOT NULL, + key_version smallint NOT NULL, + acquired_at timestamptz NOT NULL, + renewed_at timestamptz NOT NULL, + released_at timestamptz, + CONSTRAINT assessment_attempt_work_leases_pkey PRIMARY KEY (attempt_id), + CONSTRAINT assessment_attempt_work_leases_holder CHECK (octet_length(holder_digest) = 32), + CONSTRAINT assessment_attempt_work_leases_key_version CHECK (key_version > 0), + CONSTRAINT assessment_attempt_work_leases_times CHECK ( + renewed_at >= acquired_at AND (released_at IS NULL OR released_at >= acquired_at) + ) +); + +-- The two new kinds are facts without a measurement, like a fullscreen exit. +ALTER TABLE assessment_signal_events +DROP CONSTRAINT assessment_signal_events_kind, +DROP CONSTRAINT assessment_signal_events_measurement; + +ALTER TABLE assessment_signal_events +ADD CONSTRAINT assessment_signal_events_kind CHECK ( + kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit', 'screenshot_key', 'devtools_open') +), +ADD CONSTRAINT assessment_signal_events_measurement CHECK ( + (kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL) + OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647) + OR (kind IN ('fullscreen_exit', 'screenshot_key', 'devtools_open') AND duration_ms IS NULL AND size_bytes IS NULL) +); + +-- The mark of a request that holds the work session is written like the marks +-- of answers and signal batches, when the session, the network, or the +-- User-Agent differs from the last mark. +ALTER TABLE assessment_attempt_origin_marks +ADD COLUMN agent_digest bytea, +DROP CONSTRAINT assessment_attempt_origin_marks_source; + +ALTER TABLE assessment_attempt_origin_marks +ADD CONSTRAINT assessment_attempt_origin_marks_source CHECK (source IN ('answer', 'signals', 'work_session')), +ADD CONSTRAINT assessment_attempt_origin_marks_agent CHECK ( + agent_digest IS NULL OR octet_length(agent_digest) = 32 +); + +ALTER TABLE assessment_attempt_reviews +ADD COLUMN extra_agents integer NOT NULL DEFAULT 0, +ADD COLUMN client_screenshot_keys integer NOT NULL DEFAULT 0, +ADD COLUMN client_devtools_opens integer NOT NULL DEFAULT 0, +DROP CONSTRAINT assessment_attempt_reviews_reasons, +DROP CONSTRAINT assessment_attempt_reviews_counts; + +ALTER TABLE assessment_attempt_reviews +ADD CONSTRAINT assessment_attempt_reviews_reasons CHECK ( + reasons <@ ARRAY['fast_answers', 'deviating_answers', 'parallel_sessions', 'extra_networks', + 'extra_agents', 'duplicate_answers', 'client_signals']::text[] +), +ADD CONSTRAINT assessment_attempt_reviews_counts CHECK ( + answered_items >= 0 AND fast_answers >= 0 AND deviating_answers >= 0 AND parallel_alternations >= 0 + AND extra_networks >= 0 AND matched_integer_items >= 0 AND matched_sequence_items >= 0 + AND duplicate_evidence_bits >= 0 AND client_focus_loss_ms >= 0 AND client_clipboard_events >= 0 + AND client_fullscreen_exits >= 0 AND extra_agents >= 0 AND client_screenshot_keys >= 0 + AND client_devtools_opens >= 0 +); + +-- +goose Down +-- The new facts are evidence of a manual review. Rolling the schema back must +-- not drop them as a side effect: an operator exports or resolves them first. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 FROM assessment_signal_events WHERE kind IN ('screenshot_key', 'devtools_open') + ) OR EXISTS ( + SELECT 1 FROM assessment_attempt_origin_marks WHERE source = 'work_session' OR agent_digest IS NOT NULL + ) OR EXISTS ( + SELECT 1 FROM assessment_attempt_reviews + WHERE extra_agents > 0 OR client_screenshot_keys > 0 OR client_devtools_opens > 0 + OR 'extra_agents' = ANY (reasons) + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_capture_signals_retained', + MESSAGE = 'capture signal facts must be retained before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +ALTER TABLE assessment_attempt_reviews +DROP CONSTRAINT assessment_attempt_reviews_reasons, +DROP CONSTRAINT assessment_attempt_reviews_counts; + +ALTER TABLE assessment_attempt_reviews +DROP COLUMN extra_agents, +DROP COLUMN client_screenshot_keys, +DROP COLUMN client_devtools_opens; + +ALTER TABLE assessment_attempt_reviews +ADD CONSTRAINT assessment_attempt_reviews_reasons CHECK ( + reasons <@ ARRAY['fast_answers', 'deviating_answers', 'parallel_sessions', 'extra_networks', + 'duplicate_answers', 'client_signals']::text[] +), +ADD CONSTRAINT assessment_attempt_reviews_counts CHECK ( + answered_items >= 0 AND fast_answers >= 0 AND deviating_answers >= 0 AND parallel_alternations >= 0 + AND extra_networks >= 0 AND matched_integer_items >= 0 AND matched_sequence_items >= 0 + AND duplicate_evidence_bits >= 0 AND client_focus_loss_ms >= 0 AND client_clipboard_events >= 0 + AND client_fullscreen_exits >= 0 +); + +ALTER TABLE assessment_attempt_origin_marks +DROP CONSTRAINT assessment_attempt_origin_marks_agent, +DROP CONSTRAINT assessment_attempt_origin_marks_source; + +ALTER TABLE assessment_attempt_origin_marks +DROP COLUMN agent_digest; + +ALTER TABLE assessment_attempt_origin_marks +ADD CONSTRAINT assessment_attempt_origin_marks_source CHECK (source IN ('answer', 'signals')); + +ALTER TABLE assessment_signal_events +DROP CONSTRAINT assessment_signal_events_kind, +DROP CONSTRAINT assessment_signal_events_measurement; + +ALTER TABLE assessment_signal_events +ADD CONSTRAINT assessment_signal_events_kind CHECK ( + kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit') +), +ADD CONSTRAINT assessment_signal_events_measurement CHECK ( + (kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL) + OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647) + OR (kind = 'fullscreen_exit' AND duration_ms IS NULL AND size_bytes IS NULL) +); + +DROP TABLE assessment_attempt_work_leases; diff --git a/backend/db/migrations/00051_create_assessment_leak_traces.sql b/backend/db/migrations/00051_create_assessment_leak_traces.sql new file mode 100644 index 0000000..3097394 --- /dev/null +++ b/backend/db/migrations/00051_create_assessment_leak_traces.sql @@ -0,0 +1,85 @@ +-- +goose Up +-- The audit of the operator search for the attempt behind a leaked task text. +-- Every search writes one row, whatever it finds, before a result is shown. +-- A row holds no leaked text: only a keyed digest of the normalized text and its +-- length, the outcome, and, for a found search, the attempt. The attempt is not +-- a foreign key, so the row outlives an account deletion. Nothing reads these +-- rows for a candidate, an employer, a result, a category, or a quota. +CREATE TABLE assessment_leak_traces ( + id uuid NOT NULL, + actor text NOT NULL, + searched_at timestamptz NOT NULL, + text_digest bytea NOT NULL, + key_version smallint NOT NULL, + text_runes integer NOT NULL, + status text NOT NULL, + method text, + attempt_id uuid, + candidates integer NOT NULL, + evidence_bits integer NOT NULL, + CONSTRAINT assessment_leak_traces_pkey PRIMARY KEY (id), + CONSTRAINT assessment_leak_traces_actor CHECK ( + char_length(actor) <= 128 AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ), + CONSTRAINT assessment_leak_traces_digest CHECK (octet_length(text_digest) = 32), + CONSTRAINT assessment_leak_traces_key_version CHECK (key_version > 0), + CONSTRAINT assessment_leak_traces_counts CHECK (text_runes >= 0 AND candidates >= 0 AND evidence_bits >= 0), + CONSTRAINT assessment_leak_traces_status CHECK (status IN ('found', 'ambiguous', 'not_found')), + CONSTRAINT assessment_leak_traces_method CHECK ( + method IS NULL OR method IN ('invisible_mark', 'visible_code', 'wording', 'variant') + ), + CONSTRAINT assessment_leak_traces_found CHECK ( + (status = 'found' AND attempt_id IS NOT NULL AND method IS NOT NULL) + OR (status <> 'found' AND attempt_id IS NULL) + ) +); + +CREATE INDEX assessment_leak_traces_attempt_idx +ON assessment_leak_traces (attempt_id, searched_at) +WHERE attempt_id IS NOT NULL; + +CREATE INDEX assessment_leak_traces_searched_idx +ON assessment_leak_traces (searched_at, id); + +-- +goose StatementBegin +CREATE FUNCTION assessment_leak_traces_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_leak_traces_immutable', + MESSAGE = 'assessment leak trace audit records are immutable'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_leak_traces_immutable +BEFORE UPDATE OR DELETE ON assessment_leak_traces +FOR EACH ROW EXECUTE FUNCTION assessment_leak_traces_immutable(); + +CREATE TRIGGER assessment_leak_traces_no_truncate +BEFORE TRUNCATE ON assessment_leak_traces +FOR EACH STATEMENT EXECUTE FUNCTION assessment_leak_traces_immutable(); + +-- +goose Down +-- The audit of operator searches is durable evidence. Rolling the schema back +-- must not remove it as a side effect: an operator exports or resolves it first. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM assessment_leak_traces) THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'assessment_leak_traces_retained', + TABLE = 'assessment_leak_traces', + MESSAGE = 'assessment leak trace audit must be retained before rollback'; + END IF; +END; +$$; +-- +goose StatementEnd + +DROP TRIGGER assessment_leak_traces_no_truncate ON assessment_leak_traces; +DROP TRIGGER assessment_leak_traces_immutable ON assessment_leak_traces; +DROP FUNCTION assessment_leak_traces_immutable(); +DROP INDEX assessment_leak_traces_searched_idx; +DROP INDEX assessment_leak_traces_attempt_idx; +DROP TABLE assessment_leak_traces; diff --git a/backend/db/migrations/00052_create_assessment_practice_submissions.sql b/backend/db/migrations/00052_create_assessment_practice_submissions.sql new file mode 100644 index 0000000..a9ab62d --- /dev/null +++ b/backend/db/migrations/00052_create_assessment_practice_submissions.sql @@ -0,0 +1,209 @@ +-- +goose Up +-- Code practice keeps its own records next to the attempt and its result: +-- the practice items of an attempt with their private task content and +-- state, the submissions of candidate code, and one execution job per +-- submission. None of these rows is part of the attempt snapshot, the +-- idempotent attempt responses, or the result. +-- +-- A submission and its execution job are inserted in one transaction, so a +-- job exists exactly when its submission committed; the practice queue +-- worker picks the job later. The job table is that transactional queue: a +-- separate event is not needed because nothing outside PostgreSQL has to +-- learn about the submission before the worker runs it. + +-- One practice item of an attempt: the main practice or the additional one. +-- The ID is the item ID the candidate sees and the attempt item of the run +-- key. task is the private task content (languages, limits, checker, public +-- examples, and the hidden test groups); it never leaves the backend except +-- in a request to the code runner. +CREATE TABLE assessment_practices ( + id uuid NOT NULL, + attempt_id uuid NOT NULL, + user_id uuid NOT NULL, + kind text NOT NULL, + task jsonb NOT NULL, + -- not_started: nothing submitted; pending: the latest final submission + -- waits for its verdict; finished: it has one; failed: the sandbox + -- infrastructure could not run it, and the practice can be submitted + -- again. + status text NOT NULL, + failure_reason text, + -- Time of the latest final submission, or NULL before the first one. + submitted_at timestamptz, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT assessment_practices_pkey PRIMARY KEY (id), + CONSTRAINT assessment_practices_id_owner_key UNIQUE (id, user_id), + CONSTRAINT assessment_practices_attempt_kind_key UNIQUE (attempt_id, kind), + CONSTRAINT assessment_practices_attempt_owner_fk FOREIGN KEY (attempt_id, user_id) + REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_practices_kind CHECK (kind IN ('main', 'additional')), + CONSTRAINT assessment_practices_task_object CHECK ( + jsonb_typeof(task) = 'object' AND octet_length(task::text) <= 8388608 + ), + CONSTRAINT assessment_practices_status CHECK ( + status IN ('not_started', 'pending', 'finished', 'failed') + ), + CONSTRAINT assessment_practices_failure CHECK ( + (status = 'failed') = (failure_reason IS NOT NULL) + AND (failure_reason IS NULL OR failure_reason IN ('sandbox_busy', 'sandbox_error')) + ), + CONSTRAINT assessment_practices_submitted CHECK ( + (status = 'not_started') = (submitted_at IS NULL) + ), + CONSTRAINT assessment_practices_timestamps CHECK ( + created_at <= updated_at + AND (submitted_at IS NULL OR submitted_at >= created_at) + ) +); + +-- The identity, owner, kind, and task content of a practice never change; +-- only its state moves. +-- +goose StatementBegin +CREATE FUNCTION assessment_practice_immutable_task() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.id <> OLD.id OR NEW.attempt_id <> OLD.attempt_id OR NEW.user_id <> OLD.user_id OR + NEW.kind <> OLD.kind OR NEW.task <> OLD.task OR NEW.created_at <> OLD.created_at OR + NEW.updated_at < OLD.updated_at THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_practice_task_immutable', + MESSAGE = 'assessment practice identity and task are immutable'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_practice_immutable_task +BEFORE UPDATE ON assessment_practices +FOR EACH ROW EXECUTE FUNCTION assessment_practice_immutable_task(); + +-- One submission of candidate code. public is a debug run against the +-- public examples and the candidate's own tests; final is the solution that +-- the hidden groups grade. The request part of a row is immutable: once +-- stored, the source of a submission can never be replaced, and the result +-- is written once. +-- +-- idempotency_scope is the keyed digest of the operation, the +-- Idempotency-Key, and the account; it does not reveal the key. The generic +-- idempotency record of the same scope, written in the same transaction, +-- holds the request fingerprint and decides a replay for 24 hours; this +-- column only finds the submission that a replay returns. +CREATE TABLE assessment_practice_submissions ( + id uuid NOT NULL, + practice_id uuid NOT NULL, + user_id uuid NOT NULL, + mode text NOT NULL, + language text NOT NULL, + source text NOT NULL, + source_sha256 bytea NOT NULL, + -- The candidate's own tests of a public run, or NULL. + custom_tests jsonb, + idempotency_scope bytea NOT NULL, + -- The validated run result, written once by the queue worker. + result jsonb, + result_at timestamptz, + created_at timestamptz NOT NULL, + CONSTRAINT assessment_practice_submissions_pkey PRIMARY KEY (id), + CONSTRAINT assessment_practice_submissions_practice_owner_fk FOREIGN KEY (practice_id, user_id) + REFERENCES assessment_practices (id, user_id) ON DELETE CASCADE, + CONSTRAINT assessment_practice_submissions_mode CHECK (mode IN ('public', 'final')), + CONSTRAINT assessment_practice_submissions_language CHECK (language IN ('go', 'python')), + CONSTRAINT assessment_practice_submissions_source CHECK ( + char_length(source) >= 1 AND octet_length(source) <= 65536 + ), + CONSTRAINT assessment_practice_submissions_digests CHECK ( + octet_length(source_sha256) = 32 + AND octet_length(idempotency_scope) = 32 + ), + CONSTRAINT assessment_practice_submissions_custom_tests CHECK ( + custom_tests IS NULL OR ( + mode = 'public' + AND jsonb_typeof(custom_tests) = 'array' + AND octet_length(custom_tests::text) <= 262144 + ) + ), + CONSTRAINT assessment_practice_submissions_result CHECK ( + (result IS NULL) = (result_at IS NULL) + AND (result IS NULL OR (jsonb_typeof(result) = 'object' AND octet_length(result::text) <= 1048576)) + AND (result_at IS NULL OR result_at >= created_at) + ) +); + +CREATE INDEX assessment_practice_submissions_practice_idx +ON assessment_practice_submissions (practice_id, mode, created_at, id); + +-- Serves the replay of a submission by its idempotency scope. +CREATE INDEX assessment_practice_submissions_scope_idx +ON assessment_practice_submissions (user_id, idempotency_scope, created_at); + +-- A submission is immutable except for its one-time result. Rows are removed +-- only by the cascade of an account, attempt, or practice deletion. +-- +goose StatementBegin +CREATE FUNCTION assessment_practice_submission_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF pg_trigger_depth() > 1 THEN + RETURN OLD; + END IF; + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_practice_submission_delete_forbidden', + MESSAGE = 'assessment practice submissions are removed only by cascade'; + END IF; + IF (to_jsonb(NEW) - 'result' - 'result_at') IS DISTINCT FROM (to_jsonb(OLD) - 'result' - 'result_at') OR + OLD.result IS NOT NULL OR NEW.result IS NULL THEN + RAISE EXCEPTION USING + ERRCODE = '23000', CONSTRAINT = 'assessment_practice_submission_immutable', + MESSAGE = 'assessment practice submissions are immutable and get one result'; + END IF; + RETURN NEW; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER assessment_practice_submission_guard +BEFORE UPDATE OR DELETE ON assessment_practice_submissions +FOR EACH ROW EXECUTE FUNCTION assessment_practice_submission_guard(); + +-- The execution job of a submission. mode is copied from the submission so +-- the worker can run final submissions before debug runs without a join. +CREATE TABLE assessment_practice_jobs ( + submission_id uuid NOT NULL, + mode text NOT NULL, + -- queued: waits for the worker; running: the worker holds it; finished: + -- the result is stored; failed: the infrastructure gave up on it, which + -- is never a verdict on the code. + state text NOT NULL, + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + finished_at timestamptz, + CONSTRAINT assessment_practice_jobs_pkey PRIMARY KEY (submission_id), + CONSTRAINT assessment_practice_jobs_submission_fk FOREIGN KEY (submission_id) + REFERENCES assessment_practice_submissions (id) ON DELETE CASCADE, + CONSTRAINT assessment_practice_jobs_mode CHECK (mode IN ('public', 'final')), + CONSTRAINT assessment_practice_jobs_state CHECK ( + state IN ('queued', 'running', 'finished', 'failed') + ), + CONSTRAINT assessment_practice_jobs_finished CHECK ( + (state IN ('finished', 'failed')) = (finished_at IS NOT NULL) + AND created_at <= updated_at + AND (finished_at IS NULL OR finished_at >= created_at) + ) +); + +-- Serves the scan of unfinished jobs, which stays small while finished rows +-- accumulate. +CREATE INDEX assessment_practice_jobs_active_idx +ON assessment_practice_jobs (created_at, submission_id) +WHERE state IN ('queued', 'running'); + +-- +goose Down +DROP TABLE assessment_practice_jobs; +DROP TRIGGER assessment_practice_submission_guard ON assessment_practice_submissions; +DROP FUNCTION assessment_practice_submission_guard(); +DROP TABLE assessment_practice_submissions; +DROP TRIGGER assessment_practice_immutable_task ON assessment_practices; +DROP FUNCTION assessment_practice_immutable_task(); +DROP TABLE assessment_practices; diff --git a/backend/db/migrations/00053_create_assessment_practice_queue.sql b/backend/db/migrations/00053_create_assessment_practice_queue.sql new file mode 100644 index 0000000..a4ad633 --- /dev/null +++ b/backend/db/migrations/00053_create_assessment_practice_queue.sql @@ -0,0 +1,73 @@ +-- +goose Up +-- The practice queue: the execution jobs of practice submissions become +-- durable work items that one worker at a time runs on the code runner. +-- +-- The queue holds at most one running and ten queued jobs. Admission and +-- the claim both take the transaction-scoped advisory lock of the queue and +-- count the unfinished jobs, so the limits hold across backend instances. A +-- job beyond them is never inserted: the command answers busy and stores +-- nothing that would consume an attempt. +-- +-- A running job holds a lease. A worker that stops without finishing leaves +-- the lease to expire, and the next claim takes the job over with the same +-- generation, so the runner, which is idempotent by run ID, returns the run +-- it already has instead of starting a second one. Lease and retry times come +-- from the application clock. +ALTER TABLE assessment_practice_jobs +-- Generation of the run key: raised after the runner could not evaluate +-- the source, so the next try is a new run. +ADD COLUMN generation integer NOT NULL DEFAULT 0, +-- Failed tries and expired leases counted so far. A busy runner counts +-- nothing. +ADD COLUMN attempts integer NOT NULL DEFAULT 0, +-- When a worker may claim a queued job: at once, after the wait the runner +-- asked for when it was busy, or after the backoff of a failed try. +ADD COLUMN available_at timestamptz, +ADD COLUMN lease_owner uuid, +ADD COLUMN lease_expires_at timestamptz, +-- When the running try was claimed; it bounds how long a run may stay +-- unfinished on the runner. +ADD COLUMN started_at timestamptz, +-- Bounded cause of the last failed try; never runner or candidate text. +ADD COLUMN last_error_class text; + +UPDATE assessment_practice_jobs SET available_at = created_at; + +ALTER TABLE assessment_practice_jobs +ALTER COLUMN available_at SET NOT NULL, +ADD CONSTRAINT assessment_practice_jobs_lease_when_running CHECK ( + (state = 'running') = (lease_owner IS NOT NULL) + AND (lease_owner IS NULL) = (lease_expires_at IS NULL) + AND (lease_owner IS NULL) = (started_at IS NULL) +), +ADD CONSTRAINT assessment_practice_jobs_counters CHECK ( + generation >= 0 AND attempts BETWEEN 0 AND 100 +), +ADD CONSTRAINT assessment_practice_jobs_error_class CHECK ( + last_error_class IS NULL OR last_error_class IN ( + 'runner_unavailable', + 'runner_infrastructure_failure', + 'invalid_request', + 'run_timeout', + 'lease_expired' + ) +); + +-- Serves the claim of the next queued job. +CREATE INDEX assessment_practice_jobs_queued_idx +ON assessment_practice_jobs (available_at, created_at) +WHERE state = 'queued'; + +-- +goose Down +DROP INDEX assessment_practice_jobs_queued_idx; +ALTER TABLE assessment_practice_jobs +DROP CONSTRAINT assessment_practice_jobs_error_class, +DROP CONSTRAINT assessment_practice_jobs_counters, +DROP CONSTRAINT assessment_practice_jobs_lease_when_running, +DROP COLUMN last_error_class, +DROP COLUMN started_at, +DROP COLUMN lease_expires_at, +DROP COLUMN lease_owner, +DROP COLUMN available_at, +DROP COLUMN attempts, +DROP COLUMN generation; diff --git a/backend/db/migrations/00054_add_practice_job_runner_run.sql b/backend/db/migrations/00054_add_practice_job_runner_run.sql new file mode 100644 index 0000000..6eb3075 --- /dev/null +++ b/backend/db/migrations/00054_add_practice_job_runner_run.sql @@ -0,0 +1,20 @@ +-- +goose Up +-- A finished practice job keeps the opaque run ID under which the code runner +-- held the run that produced the stored result. The ID is the HMAC-derived +-- value of the run key (attempt item, submission, generation) that the runner +-- itself logs, so an operator can match a stored result to one runner run +-- without the runner learning who the candidate is. Only the finishing try +-- writes it, in the transaction that stores the result; a failed or unfinished +-- job has none. The ID is unique, because one run produces at most one result. +ALTER TABLE assessment_practice_jobs +ADD COLUMN runner_run_id uuid, +ADD CONSTRAINT assessment_practice_jobs_runner_run_state CHECK ( + runner_run_id IS NULL OR state = 'finished' +), +ADD CONSTRAINT assessment_practice_jobs_runner_run_key UNIQUE (runner_run_id); + +-- +goose Down +ALTER TABLE assessment_practice_jobs +DROP CONSTRAINT assessment_practice_jobs_runner_run_key, +DROP CONSTRAINT assessment_practice_jobs_runner_run_state, +DROP COLUMN runner_run_id; diff --git a/backend/db/migrations_test.go b/backend/db/migrations_test.go new file mode 100644 index 0000000..3a37086 --- /dev/null +++ b/backend/db/migrations_test.go @@ -0,0 +1,44 @@ +package db + +import ( + "io/fs" + "regexp" + "strings" + "testing" +) + +var migrationNamePattern = regexp.MustCompile(`^[0-9]{5}_[a-z0-9_]+\.sql$`) + +// TestMigrationsHaveSequentialNamesAndBothDirections runs without a database so +// make -C backend check catches a malformed or one-way migration. +func TestMigrationsHaveSequentialNamesAndBothDirections(t *testing.T) { + migrations, err := Migrations() + if err != nil { + t.Fatalf("Migrations() error = %v", err) + } + names, err := fs.Glob(migrations, "*.sql") + if err != nil { + t.Fatalf("list migrations: %v", err) + } + if len(names) == 0 { + t.Fatal("no embedded migrations") + } + for _, name := range names { + if !migrationNamePattern.MatchString(name) { + t.Fatalf("migration %s does not match NNNNN_description.sql", name) + } + content, err := fs.ReadFile(migrations, name) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + text := string(content) + up := strings.Index(text, "-- +goose Up") + down := strings.Index(text, "-- +goose Down") + if up < 0 || down < up { + t.Fatalf("migration %s needs a -- +goose Up section followed by a -- +goose Down section", name) + } + if strings.TrimSpace(text[down+len("-- +goose Down"):]) == "" { + t.Fatalf("migration %s has an empty Down section", name) + } + } +} diff --git a/backend/db/privacy_queries_test.go b/backend/db/privacy_queries_test.go new file mode 100644 index 0000000..3d8b117 --- /dev/null +++ b/backend/db/privacy_queries_test.go @@ -0,0 +1,153 @@ +package db + +import ( + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" +) + +// directPublicationReaders are the only queries that may name the table +// candidate_publications. The first three are the candidate's own settings +// queries; the remaining reads are narrowly scoped lock/recheck operations +// that require current C2. Organization reads also exclude hidden +// organizations, and candidate preview reads remain owner-scoped. A new +// query that reads the table directly fails this test until it is reviewed. +// +// Only queries/*.sql are covered: the project keeps SQL in sqlc queries and +// migrations, and the standards forbid raw SQL in Go code. +var directPublicationReaders = []string{ + "ReadCandidatePrivacySettings", + "ReadCandidatePublication", + "InsertCandidatePublication", + "UpdateCandidatePublication", +} + +var ownerScopedPublicationQueries = []string{ + "LockPublicationForCandidatePreview", + "LockVisiblePublicationForView", + "LockCandidatePublicationForConsentRevocation", +} + +var ownerPreviewQueries = []string{"ReadCandidateViewSourceForPreview"} + +var ( + // sqlc accepts both comment forms and tolerates trailing whitespace. + queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`) + // Any mention of the marker, to count headers that the pattern missed. + queryMarkerPattern = regexp.MustCompile(`(?i)name:\s*\w+\s+:\w+`) + publicationTableName = regexp.MustCompile(`(?i)\bcandidate_publications\b`) + effectiveViewName = regexp.MustCompile(`(?i)\bcandidate_effective_publications\b`) + hiddenTableName = regexp.MustCompile(`(?i)\bcandidate_hidden_organizations\b`) + lineComment = regexp.MustCompile(`(?m)--.*$`) + blockComment = regexp.MustCompile(`(?s)/\*.*?\*/`) +) + +func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) { + files, err := filepath.Glob("queries/*.sql") + if err != nil || len(files) == 0 { + t.Fatalf("list the query files = %v, %v", files, err) + } + var found []string + statements := make(map[string]string) + for _, file := range files { + content, err := os.ReadFile(file) + if err != nil { + t.Fatalf("read %s: %v", file, err) + } + text := string(content) + headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1) + if markers := len(queryMarkerPattern.FindAllString(text, -1)); markers != len(headers) { + t.Fatalf("%s has %d query markers but %d parsed headers: use the sqlc header form so every query is checked", file, markers, len(headers)) + } + for index, header := range headers { + end := len(text) + if index+1 < len(headers) { + end = headers[index+1][0] + } + // Comments may name the table; statements may not. + statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "") + name := text[header[2]:header[3]] + statements[name] = strings.Join(strings.Fields(statement), " ") + if publicationTableName.MatchString(statement) { + found = append(found, name) + } + if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) && !slices.Contains(ownerPreviewQueries, name) { + t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name) + } + } + } + slices.Sort(found) + want := slices.Concat(slices.Clone(directPublicationReaders), ownerScopedPublicationQueries) + slices.Sort(want) + if !slices.Equal(found, want) { + t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want) + } + closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"]) + for _, required := range []string{ + "select greatest(candidate_publications.published_at, consent_records.revoked_at)", + "inner join consent_records", + "candidate_publications.user_id = sqlc.arg(user_id)", + "candidate_publications.state = 'published'", + "consent_records.id = any(sqlc.arg(consent_record_ids)::uuid [])", + "consent_records.subject_id = candidate_publications.user_id", + "consent_records.purpose = 'c2'", + "consent_records.revoked_at is not null", + "for update of candidate_publications", + } { + if !strings.Contains(closeQuery, required) { + t.Errorf("consent revocation query lacks %q: %s", required, closeQuery) + } + } + settingsQuery := strings.ToLower(statements["ReadCandidatePrivacySettings"]) + for _, required := range []string{ + "users.id = sqlc.arg(user_id)", + "left join candidate_publications", + "left join consent_records", + "left join candidate_search_statuses", + "from candidate_hidden_organizations", + } { + if !strings.Contains(settingsQuery, required) { + t.Errorf("candidate settings query lacks %q: %s", required, settingsQuery) + } + } + for _, forbidden := range []string{"candidate_profiles", "profile_claims", "candidate_questionnaires", "contact_email", "contact_phone"} { + if strings.Contains(settingsQuery, forbidden) { + t.Errorf("candidate settings query reaches private profile data %q: %s", forbidden, settingsQuery) + } + } + if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") { + t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery) + } + previewQuery := strings.ToLower(statements["ReadCandidateViewSourceForPreview"]) + for _, required := range []string{ + "from candidate_effective_publications as effective", + "where effective.user_id = sqlc.arg(candidate_id)", + "claim.kind in ('stack', 'role', 'experience', 'project')", + "coalesce(questionnaire.work_formats, '{}'::text[])", + } { + if !strings.Contains(previewQuery, required) { + t.Errorf("owner preview query lacks %q: %s", required, previewQuery) + } + } + visibleLock := strings.ToLower(statements["LockVisiblePublicationForView"]) + for _, required := range []string{ + "candidate_publications.user_id = sqlc.arg(candidate_id)", + "candidate_publications.state = 'published'", + "candidate_publications.consent_record_id = sqlc.arg(consent_record_id)", + "consent_records.purpose = 'c2'", + "consent_records.revoked_at is null", + "candidate_hidden_organizations", + "for share of candidate_publications, consent_records", + } { + if !strings.Contains(visibleLock, required) { + t.Errorf("organization card lock lacks %q: %s", required, visibleLock) + } + } + visibleSource := strings.ToLower(statements["ListVisibleCandidateViewSources"]) + if !effectiveViewName.MatchString(visibleSource) || !hiddenTableName.MatchString(visibleSource) { + t.Errorf("organization cohort source must use the effective publication view and hidden-organization filter: %s", visibleSource) + } +} diff --git a/backend/db/queries/assessment_attempts.sql b/backend/db/queries/assessment_attempts.sql new file mode 100644 index 0000000..614335a --- /dev/null +++ b/backend/db/queries/assessment_attempts.sql @@ -0,0 +1,449 @@ +-- Finds candidate-requested selections across currently opened categories. +-- The adapter validates policy and manifest freshness, locks the category, +-- then runs this query again before it returns any pinned families. +-- name: ResolveCurrentAssessmentSelection :many +WITH current_openings AS ( + SELECT DISTINCT ON (category) + id, + category, + policy_version_id, + required_families + FROM assessment_category_openings + ORDER BY category, opened_at DESC, id DESC +), current_policy AS ( + SELECT id, version + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= statement_timestamp() + ORDER BY version DESC + LIMIT 1 +) +SELECT + opening.id AS opening_id, + opening.category, + opening.policy_version_id, + opening.required_families, + COALESCE(( + SELECT count(DISTINCT family.family_key)::integer + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), 0)::integer AS published_count, + policy.id AS effective_policy_id, + policy.version AS effective_policy_version, + binding.specialization, + binding.grade, + binding.task_languages, + binding.published_manifest_sha256, + COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'family_key', family.family_key, + 'version', family.version, + 'content_sha256', encode(family.content_sha256, 'hex') + ) ORDER BY family.family_key, family.version + ) + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), '[]'::jsonb)::text AS published_manifest +FROM current_openings AS opening +JOIN assessment_category_catalog_bindings AS binding + ON binding.opening_id = opening.id +LEFT JOIN current_policy AS policy ON true +WHERE binding.specialization = sqlc.arg(specialization) + AND binding.grade = sqlc.arg(grade) + AND ( + (sqlc.narg(task_language)::text IS NULL AND cardinality(binding.task_languages) = 0) + OR sqlc.narg(task_language)::text = ANY(binding.task_languages) + ) +ORDER BY opening.category; + +-- Serializes root quota checks for one candidate before taking its optional +-- specialization or training lock. All callers acquire these locks in order. +-- name: LockAssessmentAttemptScope :exec +WITH candidate_lock AS MATERIALIZED ( + SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.attempt:user:' || sqlc.arg(user_id)::text, + 0 + )) +) +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.attempt:track:' || sqlc.arg(user_id)::text || ':' || + COALESCE(sqlc.narg(specialization)::text, 'training'), + 0 +)) +FROM candidate_lock; + +-- Locks the active real attempt after LockAssessmentAttemptScope. +-- name: GetActiveAssessmentAttemptForSpecialization :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND specialization = sqlc.arg(specialization) + AND kind IN ('root', 'corrective') + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') +ORDER BY created_at DESC, id DESC +LIMIT 1 +FOR UPDATE; + +-- Locks the one active express attempt after LockAssessmentAttemptScope. +-- name: GetActiveTrainingAssessmentAttempt :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND kind = 'demo_express' + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') +ORDER BY created_at DESC, id DESC +LIMIT 1 +FOR UPDATE; + +-- Reads the latest root in a specialization, optionally restricted to grade. +-- name: GetLatestRootAssessmentAttempt :one +SELECT + attempt.id, attempt.user_id, attempt.kind, attempt.mode, attempt.state, attempt.outcome, + attempt.bank_category, attempt.specialization, attempt.target_grade, attempt.task_language, + attempt.root_attempt_id, attempt.product_policy_version_id, attempt.product_policy_version, + attempt.grading_policy_version_id, attempt.opening_id, attempt.opening_manifest_sha256, + attempt.training_binding_id, attempt.training_manifest_sha256, attempt.bank_version, + attempt.algorithm_version, attempt.created_at, attempt.updated_at, attempt.expires_at, + attempt.chain_deadline, attempt.idle_timeout_seconds, attempt.max_sessions, attempt.sessions_used, + attempt.session_started_at, attempt.last_activity_at, attempt.version, attempt.ended_at +FROM assessment_attempts AS attempt +LEFT JOIN assessment_attempt_results AS result + ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id +WHERE attempt.user_id = sqlc.arg(user_id) + AND attempt.specialization = sqlc.arg(specialization) + AND attempt.kind = 'root' + AND (sqlc.narg(target_grade)::text IS NULL OR attempt.target_grade = sqlc.narg(target_grade)::text) + AND attempt.state <> 'insufficient_bank' + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable') +ORDER BY attempt.created_at DESC, attempt.id DESC +LIMIT 1 +FOR SHARE OF attempt; + +-- Counts root attempts only; the caller applies the effective policy's +-- configured window and the product's approved accounting scope. +-- name: CountRootAssessmentAttemptsSince :one +SELECT count(*)::bigint +FROM assessment_attempts AS attempt +LEFT JOIN assessment_attempt_results AS result + ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id +WHERE attempt.user_id = sqlc.arg(user_id) + AND attempt.kind = 'root' + AND attempt.created_at >= sqlc.arg(since)::timestamptz + AND (sqlc.narg(specialization)::text IS NULL OR attempt.specialization = sqlc.narg(specialization)::text) + AND attempt.state <> 'insufficient_bank' + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable'); + +-- Lists explicit immutable training bindings for the effective product +-- policy. Callers reject more than one matching active binding as ambiguous. +-- name: ListCurrentAssessmentTrainingBindings :many +SELECT + binding.id, + binding.category, + binding.product_policy_version_id, + binding.item_count, + binding.manifest_sha256, + binding.family_manifest, + policy.version AS product_policy_version +FROM assessment_training_bank_bindings AS binding +JOIN policy_versions AS policy ON policy.id = binding.product_policy_version_id +WHERE policy.policy_key = 'product' + AND policy.effective_at <= statement_timestamp() + AND NOT EXISTS ( + SELECT 1 FROM policy_versions AS newer + WHERE newer.policy_key = 'product' + AND newer.effective_at <= statement_timestamp() + AND newer.version > policy.version + ) +ORDER BY binding.category, binding.created_at DESC, binding.id; + +-- Reads the exact family membership pinned by a training binding. +-- name: ListAssessmentTrainingBindingFamilies :many +SELECT + family_id, + ordinal, + family_key, + family_version, + content_sha256 +FROM assessment_training_bank_binding_families +WHERE binding_id = sqlc.arg(binding_id) +ORDER BY ordinal; + +-- Inserts the attempt header. The database guard rechecks the current policy, +-- opening or disjoint training binding, and immutable pins. +-- name: InsertAssessmentAttempt :exec +INSERT INTO assessment_attempts ( + id, + user_id, + kind, + mode, + state, + outcome, + bank_category, + specialization, + target_grade, + task_language, + root_attempt_id, + product_policy_version_id, + product_policy_version, + grading_policy_version_id, + opening_id, + opening_manifest_sha256, + training_binding_id, + training_manifest_sha256, + bank_version, + algorithm_version, + created_at, + updated_at, + expires_at, + chain_deadline, + idle_timeout_seconds, + max_sessions, + sessions_used, + session_started_at, + last_activity_at, + version, + ended_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(mode), + sqlc.arg(state), + sqlc.narg(outcome), + sqlc.arg(bank_category), + sqlc.narg(specialization), + sqlc.narg(target_grade), + sqlc.narg(task_language), + sqlc.arg(root_attempt_id), + sqlc.arg(product_policy_version_id), + sqlc.arg(product_policy_version), + sqlc.narg(grading_policy_version_id), + sqlc.narg(opening_id), + sqlc.narg(opening_manifest_sha256), + sqlc.narg(training_binding_id), + sqlc.narg(training_manifest_sha256), + sqlc.arg(bank_version), + sqlc.arg(algorithm_version), + sqlc.arg(created_at), + sqlc.arg(updated_at), + sqlc.arg(expires_at), + sqlc.narg(chain_deadline), + sqlc.arg(idle_timeout_seconds), + sqlc.arg(max_sessions), + sqlc.arg(sessions_used), + sqlc.arg(session_started_at), + sqlc.arg(last_activity_at), + sqlc.arg(version), + sqlc.narg(ended_at) +); + +-- Stores the immutable generated variant and empty answer slot. +-- name: InsertAssessmentAttemptItem :exec +INSERT INTO assessment_attempt_items ( + id, + attempt_id, + ordinal, + family_id, + family_key, + family_version, + family_content_sha256, + variant, + answer, + answered_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(ordinal), + sqlc.arg(family_id), + sqlc.arg(family_key), + sqlc.arg(family_version), + sqlc.arg(family_content_sha256), + sqlc.arg(variant), + sqlc.narg(answer), + sqlc.narg(answered_at) +); + +-- Returns a full private attempt only to its candidate. +-- name: GetAssessmentAttemptForCandidate :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id) +FOR SHARE; + +-- Reads the immutable attempt kind without locking the row. Session commands +-- use this only to decide whether C3 applies before acquiring the row lock. +-- name: GetAssessmentAttemptKindForCandidate :one +SELECT kind +FROM assessment_attempts +WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id); + +-- Locks one owner-scoped attempt while a session command performs its CAS. +-- name: LockAssessmentAttemptForCandidate :one +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id) +FOR UPDATE; + +-- Reads chain headers in creation order. The use case verifies root eligibility +-- and descending target grades in the domain before it creates a correction. +-- name: ListAssessmentAttemptChain :many +SELECT + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND specialization = sqlc.arg(specialization) + AND (id = sqlc.arg(root_attempt_id) OR root_attempt_id = sqlc.arg(root_attempt_id)) +ORDER BY created_at, id +FOR SHARE; + +-- Reads private frozen variants and candidate answer bytes in stable order. +-- name: ListAssessmentAttemptItems :many +SELECT + id, attempt_id, ordinal, family_id, family_key, family_version, + family_content_sha256, variant::text AS variant, answer, answered_at +FROM assessment_attempt_items +WHERE attempt_id = sqlc.arg(attempt_id) +ORDER BY ordinal; + +-- Applies a versioned session transition after the attempt row is locked. +-- name: UpdateAssessmentAttemptSession :one +UPDATE assessment_attempts +SET + state = sqlc.arg(state), + outcome = sqlc.narg(outcome), + updated_at = sqlc.arg(updated_at), + sessions_used = sqlc.arg(sessions_used), + session_started_at = sqlc.arg(session_started_at), + last_activity_at = sqlc.arg(last_activity_at), + version = sqlc.arg(version), + ended_at = sqlc.narg(ended_at) +WHERE id = sqlc.arg(id) + AND user_id = sqlc.arg(user_id) + AND version = sqlc.arg(expected_version) +RETURNING + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at; + +-- Stores one final answer before advancing the enclosing attempt version. +-- The caller holds the owner-scoped attempt row lock for the surrounding unit. +-- name: UpdateAssessmentAttemptItemAnswer :one +UPDATE assessment_attempt_items +SET answer = sqlc.arg(answer), answered_at = sqlc.arg(answered_at) +WHERE attempt_id = sqlc.arg(attempt_id) + AND id = sqlc.arg(item_id) + AND answer IS NULL +RETURNING id; + +-- Applies an answer, expiry, or finalization transition after the attempt row +-- is locked. Session limits and all immutable pins remain unchanged. +-- name: UpdateAssessmentAttemptTransition :one +UPDATE assessment_attempts +SET + state = sqlc.arg(state), + outcome = sqlc.narg(outcome), + updated_at = sqlc.arg(updated_at), + last_activity_at = sqlc.arg(last_activity_at), + version = sqlc.arg(version), + ended_at = sqlc.narg(ended_at) +WHERE id = sqlc.arg(id) + AND user_id = sqlc.arg(user_id) + AND version = sqlc.arg(expected_version) +RETURNING + id, user_id, kind, mode, state, outcome, bank_category, specialization, + target_grade, task_language, root_attempt_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, created_at, updated_at, expires_at, + chain_deadline, idle_timeout_seconds, max_sessions, sessions_used, + session_started_at, last_activity_at, version, ended_at; + +-- A newly reserved generic idempotency window can replace an expired typed +-- outcome before the new immutable response is inserted. +-- name: DeleteAssessmentAttemptIdempotencyOutcome :exec +DELETE FROM assessment_attempt_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- name: InsertAssessmentAttemptIdempotencyOutcome :exec +INSERT INTO assessment_attempt_idempotency_outcomes ( + scope_hash, operation, status_code, problem_code, response_snapshot, + response_schema_version, pending_item_ids, created_at +) VALUES ( + sqlc.arg(scope_hash), sqlc.arg(operation), sqlc.arg(status_code), + sqlc.narg(problem_code), sqlc.narg(response_snapshot), 1, + sqlc.arg(pending_item_ids)::uuid[], transaction_timestamp() +); + +-- name: GetAssessmentAttemptIdempotencyOutcome :one +SELECT operation, status_code, problem_code, + CAST(COALESCE(response_snapshot::text, ''::text) AS text) AS response_snapshot, + pending_item_ids +FROM assessment_attempt_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- Stores one immutable candidate-visible result with the decision rationale +-- and source versions used by its finalized attempt. +-- name: InsertAssessmentAttemptResult :exec +INSERT INTO assessment_attempt_results ( + attempt_id, user_id, result_snapshot, schema_version, kind, mode, outcome, + product_policy_version_id, product_policy_version, + grading_policy_version_id, opening_id, opening_manifest_sha256, + training_binding_id, training_manifest_sha256, bank_version, algorithm_version, + rationale_rule, pass_mark_basis_points, scored_items, raw_score, pass_points, decided_at +) +VALUES ( + sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot)::jsonb, 1, + sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome), + sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version), + sqlc.narg(grading_policy_version_id), sqlc.narg(opening_id), sqlc.narg(opening_manifest_sha256), + sqlc.narg(training_binding_id), sqlc.narg(training_manifest_sha256), + sqlc.arg(bank_version), sqlc.arg(algorithm_version), sqlc.arg(rationale_rule), + sqlc.narg(pass_mark_basis_points), sqlc.narg(scored_items), sqlc.narg(raw_score), + sqlc.narg(pass_points), sqlc.arg(decided_at) +); + +-- Reads a result only for the owning candidate. +-- name: GetAssessmentAttemptResult :one +SELECT result_snapshot::text AS result_snapshot +FROM assessment_attempt_results +WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id); diff --git a/backend/db/queries/assessment_availability.sql b/backend/db/queries/assessment_availability.sql new file mode 100644 index 0000000..4d774e6 --- /dev/null +++ b/backend/db/queries/assessment_availability.sql @@ -0,0 +1,173 @@ +-- Returns current reviewed grade/language bindings and the live published +-- family manifest at one caller-supplied database time. The adapter verifies +-- the pinned manifest hash before exposing only family keys. +-- name: ListCurrentAssessmentAvailabilitySelections :many +WITH current_policy AS ( + SELECT id, version + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= sqlc.arg(as_of)::timestamptz + ORDER BY version DESC + LIMIT 1 +), current_openings AS ( + SELECT DISTINCT ON (category) + id, + category, + policy_version_id, + required_families, + opened_at + FROM assessment_category_openings + ORDER BY category, opened_at DESC, id DESC +) +SELECT + opening.id AS opening_id, + opening.category, + opening.policy_version_id, + opening.required_families, + COALESCE(( + SELECT count(DISTINCT family.family_key)::integer + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), 0)::integer AS published_count, + policy.id AS effective_policy_id, + policy.version AS effective_policy_version, + binding.specialization, + binding.grade, + binding.task_languages, + binding.published_manifest_sha256, + COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'family_key', family.family_key, + 'version', family.version, + 'content_sha256', encode(family.content_sha256, 'hex') + ) ORDER BY family.family_key, family.version + ) + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), '[]'::jsonb)::text AS published_manifest +FROM current_openings AS opening +JOIN assessment_category_catalog_bindings AS binding + ON binding.opening_id = opening.id +LEFT JOIN current_policy AS policy ON true +ORDER BY binding.specialization, binding.grade, binding.task_languages, opening.category; + +-- Reads an active real attempt without taking the write lock used by create. +-- The availability GET never expires or otherwise mutates this row. +-- name: GetAssessmentAvailabilityActiveAttempt :one +SELECT id, expires_at +FROM assessment_attempts +WHERE user_id = sqlc.arg(user_id) + AND specialization = sqlc.arg(specialization) + AND kind IN ('root', 'corrective') + AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize') +ORDER BY created_at DESC, id DESC +LIMIT 1; + +-- Reads roots within the policy horizon and the last header in each correction +-- chain. It deliberately omits frozen items, answers, and row locks. +-- name: ListAssessmentAvailabilityRootSummaries :many +SELECT + root.target_grade AS root_target_grade, + root.created_at AS root_created_at, + root.updated_at AS root_updated_at, + root.expires_at AS root_expires_at, + root.state AS root_state, + root.outcome AS root_outcome, + root.chain_deadline AS root_chain_deadline, + latest.target_grade AS latest_target_grade, + latest.updated_at AS latest_updated_at, + latest.expires_at AS latest_expires_at, + latest.state AS latest_state, + latest.outcome AS latest_outcome, + latest.chain_deadline AS latest_chain_deadline, + COALESCE(latest_result.result_snapshot->>'not_determined_reason', '')::text AS latest_platform_error +FROM assessment_attempts AS root +JOIN LATERAL ( + SELECT attempt.* + FROM assessment_attempts AS attempt + WHERE attempt.user_id = root.user_id + AND attempt.root_attempt_id = root.id + AND attempt.kind IN ('root', 'corrective') + ORDER BY attempt.created_at DESC, attempt.id DESC + LIMIT 1 +) AS latest ON true +LEFT JOIN assessment_attempt_results AS root_result + ON root_result.attempt_id = root.id AND root_result.user_id = root.user_id +LEFT JOIN assessment_attempt_results AS latest_result + ON latest_result.attempt_id = latest.id AND latest_result.user_id = latest.user_id +WHERE root.user_id = sqlc.arg(user_id) + AND root.specialization = sqlc.arg(specialization) + AND root.kind = 'root' + AND root.created_at >= sqlc.arg(since)::timestamptz + AND root.state <> 'insufficient_bank' + AND COALESCE(root_result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable') +ORDER BY root.created_at DESC, root.id DESC; + +-- Counts eligible root attempts in a policy window and computes the instant +-- at which one additional root slot opens. The microsecond adjustment matches +-- the creation predicate created_at >= since at PostgreSQL timestamp precision. +-- name: GetAssessmentRootQuotaAvailability :one +WITH eligible AS ( + SELECT attempt.id, attempt.created_at + FROM assessment_attempts AS attempt + LEFT JOIN assessment_attempt_results AS result + ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id + WHERE attempt.user_id = sqlc.arg(user_id) + AND attempt.kind = 'root' + AND attempt.state <> 'insufficient_bank' + AND attempt.created_at >= sqlc.arg(since)::timestamptz + AND attempt.created_at <= sqlc.arg(as_of)::timestamptz + AND COALESCE(result.result_snapshot->>'not_determined_reason', '') + NOT IN ('insufficient_bank', 'sandbox_unavailable') +), total AS ( + SELECT count(*)::bigint AS attempt_count FROM eligible +) +SELECT + total.attempt_count, + CASE WHEN total.attempt_count >= sqlc.arg(max_attempts)::bigint THEN ( + SELECT eligible.created_at + + make_interval(secs => sqlc.arg(window_seconds)::double precision) + + interval '1 microsecond' + FROM eligible + ORDER BY eligible.created_at, eligible.id + LIMIT 1 + OFFSET (total.attempt_count - sqlc.arg(max_attempts)::bigint) + ) ELSE NULL::timestamptz END AS available_at +FROM total; + +-- Counts family instances disclosed after the non-repeat boundary. The first +-- item is disclosed when the attempt is created; each later item is disclosed +-- when the preceding answer is accepted. This per-item timestamp prevents a +-- long-running attempt from making later items appear older than they are. +-- Counting the first unanswered item after expiry is conservative when the +-- final response was lost, while frozen future items remain excluded. +-- name: ListAssessmentDisclosedFamilyKeys :many +WITH progress AS ( + SELECT + attempt.id AS attempt_id, + attempt.created_at, + COALESCE(max(item.ordinal) FILTER (WHERE item.answered_at IS NOT NULL), 0) + 1 AS last_disclosed_ordinal + FROM assessment_attempts AS attempt + JOIN assessment_attempt_items AS item ON item.attempt_id = attempt.id + WHERE attempt.user_id = sqlc.arg(user_id) + AND attempt.kind IN ('root', 'corrective') + AND attempt.expires_at > sqlc.arg(since)::timestamptz + GROUP BY attempt.id +), disclosed AS ( + SELECT + item.family_key, + CASE + WHEN item.ordinal = 1 THEN progress.created_at + ELSE previous.answered_at + END AS disclosed_at + FROM progress + JOIN assessment_attempt_items AS item ON item.attempt_id = progress.attempt_id + LEFT JOIN assessment_attempt_items AS previous + ON previous.attempt_id = item.attempt_id AND previous.ordinal = item.ordinal - 1 + WHERE item.ordinal <= progress.last_disclosed_ordinal +) +SELECT DISTINCT disclosed.family_key +FROM disclosed +WHERE disclosed.disclosed_at > sqlc.arg(since)::timestamptz +ORDER BY disclosed.family_key; diff --git a/backend/db/queries/assessment_bank.sql b/backend/db/queries/assessment_bank.sql new file mode 100644 index 0000000..8be358a --- /dev/null +++ b/backend/db/queries/assessment_bank.sql @@ -0,0 +1,340 @@ +-- Stores a new family version as a draft and returns the stored row with the +-- creation time set by the stamp trigger. A taken ID or (family_key, version) +-- returns no row instead of an error, so a conflict does not abort the +-- surrounding transaction. +-- name: InsertAssessmentFamily :one +INSERT INTO assessment_families ( + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle +) VALUES ( + sqlc.arg(id), + sqlc.arg(family_key), + sqlc.arg(version), + sqlc.arg(category), + sqlc.arg(specialization), + sqlc.arg(title), + sqlc.arg(bundle_name), + sqlc.arg(author), + sqlc.narg(reviewer), + sqlc.arg(review_status), + sqlc.arg(seed_generator), + sqlc.arg(answer_key), + sqlc.arg(rubric), + sqlc.arg(content_sha256), + sqlc.arg(hash_scheme), + 'draft' +) +ON CONFLICT DO NOTHING +RETURNING + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by; + +-- name: GetAssessmentFamilyByID :one +SELECT + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by +FROM assessment_families +WHERE id = sqlc.arg(id); + +-- name: GetAssessmentFamilyVersion :one +SELECT + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by +FROM assessment_families +WHERE + family_key = sqlc.arg(family_key) + AND version = sqlc.arg(version); + +-- name: GetLatestAssessmentFamily :one +SELECT + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by +FROM assessment_families +WHERE family_key = sqlc.arg(family_key) +ORDER BY version DESC +LIMIT 1; + +-- One page of the versions of a category in key and version order, after the +-- given position; an empty key and version 0 start at the beginning. The +-- (family_key, version) unique index serves the scan. +-- name: ListAssessmentFamiliesByCategory :many +SELECT + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by +FROM assessment_families +WHERE + category = sqlc.arg(category) + AND (family_key, version) > (sqlc.arg(after_key)::text, sqlc.arg(after_version)::integer) +ORDER BY family_key ASC, version ASC +LIMIT sqlc.arg(page_size); + +-- The published version of a family, if any. The partial unique index +-- assessment_families_one_published_key allows at most one. +-- name: GetPublishedAssessmentFamily :one +SELECT + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by +FROM assessment_families +WHERE + family_key = sqlc.arg(family_key) + AND lifecycle = 'published'; + +-- Serializes the operations that change which versions of a category are +-- published or open the category, until the transaction ends. The key is +-- namespaced, so it cannot collide with another use of advisory locks. +-- name: LockAssessmentCategory :exec +SELECT pg_advisory_xact_lock( + hashtextextended('lincodex.assessment.category:' || sqlc.arg(category)::text, 0) +); + +-- Counts the families of a category that have at least one published +-- version, however many versions each has. +-- name: CountPublishedAssessmentFamilies :one +SELECT count(DISTINCT family_key)::integer AS published +FROM assessment_families +WHERE + category = sqlc.arg(category) + AND lifecycle = 'published'; + +-- Moves a draft to published by the named operator and returns the row with +-- the publication time set by the guard trigger. No row means the version +-- was not a draft any more. +-- name: PublishAssessmentFamily :one +UPDATE assessment_families +SET + lifecycle = 'published', + published_by = sqlc.arg(actor) +WHERE + id = sqlc.arg(id) + AND lifecycle = 'draft' +RETURNING + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by; + +-- name: RetireAssessmentFamily :one +UPDATE assessment_families +SET + lifecycle = 'retired', + retired_by = sqlc.arg(actor) +WHERE + id = sqlc.arg(id) + AND lifecycle = 'published' +RETURNING + id, + family_key, + version, + category, + specialization, + title, + bundle_name, + author, + reviewer, + review_status, + seed_generator, + answer_key, + rubric, + content_sha256, + hash_scheme, + lifecycle, + created_at, + published_at, + published_by, + retired_at, + retired_by; + +-- Stores an opening. The insert trigger derives required_families from the +-- policy document and counts the published families, and the coverage CHECK +-- refuses the row when they are fewer; both numbers from the caller are +-- replaced by the trigger's. +-- name: InsertAssessmentCategoryOpening :one +INSERT INTO assessment_category_openings ( + id, + category, + policy_version_id, + opened_by, + required_families, + published_families, + opened_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(category), + sqlc.arg(policy_version_id), + sqlc.arg(opened_by), + 0, + 0, + clock_timestamp() +) +RETURNING + id, + category, + policy_version_id, + opened_by, + required_families, + published_families, + opened_at; + +-- name: GetCurrentAssessmentCategoryOpening :one +SELECT + id, + category, + policy_version_id, + opened_by, + required_families, + published_families, + opened_at +FROM assessment_category_openings +WHERE category = sqlc.arg(category) +ORDER BY opened_at DESC, id DESC +LIMIT 1; + +-- The database clock, which stamps the effective time of a policy version, so +-- "the version in force now" is judged against the same clock. +-- name: GetDatabaseTime :one +SELECT clock_timestamp()::timestamptz AS now; diff --git a/backend/db/queries/assessment_leak_traces.sql b/backend/db/queries/assessment_leak_traces.sql new file mode 100644 index 0000000..07c66f3 --- /dev/null +++ b/backend/db/queries/assessment_leak_traces.sql @@ -0,0 +1,51 @@ +-- Real attempts in ascending identifier order, so that a caller can walk all of +-- them in pages. Only the identifier and the time span are read. +-- name: ListAssessmentTraceAttempts :many +SELECT id, created_at, expires_at +FROM assessment_attempts +WHERE kind IN ('root', 'corrective') AND id > sqlc.arg(after_id) +ORDER BY id +LIMIT sqlc.arg(row_limit); + +-- The unmarked statements of real attempts whose text, with runs of white space +-- collapsed, contains the fragment. The fragment is matched literally: position +-- is not a pattern. The scan reads the stored variant of every item, which is +-- fine for an operator command and not for a request path. +-- name: FindAssessmentTraceStatements :many +SELECT + item.attempt_id, + (item.variant ->> 'Statement')::text AS statement +FROM assessment_attempt_items AS item +INNER JOIN assessment_attempts AS attempt ON item.attempt_id = attempt.id +WHERE + attempt.kind IN ('root', 'corrective') + AND position(sqlc.arg(fragment)::text IN regexp_replace((item.variant ->> 'Statement')::text, '\s+', ' ', 'g')) > 0 +ORDER BY item.attempt_id, item.ordinal +LIMIT sqlc.arg(row_limit); + +-- name: InsertAssessmentLeakTrace :exec +INSERT INTO assessment_leak_traces ( + id, + actor, + searched_at, + text_digest, + key_version, + text_runes, + status, + method, + attempt_id, + candidates, + evidence_bits +) VALUES ( + sqlc.arg(id), + sqlc.arg(actor), + sqlc.arg(searched_at), + sqlc.arg(text_digest), + sqlc.arg(key_version), + sqlc.arg(text_runes), + sqlc.arg(status), + sqlc.narg(method), + sqlc.narg(attempt_id), + sqlc.arg(candidates), + sqlc.arg(evidence_bits) +); diff --git a/backend/db/queries/assessment_practice.sql b/backend/db/queries/assessment_practice.sql new file mode 100644 index 0000000..02841ec --- /dev/null +++ b/backend/db/queries/assessment_practice.sql @@ -0,0 +1,161 @@ +-- Lock order of a practice command: the idempotency record, the attempt in +-- share mode, then the practice row. The attempt flows lock the attempt +-- first as well, so a practice command never waits for them in the opposite +-- order. + +-- Locks the owner's attempt in share mode, so its state cannot change while +-- a practice command decides on it, and reads the database time after the +-- lock. +-- name: LockAssessmentAttemptForPractice :one +SELECT + attempt.state, + attempt.expires_at, + clock_timestamp()::timestamptz AS database_time +FROM assessment_attempts AS attempt +WHERE + attempt.id = sqlc.arg(attempt_id) + AND attempt.user_id = sqlc.arg(user_id) +FOR SHARE; + +-- Locks one practice of the owner's attempt for a state change. +-- name: LockAssessmentPractice :one +SELECT + practice.id, + practice.attempt_id, + practice.user_id, + practice.kind, + practice.task, + practice.status, + practice.failure_reason, + practice.submitted_at, + practice.created_at +FROM assessment_practices AS practice +WHERE + practice.id = sqlc.arg(id) + AND practice.attempt_id = sqlc.arg(attempt_id) + AND practice.user_id = sqlc.arg(user_id) +FOR UPDATE; + +-- name: InsertAssessmentPractice :exec +INSERT INTO assessment_practices ( + id, + attempt_id, + user_id, + kind, + task, + status, + failure_reason, + submitted_at, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(task), + 'not_started', + NULL, + NULL, + sqlc.arg(created_at), + sqlc.arg(created_at) +); + +-- name: UpdateAssessmentPracticeState :execrows +UPDATE assessment_practices +SET + status = sqlc.arg(status), + failure_reason = sqlc.narg(failure_reason), + submitted_at = sqlc.narg(submitted_at), + updated_at = greatest(updated_at, sqlc.arg(updated_at)::timestamptz) +WHERE id = sqlc.arg(id); + +-- Finds the latest submission of the owner under an idempotency scope, which +-- a replay returns. +-- name: FindAssessmentPracticeSubmissionByScope :one +SELECT + submission.id, + submission.practice_id, + submission.mode +FROM assessment_practice_submissions AS submission +WHERE + submission.user_id = sqlc.arg(user_id) + AND submission.idempotency_scope = sqlc.arg(idempotency_scope) +ORDER BY submission.created_at DESC, submission.id DESC +LIMIT 1; + +-- The latest final submission of a practice: the solution the practice +-- state describes. +-- name: GetLatestFinalPracticeSubmission :one +SELECT + submission.id, + submission.language, + submission.source_sha256 +FROM assessment_practice_submissions AS submission +WHERE + submission.practice_id = sqlc.arg(practice_id) + AND submission.mode = 'final' +ORDER BY submission.created_at DESC, submission.id DESC +LIMIT 1; + +-- name: InsertAssessmentPracticeSubmission :exec +INSERT INTO assessment_practice_submissions ( + id, + practice_id, + user_id, + mode, + language, + source, + source_sha256, + custom_tests, + idempotency_scope, + created_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(practice_id), + sqlc.arg(user_id), + sqlc.arg(mode), + sqlc.arg(language), + sqlc.arg(source), + sqlc.arg(source_sha256), + sqlc.narg(custom_tests), + sqlc.arg(idempotency_scope), + sqlc.arg(created_at) +); + +-- Queues the execution job of a submission in the transaction that stores +-- the submission. The job is available at once. +-- name: InsertAssessmentPracticeJob :exec +INSERT INTO assessment_practice_jobs ( + submission_id, + mode, + state, + available_at, + created_at, + updated_at +) VALUES ( + sqlc.arg(submission_id), + sqlc.arg(mode), + 'queued', + sqlc.arg(created_at), + sqlc.arg(created_at), + sqlc.arg(created_at) +); + +-- Reads a debug run of the owner's attempt with the state of its job. +-- name: GetAssessmentPracticeRun :one +SELECT + submission.id, + submission.practice_id, + submission.created_at, + submission.result, + job.state, + job.finished_at +FROM assessment_practice_submissions AS submission +INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id +INNER JOIN assessment_practice_jobs AS job ON submission.id = job.submission_id +WHERE + submission.id = sqlc.arg(id) + AND submission.user_id = sqlc.arg(user_id) + AND submission.mode = 'public' + AND practice.attempt_id = sqlc.arg(attempt_id); diff --git a/backend/db/queries/assessment_practice_queue.sql b/backend/db/queries/assessment_practice_queue.sql new file mode 100644 index 0000000..7137a80 --- /dev/null +++ b/backend/db/queries/assessment_practice_queue.sql @@ -0,0 +1,194 @@ +-- The practice queue. Admission and the claim take the same +-- transaction-scoped advisory lock, so the count of unfinished jobs and the +-- change that depends on it are atomic across backend instances. A command +-- takes the lock after its attempt and practice row locks; the claim takes +-- it first and then skips job rows that another transaction locks, so a +-- claim never waits for a row lock while it holds the queue lock. + +-- name: LockAssessmentPracticeQueue :exec +SELECT pg_advisory_xact_lock(hashtextextended('lincodex.assessment.practice_queue', 0)); + +-- Counts the queued and running jobs; the caller holds the queue lock. +-- name: CountActiveAssessmentPracticeJobs :one +SELECT count(*)::integer AS active +FROM assessment_practice_jobs AS job +WHERE job.state IN ('queued', 'running'); + +-- Counts the unfinished debug runs of a practice; the caller holds the +-- practice row lock. +-- name: CountActiveAssessmentPracticeRuns :one +SELECT count(*)::integer AS active +FROM assessment_practice_jobs AS job +INNER JOIN assessment_practice_submissions AS submission ON job.submission_id = submission.id +WHERE + submission.practice_id = sqlc.arg(practice_id) + AND job.mode = 'public' + AND job.state IN ('queued', 'running'); + +-- Counts running jobs whose lease has not expired by now, the application +-- clock; the caller holds the queue lock. +-- name: CountLiveRunningAssessmentPracticeJobs :one +SELECT count(*)::integer AS running +FROM assessment_practice_jobs AS job +WHERE + job.state = 'running' + AND job.lease_expires_at > sqlc.arg(now)::timestamptz; + +-- Claims one job under the queue lock: first a running job whose lease +-- expired (its worker stopped without finishing it), then the next queued +-- job, final submissions before debug runs. A takeover keeps the generation, +-- so the runner returns the run it already has, and counts one attempt. +-- name: ClaimAssessmentPracticeJob :one +WITH candidate AS ( + SELECT + job.submission_id, + job.state = 'running' AS reclaimed + FROM assessment_practice_jobs AS job + WHERE + (job.state = 'queued' AND job.available_at <= sqlc.arg(now)::timestamptz) + OR (job.state = 'running' AND job.lease_expires_at <= sqlc.arg(now)::timestamptz) + ORDER BY + job.state = 'running' DESC, + job.mode = 'final' DESC, + job.available_at ASC, + job.created_at ASC, + job.submission_id ASC + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE assessment_practice_jobs AS job +SET + state = 'running', + lease_owner = sqlc.arg(lease_owner), + lease_expires_at = sqlc.arg(lease_expires_at), + started_at = sqlc.arg(now)::timestamptz, + attempts = job.attempts + CASE WHEN candidate.reclaimed THEN 1 ELSE 0 END, + last_error_class = CASE + WHEN candidate.reclaimed THEN 'lease_expired' ELSE job.last_error_class + END, + updated_at = greatest(job.updated_at, clock_timestamp()) +FROM candidate +WHERE job.submission_id = candidate.submission_id +RETURNING + job.submission_id, + job.mode, + job.generation, + job.attempts, + candidate.reclaimed; + +-- Reads what a claimed job runs: the submission and the task of its +-- practice. +-- name: GetAssessmentPracticeJobWork :one +SELECT + submission.id, + submission.practice_id, + submission.user_id, + submission.mode, + submission.language, + submission.source, + submission.custom_tests, + submission.created_at, + practice.task +FROM assessment_practice_submissions AS submission +INNER JOIN assessment_practices AS practice ON submission.practice_id = practice.id +WHERE submission.id = sqlc.arg(submission_id); + +-- Renews the lease of a running try. The owner and the start time identify +-- the try, so a worker whose job was taken over changes nothing. +-- name: ExtendAssessmentPracticeJobLease :execrows +UPDATE assessment_practice_jobs +SET + lease_expires_at = sqlc.arg(lease_expires_at), + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = sqlc.arg(submission_id) + AND state = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND started_at = sqlc.arg(started_at); + +-- Puts a running try back into the queue: after a busy runner, a failed +-- try, or at shutdown. counted adds the try to the attempts. +-- name: RequeueAssessmentPracticeJob :execrows +UPDATE assessment_practice_jobs +SET + state = 'queued', + available_at = sqlc.arg(available_at), + generation = sqlc.arg(generation), + attempts = attempts + sqlc.arg(counted)::integer, + last_error_class = coalesce(sqlc.narg(error_class), last_error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = sqlc.arg(submission_id) + AND state = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND started_at = sqlc.arg(started_at); + +-- Locks a running try for its completion and checks that it still belongs +-- to the worker. +-- name: LockClaimedAssessmentPracticeJob :one +SELECT job.mode +FROM assessment_practice_jobs AS job +WHERE + job.submission_id = sqlc.arg(submission_id) + AND job.state = 'running' + AND job.lease_owner = sqlc.arg(lease_owner) + AND job.started_at = sqlc.arg(started_at) +FOR UPDATE; + +-- Stores the result of a submission once; a second result changes nothing. +-- name: StoreAssessmentPracticeResult :execrows +UPDATE assessment_practice_submissions +SET + result = sqlc.arg(result), + result_at = greatest(created_at, clock_timestamp()) +WHERE + id = sqlc.arg(id) + AND result IS NULL; + +-- Ends a running try as finished or failed. A finished job keeps the run ID +-- of the runner run that produced its result. +-- name: FinishAssessmentPracticeJob :execrows +UPDATE assessment_practice_jobs +SET + state = sqlc.arg(state), + runner_run_id = sqlc.narg(runner_run_id), + finished_at = greatest(created_at, clock_timestamp()), + last_error_class = coalesce(sqlc.narg(error_class), last_error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = greatest(updated_at, clock_timestamp()) +WHERE + submission_id = sqlc.arg(submission_id) + AND state = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND started_at = sqlc.arg(started_at); + +-- Moves the practice of a final submission out of pending, but only while +-- that submission is the latest final one of the practice. +-- name: SettleAssessmentPracticeAfterJob :execrows +UPDATE assessment_practices AS practice +SET + status = sqlc.arg(status), + failure_reason = sqlc.narg(failure_reason), + updated_at = greatest(practice.updated_at, clock_timestamp()) +WHERE + practice.status = 'pending' + AND practice.id = ( + SELECT submission.practice_id + FROM assessment_practice_submissions AS submission + WHERE submission.id = sqlc.arg(submission_id) + ) + AND sqlc.arg(submission_id)::uuid = ( + SELECT latest.id + FROM assessment_practice_submissions AS latest + WHERE + latest.practice_id = practice.id + AND latest.mode = 'final' + ORDER BY latest.created_at DESC, latest.id DESC + LIMIT 1 + ); diff --git a/backend/db/queries/assessment_results.sql b/backend/db/queries/assessment_results.sql new file mode 100644 index 0000000..b28f5a9 --- /dev/null +++ b/backend/db/queries/assessment_results.sql @@ -0,0 +1,130 @@ +-- Stores the category decision and current grade captured at real-attempt +-- finalization. The base result document remains its original v1 shape. +-- name: InsertAssessmentAttemptResultV2 :exec +INSERT INTO assessment_attempt_results ( + attempt_id, user_id, result_snapshot, schema_version, category_decision, + current_confirmed_grade, kind, mode, outcome, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, + opening_manifest_sha256, training_binding_id, training_manifest_sha256, + bank_version, algorithm_version, rationale_rule, pass_mark_basis_points, + scored_items, raw_score, pass_points, decided_at +) VALUES ( + sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot), 2, + sqlc.arg(category_decision)::jsonb, sqlc.narg(current_confirmed_grade), + sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome), sqlc.arg(product_policy_version_id), + sqlc.arg(product_policy_version), sqlc.arg(grading_policy_version_id), sqlc.arg(opening_id), + sqlc.arg(opening_manifest_sha256), NULL, NULL, sqlc.arg(bank_version), + sqlc.arg(algorithm_version), sqlc.arg(rationale_rule), sqlc.arg(pass_mark_basis_points), + sqlc.arg(scored_items), sqlc.arg(raw_score), sqlc.arg(pass_points), sqlc.arg(decided_at) +); + +-- Returns both immutable result versions. NULL category fields identify a +-- legacy v1 record and must not be reconstructed from current state. +-- name: GetAssessmentAttemptResultHistoryEntry :one +SELECT schema_version, result_snapshot::text, + COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade +FROM assessment_attempt_results +WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id); + +-- The caller validates and signs an opaque owner-bound cursor. This query +-- applies the keyset to the same stable order and fetches one extra row. +-- name: ListCandidateAssessmentResults :many +SELECT attempt_id, user_id, schema_version, result_snapshot::text, + COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at +FROM assessment_attempt_results +WHERE user_id = sqlc.arg(user_id) + AND kind IN ('root', 'corrective') + AND (sqlc.narg(cursor_decided_at)::timestamptz IS NULL OR + (decided_at, attempt_id) < + (sqlc.narg(cursor_decided_at)::timestamptz, sqlc.narg(cursor_attempt_id)::uuid)) +ORDER BY decided_at DESC, attempt_id DESC +LIMIT sqlc.arg(limit_count)::integer + 1; + +-- Acquired after C3, candidate/specialization scope, and attempt row locks. +-- This independent lock serializes current category upgrades for one scope. +-- name: LockCandidateAssessmentCategory :exec +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.category:candidate:' || sqlc.arg(candidate_id)::text || ':' || sqlc.arg(specialization)::text, + 0 +)); + +-- name: GetCandidateAssessmentCategory :one +SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +FROM candidate_assessment_categories +WHERE candidate_id = sqlc.arg(candidate_id) AND specialization = sqlc.arg(specialization); + +-- name: ListCandidateAssessmentCategories :many +SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +FROM candidate_assessment_categories +WHERE candidate_id = sqlc.arg(candidate_id) +ORDER BY specialization; + +-- name: GetSyntheticCategoryReview :one +SELECT review.id, review.opening_id, review.category, review.source, + review.opening_manifest_sha256, review.product_policy_version_id, + review.product_policy_version, review.reviewed_by, review.reviewed_at +FROM assessment_synthetic_category_reviews AS review +JOIN assessment_category_openings AS opening ON opening.id = review.opening_id +WHERE review.opening_id = sqlc.arg(opening_id) + AND review.category = sqlc.arg(category) + AND review.source = 'synthetic_demo' + AND review.opening_manifest_sha256 = sqlc.arg(opening_manifest_sha256) + AND review.product_policy_version_id = sqlc.arg(product_policy_version_id) + AND review.product_policy_version = sqlc.arg(product_policy_version) + AND opening.policy_version_id = sqlc.arg(grading_policy_version_id); + +-- The application accepts only a validated immutable review snapshot. The +-- trigger independently checks the source opening, manifest and policy. A +-- concurrent or repeated attestation of the same exact source inserts nothing, +-- and the caller reads the stored one. +-- name: InsertSyntheticCategoryReview :execrows +INSERT INTO assessment_synthetic_category_reviews ( + id, opening_id, category, source, opening_manifest_sha256, + product_policy_version_id, product_policy_version, reviewed_by, reviewed_at +) VALUES ( + sqlc.arg(id), sqlc.arg(opening_id), sqlc.arg(category), sqlc.arg(source), + sqlc.arg(opening_manifest_sha256), sqlc.arg(product_policy_version_id), + sqlc.arg(product_policy_version), sqlc.arg(reviewed_by), sqlc.arg(reviewed_at) +) +ON CONFLICT ON CONSTRAINT assessment_synthetic_category_reviews_exact_source_key DO NOTHING; + +-- Only strict grade upgrades replace the current row. The trigger enforces +-- the same monotonic rule as a final guard against adapter mistakes. The +-- grading policy is read from the immutable opening, and the guard trigger +-- compares it with the policy captured in the assigned result. +-- name: SaveCandidateAssessmentCategory :execrows +INSERT INTO candidate_assessment_categories ( + candidate_id, specialization, grade, source_attempt_id, source_review_id, + product_policy_version_id, product_policy_version, grading_policy_version_id, + opening_id, opening_manifest_sha256, source, calibration_status, assigned_at +) VALUES ( + sqlc.arg(candidate_id), sqlc.arg(specialization), sqlc.arg(grade), sqlc.arg(source_attempt_id), + sqlc.arg(source_review_id), sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version), + ( + SELECT opening.policy_version_id + FROM assessment_category_openings AS opening + WHERE opening.id = sqlc.arg(opening_id) + ), + sqlc.arg(opening_id), sqlc.arg(opening_manifest_sha256), + sqlc.arg(source), sqlc.arg(calibration_status), sqlc.arg(assigned_at) +) +ON CONFLICT (candidate_id, specialization) DO UPDATE SET + grade = EXCLUDED.grade, + source_attempt_id = EXCLUDED.source_attempt_id, + source_review_id = EXCLUDED.source_review_id, + product_policy_version_id = EXCLUDED.product_policy_version_id, + product_policy_version = EXCLUDED.product_policy_version, + grading_policy_version_id = EXCLUDED.grading_policy_version_id, + opening_id = EXCLUDED.opening_id, + opening_manifest_sha256 = EXCLUDED.opening_manifest_sha256, + source = EXCLUDED.source, + calibration_status = EXCLUDED.calibration_status, + assigned_at = EXCLUDED.assigned_at +WHERE CASE candidate_assessment_categories.grade + WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END + < CASE EXCLUDED.grade + WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END; diff --git a/backend/db/queries/assessment_signal_notice.sql b/backend/db/queries/assessment_signal_notice.sql new file mode 100644 index 0000000..33bc856 --- /dev/null +++ b/backend/db/queries/assessment_signal_notice.sql @@ -0,0 +1,15 @@ +-- The caller has already checked that the user is a candidate. A missing row +-- means the notice version was not acknowledged. +-- name: GetAssessmentSignalNoticeAcknowledgement :one +SELECT acknowledged_at +FROM assessment_signal_notice_acknowledgements +WHERE + user_id = sqlc.arg(user_id) + AND notice_version = sqlc.arg(notice_version); + +-- The first acknowledgement wins; a repeat keeps the stored time and inserts +-- nothing. The caller reads the stored row afterwards in the same transaction. +-- name: InsertAssessmentSignalNoticeAcknowledgement :exec +INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) +VALUES (sqlc.arg(user_id), sqlc.arg(notice_version), sqlc.arg(acknowledged_at)) +ON CONFLICT (user_id, notice_version) DO NOTHING; diff --git a/backend/db/queries/assessment_signal_review.sql b/backend/db/queries/assessment_signal_review.sql new file mode 100644 index 0000000..f30da24 --- /dev/null +++ b/backend/db/queries/assessment_signal_review.sql @@ -0,0 +1,263 @@ +-- name: InsertAssessmentAnswerObservation :exec +INSERT INTO assessment_answer_observations ( + attempt_id, + item_instance_id, + user_id, + family_id, + variant_seed, + answer_format, + answer_fingerprint, + key_version, + elapsed_ms, + measured_from_answer, + observed_at +) VALUES ( + sqlc.arg(attempt_id), + sqlc.arg(item_instance_id), + sqlc.arg(user_id), + sqlc.arg(family_id), + sqlc.arg(variant_seed), + sqlc.arg(answer_format), + sqlc.arg(answer_fingerprint), + sqlc.arg(key_version), + sqlc.arg(elapsed_ms), + sqlc.arg(measured_from_answer), + sqlc.arg(observed_at) +); + +-- name: InsertAssessmentOriginMark :exec +INSERT INTO assessment_attempt_origin_marks ( + id, + attempt_id, + source, + observed_at, + session_digest, + network_digest, + agent_digest, + key_version +) VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(source), + sqlc.arg(observed_at), + sqlc.arg(session_digest), + sqlc.narg(network_digest), + sqlc.narg(agent_digest), + sqlc.arg(key_version) +); + +-- An attempt holds at most 220 items, so the list is bounded by the attempt. +-- name: ListAssessmentAnswerTimes :many +SELECT answer_format, elapsed_ms, measured_from_answer +FROM assessment_answer_observations +WHERE attempt_id = sqlc.arg(attempt_id) +ORDER BY observed_at, item_instance_id +LIMIT 220; + +-- Marks exist only where the session or the network changed. The bound keeps a +-- request that flaps between networks from growing the list without limit. +-- name: ListAssessmentOriginMarks :many +SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest +FROM assessment_attempt_origin_marks +WHERE attempt_id = sqlc.arg(attempt_id) +ORDER BY observed_at, id +LIMIT 5000; + +-- The caller holds the attempt row lock, so the last mark is stable. +-- name: GetLastAssessmentOriginMark :one +SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest +FROM assessment_attempt_origin_marks +WHERE attempt_id = sqlc.arg(attempt_id) +ORDER BY observed_at DESC, id DESC +LIMIT 1; + +-- Compares this attempt with every other attempt separately. A matched answer +-- is an equal fingerprint of the same family version under the same key +-- generation, given by another candidate to a different seed variant. It +-- carries -log2 of the share of answers that hold that fingerprint, read from +-- the maintained counters, between +-- zero and the cap of its format, and the bits of one pair add up. Pairs under +-- min_bits are dropped, the strongest come first, and the list is bounded. +-- An attempt has ended when its state is terminal or its deadline has passed. +-- name: ListAssessmentDuplicatePairs :many +WITH mine AS ( + SELECT + own.family_id, + own.key_version, + own.answer_fingerprint, + own.answer_format, + own.variant_seed, + own.user_id + FROM assessment_answer_observations AS own + WHERE own.attempt_id = sqlc.arg(attempt_id) +), + +pair_items AS ( + SELECT + other.attempt_id AS other_attempt_id, + mine.answer_format, + least( + CASE + WHEN mine.answer_format = 'integer' THEN sqlc.arg(integer_cap_bits)::float8 + ELSE sqlc.arg(sequence_cap_bits)::float8 + END, + greatest(0::float8, -ln(holders.holders::float8 / totals.answer_count::float8) / ln(2::float8)) + ) AS bits + FROM mine + INNER JOIN assessment_answer_observations AS other + ON mine.family_id = other.family_id + AND mine.key_version = other.key_version + AND mine.answer_fingerprint = other.answer_fingerprint + AND mine.user_id <> other.user_id + AND mine.variant_seed <> other.variant_seed + INNER JOIN assessment_answer_fingerprint_holders AS holders + ON mine.family_id = holders.family_id + AND mine.key_version = holders.key_version + AND mine.answer_fingerprint = holders.answer_fingerprint + INNER JOIN assessment_answer_family_totals AS totals + ON mine.family_id = totals.family_id + AND mine.key_version = totals.key_version +) + +SELECT + pair_items.other_attempt_id, + other_attempt.product_policy_version_id, + floor(sum(pair_items.bits))::integer AS evidence_bits, + (count(*) FILTER (WHERE pair_items.answer_format = 'integer'))::integer AS integer_items, + (count(*) FILTER (WHERE pair_items.answer_format = 'integer_sequence'))::integer AS sequence_items +FROM pair_items +INNER JOIN assessment_attempts AS other_attempt ON pair_items.other_attempt_id = other_attempt.id +WHERE + NOT sqlc.arg(ended_only)::boolean + OR other_attempt.state IN ('completed', 'expired', 'insufficient_bank') + OR other_attempt.expires_at <= sqlc.arg(now)::timestamptz +GROUP BY pair_items.other_attempt_id, other_attempt.product_policy_version_id +HAVING floor(sum(pair_items.bits)) >= sqlc.arg(min_bits)::float8 +ORDER BY evidence_bits DESC, pair_items.other_attempt_id +LIMIT sqlc.arg(row_limit); + +-- The attempt a review job works on: real attempts only. +-- name: GetAssessmentReviewSubject :one +SELECT product_policy_version_id +FROM assessment_attempts +WHERE id = sqlc.arg(attempt_id) AND kind IN ('root', 'corrective'); + +-- name: GetAssessmentClientSignalTotals :one +SELECT + COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms, + (count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events, + (count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits, + (count(*) FILTER (WHERE kind = 'screenshot_key'))::integer AS screenshot_keys, + (count(*) FILTER (WHERE kind = 'devtools_open'))::integer AS devtools_opens +FROM assessment_signal_events +WHERE attempt_id = sqlc.arg(attempt_id); + +-- The times come from the database clock, never from a caller, and the update +-- time cannot fall behind the stored times, so two jobs writing one review in +-- either order keep the order check. The first evaluation time and the policy +-- version stay; the guard trigger refuses a change of either. +-- name: UpsertAssessmentAttemptReview :exec +INSERT INTO assessment_attempt_reviews ( + attempt_id, + policy_version_id, + band, + reasons, + answered_items, + fast_answers, + deviating_answers, + parallel_alternations, + extra_networks, + matched_integer_items, + matched_sequence_items, + duplicate_evidence_bits, + client_focus_loss_ms, + client_clipboard_events, + client_fullscreen_exits, + extra_agents, + client_screenshot_keys, + client_devtools_opens, + evaluated_at, + updated_at +) VALUES ( + sqlc.arg(attempt_id), + sqlc.arg(policy_version_id), + sqlc.arg(band), + sqlc.arg(reasons)::text[], + sqlc.arg(answered_items), + sqlc.arg(fast_answers), + sqlc.arg(deviating_answers), + sqlc.arg(parallel_alternations), + sqlc.arg(extra_networks), + sqlc.arg(matched_integer_items), + sqlc.arg(matched_sequence_items), + sqlc.arg(duplicate_evidence_bits), + sqlc.arg(client_focus_loss_ms), + sqlc.arg(client_clipboard_events), + sqlc.arg(client_fullscreen_exits), + sqlc.arg(extra_agents), + sqlc.arg(client_screenshot_keys), + sqlc.arg(client_devtools_opens), + clock_timestamp(), + clock_timestamp() +) +ON CONFLICT (attempt_id) DO UPDATE SET + policy_version_id = EXCLUDED.policy_version_id, + band = EXCLUDED.band, + reasons = EXCLUDED.reasons, + answered_items = EXCLUDED.answered_items, + fast_answers = EXCLUDED.fast_answers, + deviating_answers = EXCLUDED.deviating_answers, + parallel_alternations = EXCLUDED.parallel_alternations, + extra_networks = EXCLUDED.extra_networks, + matched_integer_items = EXCLUDED.matched_integer_items, + matched_sequence_items = EXCLUDED.matched_sequence_items, + duplicate_evidence_bits = EXCLUDED.duplicate_evidence_bits, + client_focus_loss_ms = EXCLUDED.client_focus_loss_ms, + client_clipboard_events = EXCLUDED.client_clipboard_events, + client_fullscreen_exits = EXCLUDED.client_fullscreen_exits, + extra_agents = EXCLUDED.extra_agents, + client_screenshot_keys = EXCLUDED.client_screenshot_keys, + client_devtools_opens = EXCLUDED.client_devtools_opens, + updated_at = greatest( + clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at + ); + +-- Serializes the evaluations of one review. A job takes these locks for every +-- attempt it will write, in ascending attempt order, before it reads any fact, +-- so what it reads is what the previous writer committed. +-- name: LockAssessmentReview :exec +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.signal_review:' || sqlc.arg(attempt_id)::text, + 0 +)); + +-- name: GetAssessmentAttemptReview :one +SELECT + review.attempt_id, + review.policy_version_id, + policy.version AS policy_version, + review.band, + review.reasons, + review.answered_items, + review.fast_answers, + review.deviating_answers, + review.parallel_alternations, + review.extra_networks, + review.matched_integer_items, + review.matched_sequence_items, + review.duplicate_evidence_bits, + review.client_focus_loss_ms, + review.client_clipboard_events, + review.client_fullscreen_exits, + review.extra_agents, + review.client_screenshot_keys, + review.client_devtools_opens, + review.evaluated_at, + review.updated_at +FROM assessment_attempt_reviews AS review +JOIN policy_versions AS policy ON policy.id = review.policy_version_id +WHERE review.attempt_id = sqlc.arg(attempt_id); + +-- name: InsertAssessmentReviewRead :exec +INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at) +VALUES (sqlc.arg(id), sqlc.arg(attempt_id), sqlc.arg(actor), sqlc.arg(found), sqlc.arg(read_at)); diff --git a/backend/db/queries/assessment_signals.sql b/backend/db/queries/assessment_signals.sql new file mode 100644 index 0000000..60ab7ce --- /dev/null +++ b/backend/db/queries/assessment_signals.sql @@ -0,0 +1,78 @@ +-- New outcomes share the generic idempotency row and are counted for the +-- attempt's rolling receipt window. Replays bypass this query in the usecase. +-- name: CountRecentAssessmentSignalOutcomes :one +SELECT + count(*)::bigint AS outcome_count, + COALESCE(min(received_at), sqlc.arg(since)::timestamptz) AS oldest_at +FROM assessment_signal_idempotency_outcomes +WHERE + attempt_id = sqlc.arg(attempt_id) + AND received_at > sqlc.arg(since); + +-- The attempt row is already locked by the caller. Store a parent before its +-- bounded child events, in the same transaction as the immutable receipt. +-- name: InsertAssessmentSignalBatch :exec +INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count) +VALUES ( + sqlc.arg(id), + sqlc.arg(attempt_id), + sqlc.arg(received_at), + sqlc.arg(event_count) +); + +-- Each inserted event is checked by the database guard against attempt state +-- and the aggregate capacity as a second line of defense. +-- name: InsertAssessmentSignalEvent :exec +INSERT INTO assessment_signal_events ( + batch_id, + attempt_id, + ordinal, + item_instance_id, + kind, + occurred_at, + duration_ms, + size_bytes +) VALUES ( + sqlc.arg(batch_id), + sqlc.arg(attempt_id), + sqlc.arg(ordinal), + sqlc.arg(item_instance_id), + sqlc.arg(kind), + sqlc.arg(occurred_at), + sqlc.narg(duration_ms)::integer, + sqlc.narg(size_bytes)::integer +); + +-- Count events only for the already owner-locked attempt. +-- name: CountAssessmentSignalEvents :one +SELECT count(*)::bigint AS event_count +FROM assessment_signal_events +WHERE attempt_id = sqlc.arg(attempt_id); + +-- The generic reservation has already established that a previous outcome is +-- expired before this child is removed and replaced in the same transaction. +-- name: DeleteExpiredAssessmentSignalOutcome :exec +DELETE FROM assessment_signal_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- Save exactly one immutable response receipt for each live idempotency scope. +-- name: InsertAssessmentSignalOutcome :exec +INSERT INTO assessment_signal_idempotency_outcomes ( + scope_hash, + attempt_id, + status, + accepted_events, + received_at +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(attempt_id), + sqlc.arg(status), + sqlc.arg(accepted_events), + sqlc.arg(received_at) +); + +-- Read only the receipt associated with the reserved idempotency scope. +-- name: GetAssessmentSignalOutcome :one +SELECT status, accepted_events, received_at +FROM assessment_signal_idempotency_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/assessment_work_leases.sql b/backend/db/queries/assessment_work_leases.sql new file mode 100644 index 0000000..3bfd280 --- /dev/null +++ b/backend/db/queries/assessment_work_leases.sql @@ -0,0 +1,30 @@ +-- The hold of the single active work session of a real attempt. The caller +-- holds the row lock of the attempt, so one attempt's lease is changed by one +-- transaction at a time. +-- name: GetAssessmentWorkLease :one +SELECT attempt_id, holder_digest, key_version, acquired_at, renewed_at, released_at +FROM assessment_attempt_work_leases +WHERE attempt_id = sqlc.arg(attempt_id); + +-- name: UpsertAssessmentWorkLease :exec +INSERT INTO assessment_attempt_work_leases ( + attempt_id, + holder_digest, + key_version, + acquired_at, + renewed_at, + released_at +) VALUES ( + sqlc.arg(attempt_id), + sqlc.arg(holder_digest), + sqlc.arg(key_version), + sqlc.arg(acquired_at), + sqlc.arg(renewed_at), + sqlc.narg(released_at) +) +ON CONFLICT (attempt_id) DO UPDATE SET + holder_digest = EXCLUDED.holder_digest, + key_version = EXCLUDED.key_version, + acquired_at = EXCLUDED.acquired_at, + renewed_at = EXCLUDED.renewed_at, + released_at = EXCLUDED.released_at; diff --git a/backend/db/queries/candidate.sql b/backend/db/queries/candidate.sql new file mode 100644 index 0000000..992814b --- /dev/null +++ b/backend/db/queries/candidate.sql @@ -0,0 +1,177 @@ +-- Queries of the manual candidate profile. The profile is personal +-- data of the account that owns it: every statement is scoped by user_id, and +-- no statement selects another account's row. None of them names a file, the +-- ML service, or an FSP account, because the profile needs none. + +-- Stores the first save of a profile at version 1. No row returns when the +-- account already has a profile, so a first save that lost a race with +-- another first save from another tab can be told apart and answered as a +-- version conflict. +-- name: InsertCandidateProfile :one +INSERT INTO candidate_profiles ( + user_id, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(user_id), + 1, + sqlc.arg(at), + sqlc.arg(at) +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version, created_at, updated_at; + +-- Advances the version over the one the caller read, in the same statement. +-- The row lock it takes serializes concurrent saves of one profile. The update +-- time never moves back: an application clock behind the stored time (clock +-- skew between instances) keeps the stored time, which the CHECK +-- candidate_profiles_updated_after_creation also requires. No row +-- returns for a stale version or for an account without a profile, which the +-- caller answers as a version conflict. +-- name: AdvanceCandidateProfileVersion :one +UPDATE candidate_profiles +SET + version = candidate_profiles.version + 1, + updated_at = GREATEST(candidate_profiles.updated_at, sqlc.arg(at)) +WHERE + candidate_profiles.user_id = sqlc.arg(user_id) + AND candidate_profiles.version = sqlc.arg(expected_version) +RETURNING user_id, version, created_at, updated_at; + +-- Reads the profile row of an account together with every claim in one +-- statement, so the version and the claims come from one snapshot: a save that +-- commits between two separate reads could pair version N with the claims of +-- N+1. A profile without a claim returns one row with NULL claim columns, and +-- no row at all means the account has not saved a profile (contract version +-- 0). Claims come in a stable order: single fields by kind, list items by +-- position. Never replace this with two statements. +-- name: ReadCandidateProfile :many +SELECT + candidate_profiles.user_id, + candidate_profiles.version, + candidate_profiles.created_at, + candidate_profiles.updated_at, + candidate_profile_claims.kind, + candidate_profile_claims.ordinal, + candidate_profile_claims.value, + candidate_profile_claims.status, + candidate_profile_claims.origin, + candidate_profile_claims.trust_level, + candidate_profile_claims.quote, + candidate_profile_claims.extraction_version, + candidate_profile_claims.confirmed_at, + COALESCE( + ( + SELECT jsonb_agg( + jsonb_build_object( + 'first_index', confirmations.first_index, + 'second_index', confirmations.second_index, + 'first_period', jsonb_build_object( + 'started_on', confirmations.first_started_on, + 'ended_on', confirmations.first_ended_on + ), + 'second_period', jsonb_build_object( + 'started_on', confirmations.second_started_on, + 'ended_on', confirmations.second_ended_on + ) + ) ORDER BY confirmations.first_index, confirmations.second_index + )::text + FROM candidate_profile_overlap_confirmations AS confirmations + WHERE confirmations.user_id = candidate_profiles.user_id + ), + '[]'::text + )::text AS parallel_period_acknowledgements +FROM candidate_profiles +LEFT JOIN candidate_profile_claims + ON candidate_profile_claims.user_id = candidate_profiles.user_id +WHERE candidate_profiles.user_id = sqlc.arg(user_id) +ORDER BY candidate_profile_claims.kind, candidate_profile_claims.ordinal; + +-- Removes the claims that a save replaces. The adapter calls it after the +-- version advanced and before it inserts the new set, in one transaction. +-- name: DeleteCandidateProfileClaims :exec +DELETE FROM candidate_profile_claims +WHERE user_id = sqlc.arg(user_id); + +-- Stores one claim of the new set. Provenance fields are the domain's; the +-- statement never takes a trust level from the caller, because every claim +-- has level 0. +-- name: InsertCandidateProfileClaim :exec +INSERT INTO candidate_profile_claims ( + user_id, + kind, + ordinal, + value, + status, + origin, + trust_level, + quote, + extraction_version, + confirmed_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(ordinal), + sqlc.arg(value), + sqlc.arg(status), + sqlc.arg(origin), + 0, + sqlc.narg(quote), + sqlc.narg(extraction_version), + sqlc.narg(confirmed_at) +); + +-- Replaces the current explicit decisions with those in the new profile. +-- The versioned profile row is advanced first in this same transaction. +-- name: DeleteCandidateProfileOverlapConfirmations :exec +DELETE FROM candidate_profile_overlap_confirmations +WHERE user_id = sqlc.arg(user_id); + +-- name: InsertCandidateProfileOverlapConfirmation :exec +INSERT INTO candidate_profile_overlap_confirmations ( + user_id, + first_index, + second_index, + first_started_on, + first_ended_on, + second_started_on, + second_ended_on +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(first_index), + sqlc.arg(second_index), + sqlc.arg(first_started_on), + sqlc.narg(first_ended_on), + sqlc.arg(second_started_on), + sqlc.narg(second_ended_on) +); + +-- Every changed version appends exactly one private snapshot. The unique +-- key prevents a second snapshot for the same profile version. +-- name: AppendCandidateProfileHistory :exec +INSERT INTO candidate_profile_history ( + user_id, + version, + changed_at, + snapshot +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(version), + sqlc.arg(changed_at), + sqlc.arg(snapshot)::jsonb +); + +-- Saving a profile advances onboarding only from that exact step. A retry or +-- a save after a later step is already stored never regresses onboarding. +-- name: AdvanceCandidateOnboardingAfterProfile :exec +UPDATE users +SET + onboarding_step = 'candidate_questionnaire', + version = users.version + 1, + updated_at = GREATEST(users.updated_at, sqlc.arg(at)::timestamptz) +WHERE + users.id = sqlc.arg(user_id) + AND users.scenario = 'candidate' + AND users.email_verified_at IS NOT NULL + AND users.onboarding_step = 'candidate_profile'; diff --git a/backend/db/queries/candidate_search.sql b/backend/db/queries/candidate_search.sql new file mode 100644 index 0000000..50a33cb --- /dev/null +++ b/backend/db/queries/candidate_search.sql @@ -0,0 +1,18 @@ +-- Reads that only the match search needs. The visibility of the candidates and +-- their permitted evidence come from the card and evidence queries, which are +-- the single copy of those barriers; this file adds no candidate-facing read. + +-- The number of candidates who hold each given category from a source that is +-- not a synthetic demonstration, which is the size of the comparable real +-- cohort that a percentile needs. It returns counts only, for the pairs the +-- caller passes as "specialization/grade", and no row for a pair nobody holds. +-- name: CountRealComparableCategories :many +SELECT + category.specialization, + category.grade, + count(*)::bigint AS candidates +FROM candidate_assessment_categories AS category +WHERE + category.source <> 'synthetic_demo' + AND (category.specialization || '/' || category.grade) = any(sqlc.arg(categories)::text []) +GROUP BY category.specialization, category.grade; diff --git a/backend/db/queries/company_quota.sql b/backend/db/queries/company_quota.sql new file mode 100644 index 0000000..e2578e2 --- /dev/null +++ b/backend/db/queries/company_quota.sql @@ -0,0 +1,192 @@ +-- Writers lock the organization first, then, for an E0 organization, the holding +-- whose pool it shares, then invitation/card-view state, and finally usage rows. +-- The organization lock serializes quota decisions for the tenant, the holding +-- lock serializes the E0 pool across the organizations of one holding, and +-- together they make the subsequent count and insert atomic. + +-- Takes the organization lock ahead of every share lock of a reader that will +-- reserve usage later. FOR NO KEY UPDATE conflicts with itself and with FOR +-- SHARE, so readers of one organization queue up instead of deadlocking on a +-- share lock that each then tries to raise, but it does not conflict with the +-- FOR KEY SHARE that a foreign key takes, such as the hidden-organization +-- insert of a candidate, which holds the candidate's row and then needs this +-- one. The reservation itself still takes FOR UPDATE inside the same +-- transaction. The result carries the holding, whose pool an E0 organization +-- shares; the caller locks that holding right after this lock. +-- name: LockCompanyQuotaOrganizationFirst :one +SELECT + id, + verification_level, + holding_id +FROM organizations +WHERE id = sqlc.arg(organization_id) +FOR NO KEY UPDATE; + +-- name: LockCompanyQuotaOrganization :one +SELECT + id, + verification_level, + verification_basis, + verification_changed_at, + holding_id +FROM organizations +WHERE id = sqlc.arg(organization_id) +FOR UPDATE; + +-- Takes the pool lock of an E0 holding. It follows the organization lock, so +-- every writer locks an organization first and its holding second. Two +-- reservations of one holding queue here, and the second one counts the +-- usage that the first one committed. The lock does not conflict with the +-- FOR KEY SHARE that organizations.holding_id takes when an organization joins +-- the holding. +-- name: LockCompanyQuotaHolding :one +SELECT id +FROM holdings +WHERE id = sqlc.arg(holding_id) +FOR NO KEY UPDATE; + +-- name: FindCompanyInvitationQuotaUsage :one +SELECT invitation_id +FROM company_invitation_quota_usage +WHERE + organization_id = sqlc.arg(organization_id) + AND invitation_id = sqlc.arg(invitation_id) +FOR UPDATE; + +-- name: CountCompanyInvitationQuotaWindow :one +SELECT + count(*)::bigint AS usage_count, + min(reserved_at) AS earliest_at +FROM company_invitation_quota_usage +WHERE + organization_id = sqlc.arg(organization_id) + AND reserved_at > sqlc.arg(window_start); + +-- Counts the invitation usage of the E0 pool of a holding: the usage of every +-- organization of the holding whose trust level is E0 when the count runs. Each +-- row stays attributed to the organization that consumed it. +-- name: CountCompanyInvitationQuotaHoldingWindow :one +SELECT + count(*)::bigint AS usage_count, + min(usage.reserved_at) AS earliest_at +FROM company_invitation_quota_usage AS usage +INNER JOIN organizations AS organization ON organization.id = usage.organization_id +WHERE + organization.holding_id = sqlc.arg(holding_id) + AND organization.verification_level = 'e0' + AND usage.reserved_at > sqlc.arg(window_start); + +-- name: InsertCompanyInvitationQuotaUsage :exec +INSERT INTO company_invitation_quota_usage ( + organization_id, + invitation_id, + reserved_at, + policy_version_id, + verification_level, + verification_basis, + verification_changed_at, + quota_tier +) VALUES ( + sqlc.arg(organization_id), + sqlc.arg(invitation_id), + sqlc.arg(reserved_at), + sqlc.arg(policy_version_id), + sqlc.arg(verification_level), + sqlc.arg(verification_basis), + sqlc.arg(verification_changed_at), + sqlc.arg(quota_tier) +); + +-- name: FindCompanyCardViewQuotaUsage :one +SELECT last_seen_at +FROM company_card_view_quota_usage +WHERE + organization_id = sqlc.arg(organization_id) + AND candidate_id = sqlc.arg(candidate_id) +FOR UPDATE; + +-- name: RefreshCompanyCardViewQuotaUsage :execrows +UPDATE company_card_view_quota_usage +SET + last_seen_at = greatest(last_seen_at, sqlc.arg(last_seen_at)), + policy_version_id = sqlc.arg(policy_version_id), + verification_level = sqlc.arg(verification_level), + verification_basis = sqlc.arg(verification_basis), + verification_changed_at = sqlc.arg(verification_changed_at), + quota_tier = sqlc.arg(quota_tier) +WHERE + organization_id = sqlc.arg(organization_id) + AND candidate_id = sqlc.arg(candidate_id) + AND last_seen_at > sqlc.arg(window_start); + +-- name: CountCompanyCardViewQuotaWindow :one +SELECT + count(*)::bigint AS usage_count, + min(last_seen_at) AS earliest_at +FROM company_card_view_quota_usage +WHERE + organization_id = sqlc.arg(organization_id) + AND last_seen_at > sqlc.arg(window_start); + +-- Counts the distinct-card usage of the E0 pool of a holding, with the same +-- rule as CountCompanyInvitationQuotaHoldingWindow. A view is still counted +-- per organization: the same candidate seen by two organizations of one +-- holding is two charges. +-- name: CountCompanyCardViewQuotaHoldingWindow :one +SELECT + count(*)::bigint AS usage_count, + min(usage.last_seen_at) AS earliest_at +FROM company_card_view_quota_usage AS usage +INNER JOIN organizations AS organization ON organization.id = usage.organization_id +WHERE + organization.holding_id = sqlc.arg(holding_id) + AND organization.verification_level = 'e0' + AND usage.last_seen_at > sqlc.arg(window_start); + +-- name: SaveCompanyCardViewQuotaUsage :exec +INSERT INTO company_card_view_quota_usage ( + organization_id, + candidate_id, + last_seen_at, + policy_version_id, + verification_level, + verification_basis, + verification_changed_at, + quota_tier +) VALUES ( + sqlc.arg(organization_id), + sqlc.arg(candidate_id), + sqlc.arg(last_seen_at), + sqlc.arg(policy_version_id), + sqlc.arg(verification_level), + sqlc.arg(verification_basis), + sqlc.arg(verification_changed_at), + sqlc.arg(quota_tier) +) +ON CONFLICT (organization_id, candidate_id) +DO UPDATE SET + last_seen_at = greatest( + company_card_view_quota_usage.last_seen_at, + EXCLUDED.last_seen_at + ), + policy_version_id = EXCLUDED.policy_version_id, + verification_level = EXCLUDED.verification_level, + verification_basis = EXCLUDED.verification_basis, + verification_changed_at = EXCLUDED.verification_changed_at, + quota_tier = EXCLUDED.quota_tier; + +-- name: DeleteExpiredCompanyCardViewQuotaUsage :execrows +WITH expired AS ( + SELECT quota_usage.organization_id, quota_usage.candidate_id + FROM company_card_view_quota_usage AS quota_usage + WHERE + quota_usage.organization_id = sqlc.arg(organization_id) + AND quota_usage.last_seen_at <= sqlc.arg(window_start) + ORDER BY quota_usage.last_seen_at, quota_usage.candidate_id + LIMIT sqlc.arg(row_limit)::integer +) +DELETE FROM company_card_view_quota_usage AS usage +USING expired +WHERE + usage.organization_id = expired.organization_id + AND usage.candidate_id = expired.candidate_id; diff --git a/backend/db/queries/consents.sql b/backend/db/queries/consents.sql new file mode 100644 index 0000000..f1beee4 --- /dev/null +++ b/backend/db/queries/consents.sql @@ -0,0 +1,478 @@ +-- name: GetConsentText :one +SELECT + purpose, + version, + body, + body_sha256, + kind, + published_at +FROM consent_texts +WHERE + purpose = sqlc.arg(purpose) + AND version = sqlc.arg(version); + +-- The text of a purpose that applies at a time: the latest publication not +-- after it. +-- name: GetCurrentConsentText :one +SELECT + purpose, + version, + body, + body_sha256, + kind, + published_at +FROM consent_texts +WHERE + purpose = sqlc.arg(purpose) + AND published_at <= sqlc.arg(at) +ORDER BY published_at DESC +LIMIT 1; + +-- Records a grant of C1, C2, C3, or C5. An unrevoked record of the same +-- subject, purpose, and text version already exists when no row returns; +-- the insert then changes nothing and does not abort the transaction. +-- name: InsertConsentRecord :one +INSERT INTO consent_records ( + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + granted_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(subject_id), + sqlc.arg(purpose), + sqlc.arg(text_version), + sqlc.arg(text_hash), + sqlc.arg(source), + sqlc.narg(registration_version)::bigint, + sqlc.arg(granted_at) +) +ON CONFLICT (subject_id, purpose, text_version) +WHERE revoked_at IS NULL AND purpose <> 'c4' +DO NOTHING +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + ( + CASE + WHEN exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = consent_records.subject_id + AND newer.purpose = consent_records.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (consent_records.granted_at, consent_records.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state; + +-- Records a C4 grant with its scope. The invitation already has a C4 record +-- when no row returns; the insert then changes nothing and does not abort +-- the transaction. +-- name: InsertContactConsentRecord :one +INSERT INTO consent_records ( + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(subject_id), + 'c4', + sqlc.arg(text_version), + sqlc.arg(text_hash), + 'invitation_acceptance', + NULL, + sqlc.arg(organization_id), + sqlc.arg(organization_name), + sqlc.arg(field_set)::text [], + sqlc.arg(invitation_id), + sqlc.arg(invitation_terms_version), + sqlc.arg(granted_at) +) +ON CONFLICT (invitation_id) WHERE invitation_id IS NOT NULL +DO NOTHING +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state; + +-- name: GetUnrevokedConsentRecordByVersion :one +SELECT + record.id, + record.subject_id, + record.purpose, + record.text_version, + record.text_hash, + record.source, + record.registration_version, + record.organization_id, + record.organization_name, + record.field_set, + record.invitation_id, + record.invitation_terms_version, + record.granted_at, + record.revoked_at, + record.revocation_source, + ( + CASE + WHEN exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = record.subject_id + AND newer.purpose = record.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (record.granted_at, record.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state +FROM consent_records AS record +WHERE + record.subject_id = sqlc.arg(subject_id) + AND record.purpose = sqlc.arg(purpose) + AND record.text_version = sqlc.arg(text_version) + AND record.revoked_at IS NULL; + +-- name: GetContactConsentRecordByInvitation :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + ( + CASE WHEN revoked_at IS NULL THEN 'active' ELSE 'revoked' END + )::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND invitation_id = sqlc.arg(invitation_id); + +-- The newest unrevoked record of a purpose other than C4. +-- name: GetCurrentConsentRecord :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = sqlc.arg(purpose) + AND purpose <> 'c4' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1; + +-- Keeps the current C3 grant stable through a real assessment transaction. +-- Revocation updates this row and therefore waits until the caller commits. +-- name: LockCurrentConsentForUse :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c3' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1 +FOR SHARE; + +-- Locks the active registration C1 while its pending registration is applied. +-- name: LockRegistrationConsentRecord :one +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c1' + AND source = 'registration' + AND registration_version = sqlc.arg(registration_version) + AND revoked_at IS NULL +FOR UPDATE; + +-- name: ListCurrentContactConsentRecords :many +SELECT + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'active'::text AS state +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c4' + AND organization_id = sqlc.arg(organization_id) + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC; + +-- Revokes every unrevoked record of a purpose other than C4, superseded ones +-- included, and returns them. A revocation time before the grant time, from +-- clock skew between instances, is stamped at the grant time instead. +-- name: RevokeConsentRecords :many +UPDATE consent_records +SET + revoked_at = greatest(sqlc.arg(revoked_at)::timestamptz, granted_at), + revocation_source = sqlc.arg(revocation_source) +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = sqlc.arg(purpose) + AND purpose <> 'c4' + AND revoked_at IS NULL +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'revoked'::text AS state; + +-- Revokes every unrevoked C4 record of the subject for one organization and +-- returns them, with the same clamp of the revocation time as above. +-- name: RevokeContactConsentRecords :many +UPDATE consent_records +SET + revoked_at = greatest(sqlc.arg(revoked_at)::timestamptz, granted_at), + revocation_source = sqlc.arg(revocation_source) +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c4' + AND organization_id = sqlc.arg(organization_id) + AND revoked_at IS NULL +RETURNING + id, + subject_id, + purpose, + text_version, + text_hash, + source, + registration_version, + organization_id, + organization_name, + field_set, + invitation_id, + invitation_terms_version, + granted_at, + revoked_at, + revocation_source, + 'revoked'::text AS state; + +-- One page of the subject's ledger, newest grant first, optionally limited +-- to one state. Every record query is scoped by the subject, so a caller +-- never reads or revokes another subject's consent. The state is computed, +-- never stored: revoked once revoked_at is set; superseded when a newer +-- unrevoked record of the same subject and purpose exists (never for C4, +-- whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of +-- the last record of the previous page. +-- name: ListConsentRecords :many +WITH ledger AS ( + SELECT + record.id, + record.subject_id, + record.purpose, + record.text_version, + record.text_hash, + record.source, + record.registration_version, + record.organization_id, + record.organization_name, + record.field_set, + record.invitation_id, + record.invitation_terms_version, + record.granted_at, + record.revoked_at, + record.revocation_source, + ( + CASE + WHEN record.revoked_at IS NOT NULL THEN 'revoked' + WHEN record.purpose <> 'c4' AND exists( + SELECT 1 FROM consent_records AS newer + WHERE + newer.subject_id = record.subject_id + AND newer.purpose = record.purpose + AND newer.revoked_at IS NULL + AND (newer.granted_at, newer.id) + > (record.granted_at, record.id) + ) THEN 'superseded' + ELSE 'active' + END + )::text AS state + FROM consent_records AS record + WHERE record.subject_id = sqlc.arg(subject_id) +) + +SELECT + ledger.id, + ledger.subject_id, + ledger.purpose, + ledger.text_version, + ledger.text_hash, + ledger.source, + ledger.registration_version, + ledger.organization_id, + ledger.organization_name, + ledger.field_set, + ledger.invitation_id, + ledger.invitation_terms_version, + ledger.granted_at, + ledger.revoked_at, + ledger.revocation_source, + ledger.state +FROM ledger +WHERE + (sqlc.narg(state)::text IS NULL OR ledger.state = sqlc.narg(state)::text) + AND ( + sqlc.narg(after_granted_at)::timestamptz IS NULL + OR (ledger.granted_at, ledger.id) < ( + sqlc.narg(after_granted_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY ledger.granted_at DESC, ledger.id DESC +LIMIT sqlc.arg(row_limit); + +-- Creates one durable deletion request per subject until a worker completes it. +-- The caller appends the matching outbox intent in the same transaction only +-- when this insert returns a row. +-- name: CreateAccountDeletionRequest :one +INSERT INTO account_deletion_requests ( + id, + subject_id, + status, + requested_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(subject_id), + 'requested', + sqlc.arg(requested_at) +) +ON CONFLICT (subject_id) +WHERE subject_id IS NOT NULL AND status IN ('requested', 'processing') +DO NOTHING +RETURNING id, subject_id, status, requested_at; + +-- Reads the durable active deletion request when an earlier request already +-- exists. A completed request does not suppress a later explicit request. +-- name: GetActiveAccountDeletionRequest :one +SELECT id, subject_id, status, requested_at +FROM account_deletion_requests +WHERE subject_id = sqlc.arg(subject_id) + AND status IN ('requested', 'processing') +ORDER BY requested_at, id +LIMIT 1; diff --git a/backend/db/queries/contact_grants.sql b/backend/db/queries/contact_grants.sql new file mode 100644 index 0000000..70f77f1 --- /dev/null +++ b/backend/db/queries/contact_grants.sql @@ -0,0 +1,111 @@ +-- Store the contact grant of an acceptance. The row is inserted in the same +-- transaction as its C4 consent record and the accepted state; the database +-- checks that the record, the invitation, and the candidate agree. +-- name: InsertContactGrant :exec +INSERT INTO contact_grants ( + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(organization_id), + sqlc.arg(candidate_id), + sqlc.arg(source_invitation_id), + sqlc.arg(consent_record_id), + sqlc.arg(terms_version), + sqlc.arg(fields)::text [], + sqlc.arg(consent_text_version), + sqlc.arg(granted_at) +); + +-- Read the grant of one invitation of one organization. An invitation of +-- another organization finds nothing. +-- name: GetContactGrantByInvitation :one +SELECT + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at, + revoked_at, + revocation_reason +FROM contact_grants +WHERE + organization_id = sqlc.arg(organization_id) + AND source_invitation_id = sqlc.arg(invitation_id); + +-- Share-locks the consent C4 record of a grant for the duration of a contact +-- read. The read locks the record before the grant, the order that a C4 +-- revocation follows when it stamps the record and then closes its grants. No +-- row means the record is revoked or belongs to another scope, which closes +-- the read. +-- name: LockCurrentContactConsentRecord :one +SELECT consent_records.id +FROM consent_records +WHERE + consent_records.id = sqlc.arg(consent_record_id) + AND consent_records.subject_id = sqlc.arg(candidate_id) + AND consent_records.organization_id = sqlc.arg(organization_id) + AND consent_records.purpose = 'c4' + AND consent_records.revoked_at IS NULL +FOR SHARE; + +-- Share-locks one grant for the duration of a contact read and returns its +-- stored state. The caller decides whether the state still allows the read. +-- name: LockContactGrant :one +SELECT + id, + organization_id, + candidate_id, + source_invitation_id, + consent_record_id, + terms_version, + fields, + consent_text_version, + granted_at, + revoked_at, + revocation_reason +FROM contact_grants +WHERE id = sqlc.arg(id) +FOR SHARE; + +-- Closes the active grants of one candidate with one reason. A nil organization +-- closes every organization of the candidate, and a non-nil list of consent +-- records closes only the grants that those records gave. The grant rows are +-- locked in identifier order, so two closures that overlap take their locks in +-- the same order. The revocation time never precedes the grant time, which the +-- grant checks. A grant that is already closed keeps its first stamp. +-- name: CloseActiveContactGrants :execrows +WITH targets AS ( + SELECT contact_grants.id + FROM contact_grants + WHERE + contact_grants.candidate_id = sqlc.arg(candidate_id) + AND ( + sqlc.narg(organization_id)::uuid IS NULL + OR contact_grants.organization_id = sqlc.narg(organization_id)::uuid + ) + AND ( + sqlc.narg(consent_record_ids)::uuid [] IS NULL + OR contact_grants.consent_record_id = ANY(sqlc.narg(consent_record_ids)::uuid []) + ) + AND contact_grants.revoked_at IS NULL + ORDER BY contact_grants.id + FOR NO KEY UPDATE +) +UPDATE contact_grants +SET + revoked_at = greatest(contact_grants.granted_at, sqlc.arg(revoked_at)::timestamptz), + revocation_reason = sqlc.arg(revocation_reason) +FROM targets +WHERE contact_grants.id = targets.id; diff --git a/backend/db/queries/delivery.sql b/backend/db/queries/delivery.sql new file mode 100644 index 0000000..27d8073 --- /dev/null +++ b/backend/db/queries/delivery.sql @@ -0,0 +1,879 @@ +-- Stores a new delivery. A delivery with the same ID already exists when the +-- same request is handled again; the statement then inserts nothing and +-- returns 0 rows, and the stored content stays as it was. While another +-- transaction holds an uncommitted row with the same ID, the insert waits +-- for it. +-- name: InsertDelivery :execrows +INSERT INTO deliveries ( + id, + source_event_id, + recipient_user_id, + recipient_email, + kind, + template_version, + subject, + text_body, + html_body, + content_sha256, + provider, + provider_account, + idempotency_key, + status, + attempt_count, + next_attempt_at, + last_attempt_at, + provider_message_id, + email_token_id, + subject_kind, + subject_id, + subject_organization_id, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.narg(source_event_id), + sqlc.arg(recipient_user_id), + sqlc.arg(recipient_email), + sqlc.arg(kind), + sqlc.arg(template_version), + sqlc.arg(subject), + sqlc.arg(text_body), + sqlc.arg(html_body), + sqlc.arg(content_sha256), + sqlc.arg(provider), + sqlc.arg(provider_account), + sqlc.arg(idempotency_key), + sqlc.arg(status), + sqlc.arg(attempt_count), + sqlc.narg(next_attempt_at), + sqlc.narg(last_attempt_at), + sqlc.narg(provider_message_id), + sqlc.narg(email_token_id), + sqlc.narg(subject_kind), + sqlc.narg(subject_id), + sqlc.narg(subject_organization_id), + sqlc.arg(version), + sqlc.arg(created_at), + sqlc.arg(updated_at) +) +ON CONFLICT (id) DO NOTHING; + +-- name: GetDeliveryByID :one +SELECT + id, + source_event_id, + recipient_user_id, + recipient_email, + kind, + template_version, + subject, + text_body, + html_body, + content_sha256, + provider, + provider_account, + idempotency_key, + status, + attempt_count, + next_attempt_at, + last_attempt_at, + provider_message_id, + version, + created_at, + updated_at, + email_token_id, + cancel_reason, + claim_owner, + claimed_until, + first_send_started_at, + failure_count, + body_redacted_at, + subject_kind, + subject_id, + subject_organization_id +FROM deliveries +WHERE id = sqlc.arg(id); + +-- Reads only the metadata needed by the local operator retry interface. It +-- intentionally does not select the address, token, subject, or message body. +-- name: GetDeliveryRetrySnapshot :one +SELECT + id, + provider, + provider_account, + status, + attempt_count, + next_attempt_at, + first_send_started_at, + manual_retry_started_at +FROM deliveries +WHERE id = sqlc.arg(id); + +-- Advances a delivery past one attempt and appends the attempt in one +-- statement, so both happen or neither does, inside or outside a +-- transaction. The update applies only while the stored version still +-- equals expected_version; otherwise nothing is written and the statement +-- returns 0 rows. Two workers that record the same attempt number therefore +-- cannot both succeed. The lease of the sending worker ends with the +-- attempt, and so does the count of worker failures. When lease_owner is +-- given, the update applies only while that worker still holds the lease. +-- A token mail that reaches a terminal status loses its bodies in the same +-- statement, so the one-time token does not stay at rest; the trigger allows +-- exactly this change of the content columns. +-- name: RecordDeliveryAttempt :execrows +WITH advanced AS ( + UPDATE deliveries + SET + status = sqlc.arg(status), + attempt_count = sqlc.arg(attempt_number), + next_attempt_at = sqlc.narg(next_attempt_at), + last_attempt_at = sqlc.arg(attempted_at), + provider_message_id = coalesce( + sqlc.narg(provider_message_id), deliveries.provider_message_id + ), + claim_owner = NULL, + claimed_until = NULL, + failure_count = 0, + text_body = CASE + WHEN + sqlc.arg(status)::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + sqlc.arg(status)::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + sqlc.arg(status)::text IN ('accepted', 'rejected') + AND deliveries.kind IN ('verification', 'password_reset') + THEN sqlc.arg(updated_at) + ELSE deliveries.body_redacted_at + END, + version = deliveries.version + 1, + updated_at = sqlc.arg(updated_at) + WHERE + deliveries.id = sqlc.arg(delivery_id) + AND deliveries.version = sqlc.arg(expected_version) + AND ( + sqlc.narg(lease_owner)::uuid IS NULL + OR deliveries.claim_owner = sqlc.narg(lease_owner)::uuid + ) + RETURNING deliveries.id +) + +INSERT INTO delivery_attempts ( + delivery_id, + attempt_number, + attempted_at, + outcome, + rejection, + provider_code, + provider_message_id, + retry_after_ns, + status_after, + next_attempt_at +) +SELECT + advanced.id, + sqlc.arg(attempt_number), + sqlc.arg(attempted_at), + sqlc.arg(outcome), + sqlc.narg(rejection), + sqlc.narg(provider_code), + sqlc.narg(provider_message_id), + sqlc.arg(retry_after_ns), + sqlc.arg(status), + sqlc.narg(next_attempt_at) +FROM advanced; + +-- Stores a change of the delivery state that is not an attempt: a quota wait, +-- a cancellation, or a new provider account before the first attempt. It +-- applies only while the stored version still equals expected_version and +-- returns 0 rows otherwise. The trigger refuses a provider change after an +-- attempt. release_claim ends the lease of the sending worker with the +-- change; a new provider account keeps it, because the worker rebinds a +-- delivery it holds and then sends it. +-- name: UpdateDeliveryState :execrows +UPDATE deliveries +SET + status = sqlc.arg(status), + next_attempt_at = sqlc.narg(next_attempt_at), + cancel_reason = sqlc.narg(cancel_reason), + failure_count = 0, + provider = sqlc.arg(provider), + provider_account = sqlc.arg(provider_account), + claim_owner = CASE + WHEN sqlc.arg(release_claim)::boolean THEN NULL ELSE deliveries.claim_owner + END, + claimed_until = CASE + WHEN sqlc.arg(release_claim)::boolean THEN NULL ELSE deliveries.claimed_until + END, + text_body = CASE + WHEN + sqlc.arg(status)::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + sqlc.arg(status)::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + sqlc.arg(status)::text = 'cancelled' + AND deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN sqlc.arg(updated_at) + ELSE deliveries.body_redacted_at + END, + version = deliveries.version + 1, + updated_at = sqlc.arg(updated_at) +WHERE + deliveries.id = sqlc.arg(id) + AND deliveries.version = sqlc.arg(expected_version); + +-- Claims the most overdue delivery that the sending worker may send, in one +-- statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds +-- (the literals match the predicate of deliveries_due_idx, so an idle poll +-- reads only that small index) whose next_attempt_at has passed, pinned to the +-- configured provider account (or to rebind_provider before its first +-- attempt, which the worker moves to the configured account), and held by no +-- live lease. A row that another worker locks is skipped without waiting, so +-- several processes never take the same delivery, and a delivery whose lease +-- expired, because its worker stopped, is claimed again. +-- The lease is measured by the database clock, never by the clock of an +-- application instance: it lasts lease_seconds from clock_timestamp(), and a +-- lease is live while claimed_until is later than clock_timestamp(). Due times +-- stay on the application clock that wrote them. Neither the version nor +-- updated_at changes: a claim is not a change of the delivery. +-- previous_claimed_until is the deadline of an abandoned lease, NULL for a +-- delivery nobody held; since_first_send_seconds always measures from the +-- original first request by the database clock, and is -1 when none started. +-- manual_retry_pending is true until the first provider call of the latest +-- manual authorization starts. send_start_unsettled means a provider call +-- started at the current attempt_count but no result was recorded afterward. +-- has_uncertain_attempt keeps an earlier unknown result visible even if a +-- later confirmed refusal moved the current delivery back to pending. +-- now is the application clock. Unknown deliveries without a scheduled retry +-- and quota waits with an unknown reset wait for an operator. +-- name: ClaimDueDelivery :one +WITH candidate AS ( + SELECT + due.id, + due.claimed_until AS previous_claimed_until, + coalesce( + extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), + -1 + )::float8 AS since_first_send_seconds, + (due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL) + AS manual_retry_pending, + (due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started, + ( + due.send_started_attempt_count IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + )::boolean AS send_start_unsettled, + EXISTS ( + SELECT 1 + FROM delivery_attempts AS prior_attempt + WHERE prior_attempt.delivery_id = due.id + AND prior_attempt.outcome = 'unknown' + )::boolean AS has_uncertain_attempt + FROM deliveries AS due + WHERE + due.kind IN ('verification', 'password_reset') + AND due.kind = any(sqlc.arg(kinds)::text []) + AND due.status IN ('pending', 'waiting_quota', 'unknown') + AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= sqlc.arg(now)::timestamptz + AND ( + ( + due.provider = sqlc.arg(provider) + AND due.provider_account = sqlc.arg(provider_account) + ) + OR ( + due.provider = sqlc.arg(rebind_provider)::text + AND due.attempt_count = 0 + ) + ) + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + ORDER BY due.next_attempt_at, due.id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE deliveries AS claimed +SET + claim_owner = sqlc.arg(lease_owner)::uuid, + claimed_until = clock_timestamp() + + make_interval(secs => sqlc.arg(lease_seconds)::float8) +FROM candidate +WHERE claimed.id = candidate.id +RETURNING + claimed.id, + claimed.source_event_id, + claimed.recipient_user_id, + claimed.recipient_email, + claimed.kind, + claimed.template_version, + claimed.subject, + claimed.text_body, + claimed.html_body, + claimed.content_sha256, + claimed.provider, + claimed.provider_account, + claimed.idempotency_key, + claimed.status, + claimed.attempt_count, + claimed.next_attempt_at, + claimed.last_attempt_at, + claimed.provider_message_id, + claimed.email_token_id, + claimed.cancel_reason, + claimed.body_redacted_at, + claimed.failure_count, + claimed.version, + claimed.created_at, + claimed.updated_at, + claimed.subject_kind, + claimed.subject_id, + claimed.subject_organization_id, + candidate.previous_claimed_until, + candidate.since_first_send_seconds, + candidate.manual_retry_pending, + candidate.manual_retry_cycle_started, + candidate.send_start_unsettled, + candidate.has_uncertain_attempt; + +-- Claims the most overdue product notification, under the same rules as +-- ClaimDueDelivery: a lease in the database clock, the configured provider +-- account or a rebind of a delivery before its first attempt, and no live +-- lease. It reads deliveries_product_due_idx, whose predicate repeats the +-- literal kind below, so the backlog of service mail never enters the scan. +-- A notification is claimed here whatever its subject; the sending worker +-- checks the subject's rights after the claim and cancels a notice whose +-- basis no longer holds. +-- name: ClaimDueProductDelivery :one +WITH candidate AS ( + SELECT + due.id, + due.claimed_until AS previous_claimed_until, + coalesce( + extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), + -1 + )::float8 AS since_first_send_seconds, + (due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL) + AS manual_retry_pending, + (due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started, + ( + due.send_started_attempt_count IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + )::boolean AS send_start_unsettled, + EXISTS ( + SELECT 1 + FROM delivery_attempts AS prior_attempt + WHERE prior_attempt.delivery_id = due.id + AND prior_attempt.outcome = 'unknown' + )::boolean AS has_uncertain_attempt + FROM deliveries AS due + WHERE + due.kind = 'notification' + AND due.status IN ('pending', 'waiting_quota', 'unknown') + AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= sqlc.arg(now)::timestamptz + AND ( + ( + due.provider = sqlc.arg(provider) + AND due.provider_account = sqlc.arg(provider_account) + ) + OR ( + due.provider = sqlc.arg(rebind_provider)::text + AND due.attempt_count = 0 + ) + ) + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + ORDER BY due.next_attempt_at, due.id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) + +UPDATE deliveries AS claimed +SET + claim_owner = sqlc.arg(lease_owner)::uuid, + claimed_until = clock_timestamp() + + make_interval(secs => sqlc.arg(lease_seconds)::float8) +FROM candidate +WHERE claimed.id = candidate.id +RETURNING + claimed.id, + claimed.source_event_id, + claimed.recipient_user_id, + claimed.recipient_email, + claimed.kind, + claimed.template_version, + claimed.subject, + claimed.text_body, + claimed.html_body, + claimed.content_sha256, + claimed.provider, + claimed.provider_account, + claimed.idempotency_key, + claimed.status, + claimed.attempt_count, + claimed.next_attempt_at, + claimed.last_attempt_at, + claimed.provider_message_id, + claimed.email_token_id, + claimed.cancel_reason, + claimed.body_redacted_at, + claimed.failure_count, + claimed.version, + claimed.created_at, + claimed.updated_at, + claimed.subject_kind, + claimed.subject_id, + claimed.subject_organization_id, + candidate.previous_claimed_until, + candidate.since_first_send_seconds, + candidate.manual_retry_pending, + candidate.manual_retry_cycle_started, + candidate.send_start_unsettled, + candidate.has_uncertain_attempt; + +-- Authorizes one retry of a terminal unknown delivery. The update and append- +-- only decision share one statement and lock the current row, so a second or +-- concurrent operator decision cannot schedule another send for the same +-- unknown attempt. The provider account must still match the delivery's pin. +-- name: AuthorizeUnknownDeliveryRetry :execrows +WITH eligible AS MATERIALIZED ( + SELECT + due.id, + (due.claim_owner IS NOT NULL) AS previous_lease_expired, + ( + due.manual_retry_started_at IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + ) AS unsettled_manual_send, + greatest( + clock_timestamp(), + due.updated_at, + coalesce(due.last_attempt_at, due.updated_at) + ) AS lost_attempt_at + FROM deliveries AS due + WHERE + due.id = sqlc.arg(delivery_id) + AND due.status = 'unknown' + AND due.next_attempt_at IS NULL + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + AND due.attempt_count > 0 + AND due.provider = sqlc.arg(provider) + AND due.provider_account = sqlc.arg(provider_account) + AND due.first_send_started_at IS NOT NULL + AND clock_timestamp() - due.first_send_started_at + >= make_interval(secs => sqlc.arg(minimum_age_seconds)::float8) + AND sqlc.arg(duplicate_risk_acknowledged)::boolean + AND sqlc.arg(actor)::text ~ '^operator:[a-z0-9][a-z0-9._-]*$' + FOR UPDATE +), authorized AS ( + UPDATE deliveries AS due + SET + attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END, + last_attempt_at = CASE + WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at + ELSE due.last_attempt_at + END, + next_attempt_at = greatest( + sqlc.arg(now)::timestamptz, + due.updated_at, + coalesce(eligible.lost_attempt_at, due.updated_at) + ), + manual_retry_authorized_at = clock_timestamp(), + manual_retry_started_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + version = due.version + 1, + updated_at = greatest( + due.updated_at, + sqlc.arg(now)::timestamptz, + coalesce(eligible.lost_attempt_at, due.updated_at) + ) + FROM eligible + WHERE due.id = eligible.id + RETURNING + due.id, + due.attempt_count, + eligible.previous_lease_expired, + eligible.unsettled_manual_send, + eligible.lost_attempt_at +), recorded_lost_attempt AS ( + -- A manual send whose lease expired after Mark but before settlement has + -- no provider answer. Preserve it as an unknown attempt before this new + -- explicit decision schedules another possible send. + INSERT INTO delivery_attempts ( + delivery_id, + attempt_number, + attempted_at, + outcome, + rejection, + provider_code, + provider_message_id, + retry_after_ns, + status_after, + next_attempt_at + ) + SELECT + authorized.id, + authorized.attempt_count, + authorized.lost_attempt_at, + 'unknown', + NULL, + NULL, + NULL, + 0, + 'unknown', + NULL + FROM authorized + WHERE authorized.unsettled_manual_send + RETURNING delivery_id +) +INSERT INTO delivery_retry_decisions ( + delivery_id, + attempt_count, + actor, + duplicate_risk_acknowledged, + previous_lease_expired, + decided_at +) +SELECT + authorized.id, + authorized.attempt_count, + sqlc.arg(actor), + sqlc.arg(duplicate_risk_acknowledged), + authorized.previous_lease_expired, + clock_timestamp() +FROM authorized; + +-- Stops a due automatic retry of an unknown delivery without recording a +-- fictitious provider attempt, for example when the 23-hour safety cutoff is +-- reached after the claim but before the provider call. +-- name: StopUnknownDeliveryRetry :execrows +UPDATE deliveries +SET + status = 'unknown', + next_attempt_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) +WHERE + id = sqlc.arg(id) + AND status IN ('pending', 'waiting_quota', 'unknown') + AND next_attempt_at IS NOT NULL + AND claim_owner = sqlc.arg(lease_owner)::uuid; + +-- Ends a claimed delivery whose stored content no longer matches its hash, so +-- one broken row never blocks the delivery queue. It matches only a delivery +-- that the worker could still send, ends the lease, advances the version, and +-- redacts the bodies of a token mail like any other cancellation. now is the +-- application clock. +-- name: CancelUnreadableDelivery :execrows +UPDATE deliveries +SET + status = 'cancelled', + cancel_reason = 'content_invalid', + next_attempt_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + text_body = CASE + WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.text_body + END, + html_body = CASE + WHEN deliveries.kind IN ('verification', 'password_reset', 'notification') THEN '' ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) + ELSE deliveries.body_redacted_at + END, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) +WHERE + id = sqlc.arg(id) + AND status IN ('pending', 'waiting_quota'); + +-- Records that the sending worker failed on a delivery, so a broken row does +-- not stay at the head of the queue: the delivery is due again at +-- next_attempt_at and its lease ends. With count_failure the failure is +-- counted; after max_failures consecutive failures the delivery is cancelled +-- with the reason processing_failed, which an operator sees, and a token mail +-- loses its bodies. Without it nothing is counted and nothing is cancelled: +-- the failure says nothing about the row (a transient storage error, or a +-- stretch of failures across many rows). The row is touched only when no other +-- worker holds a live lease on it: lease_owner may hold it, or the lease is +-- free or expired. It returns the status after the change; no row means that +-- the delivery is no longer pending or waiting, or another worker holds it. +-- now is the application clock. +-- name: RecordDeliveryFailure :one +UPDATE deliveries +SET + failure_count = CASE + WHEN sqlc.arg(count_failure)::boolean THEN deliveries.failure_count + 1 ELSE deliveries.failure_count + END, + status = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + THEN 'cancelled' + ELSE deliveries.status + END, + cancel_reason = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + THEN 'processing_failed' + ELSE deliveries.cancel_reason + END, + next_attempt_at = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + THEN NULL + ELSE sqlc.arg(next_attempt_at)::timestamptz + END, + text_body = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + AND deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN '' + ELSE deliveries.text_body + END, + html_body = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + AND deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN '' + ELSE deliveries.html_body + END, + body_redacted_at = CASE + WHEN + sqlc.arg(count_failure)::boolean + AND deliveries.failure_count + 1 >= sqlc.arg(max_failures)::integer + AND deliveries.kind IN ('verification', 'password_reset', 'notification') + THEN greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) + ELSE deliveries.body_redacted_at + END, + claim_owner = NULL, + claimed_until = NULL, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) +WHERE + id = sqlc.arg(id) + AND status IN ('pending', 'waiting_quota') + AND ( + claim_owner IS NULL + OR claim_owner = sqlc.arg(lease_owner)::uuid + OR claimed_until <= clock_timestamp() + ) +RETURNING status; + +-- Locks the delivery row of the lease holder until the transaction ends, so +-- every path that settles a send takes the delivery lock before the quota +-- rows, the same order as the claim. No row means that owner no longer holds +-- the lease. +-- name: LockClaimedDelivery :one +SELECT id +FROM deliveries +WHERE + id = sqlc.arg(id) + AND claim_owner = sqlc.arg(lease_owner) +FOR UPDATE; + +-- Notes that a request is about to start, by the database clock, and clears +-- the count of worker failures. For an operator-authorized send, this sets +-- its single-use marker without overwriting the original first-send time. The +-- marker captures the current attempt_count so a lost result can be recovered +-- as unknown instead of silently retried. When require_dedup_window is true, +-- the age check is repeated here after quota work and the row lock, immediately +-- before the network call; manual starts never reset that original window. +-- name: MarkDeliverySendStarted :execrows +UPDATE deliveries +SET + first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()), + send_started_attempt_count = deliveries.attempt_count, + next_attempt_at = CASE + WHEN deliveries.manual_retry_authorized_at IS NOT NULL + AND deliveries.manual_retry_started_at IS NULL + THEN NULL + ELSE deliveries.next_attempt_at + END, + manual_retry_started_at = CASE + WHEN deliveries.manual_retry_authorized_at IS NOT NULL + AND deliveries.manual_retry_started_at IS NULL + THEN clock_timestamp() + ELSE deliveries.manual_retry_started_at + END, + failure_count = 0 +WHERE + id = sqlc.arg(id) + AND claim_owner = sqlc.arg(lease_owner) + AND ( + NOT sqlc.arg(require_dedup_window)::boolean + OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL) + OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL + OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) + < make_interval(secs => sqlc.arg(retry_window_seconds)::float8) + ); + +-- Gives a claimed delivery back without changing it, so the next pass may +-- claim it. It matches only the lease of lease_owner: a delivery that another +-- worker took over after the lease expired is left alone. +-- name: ReleaseDeliveryClaim :execrows +UPDATE deliveries +SET + claim_owner = NULL, + claimed_until = NULL +WHERE + id = sqlc.arg(id) + AND claim_owner = sqlc.arg(lease_owner); + +-- Reads the token a delivery is bound to and the account it is addressed to +-- in one statement, for the check right before a service mail is sent. It +-- takes no lock. It reads the account address only as the comparison key and +-- selects no token hash. A missing binding or token row gives NULL token +-- columns. +-- name: GetServiceMailState :one +SELECT + (token.id IS NOT NULL)::boolean AS token_found, + token.purpose AS token_purpose, + token.user_id AS token_user_id, + token.registration_version AS token_registration_version, + token.consumed_at AS token_consumed_at, + token.invalidated_at AS token_invalidated_at, + token.expires_at AS token_expires_at, + owner.registration_version AS account_registration_version, + (owner.email_verified_at IS NOT NULL)::boolean AS account_email_verified, + owner.email_normalized AS account_email_key +FROM deliveries AS delivery +INNER JOIN users AS owner ON delivery.recipient_user_id = owner.id +LEFT JOIN email_tokens AS token ON delivery.email_token_id = token.id +WHERE delivery.id = sqlc.arg(id); + +-- name: ListDeliveryAttempts :many +SELECT + delivery_id, + attempt_number, + attempted_at, + outcome, + rejection, + provider_code, + provider_message_id, + retry_after_ns, + status_after, + next_attempt_at +FROM delivery_attempts +WHERE delivery_id = sqlc.arg(delivery_id) +ORDER BY attempt_number; + +-- name: InsertMailRequest :exec +INSERT INTO mail_requests ( + id, + recipient_user_id, + kind, + subject, + body, + link_path, + subject_kind, + subject_id, + subject_organization_id, + created_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(recipient_user_id), + sqlc.arg(kind), + sqlc.arg(subject), + sqlc.arg(body), + sqlc.arg(link_path), + sqlc.narg(subject_kind), + sqlc.narg(subject_id), + sqlc.narg(subject_organization_id), + sqlc.arg(created_at) +); + +-- Locks a request for the consumer transaction that turns it into a +-- delivery. A concurrent consumer of the same request waits here and then +-- finds the row deleted. The account cleanup and the cascade from users take +-- the same row lock, so a request is never converted for an account whose +-- deletion is in progress without one of the two transactions waiting. +-- name: LockMailRequest :one +SELECT + id, + recipient_user_id, + kind, + subject, + body, + link_path, + subject_kind, + subject_id, + subject_organization_id, + created_at +FROM mail_requests +WHERE id = sqlc.arg(id) +FOR UPDATE; + +-- name: DeleteMailRequest :execrows +DELETE FROM mail_requests +WHERE id = sqlc.arg(id); + +-- Reads the status of the newest delivery of a kind addressed to an account, +-- for the account's own view of its mail. It selects no address and no +-- content. The recipient index narrows the scan to the account's rows. +-- name: GetLatestDeliveryStatus :one +SELECT + id, + kind, + status, + next_attempt_at, + created_at, + updated_at +FROM deliveries +WHERE + recipient_user_id = sqlc.arg(recipient_user_id) + AND kind = sqlc.arg(kind) +ORDER BY created_at DESC, id DESC +LIMIT 1; + +-- Aggregates the deliveries by kind and status for the metrics, at most once +-- per metrics interval. It reads only kind, status, and next_attempt_at, +-- never an address, a body, or an ID. No index covers status, so it scans +-- the table; add an index on (status) or keep per-status counters before +-- the table holds millions of rows. +-- name: GetDeliveryStatistics :many +SELECT + kind, + status, + count(*) AS deliveries, + min(next_attempt_at) FILTER ( + WHERE status = 'pending' + )::timestamptz AS earliest_pending_attempt_at +FROM deliveries +GROUP BY kind, status; diff --git a/backend/db/queries/event_consumer.sql b/backend/db/queries/event_consumer.sql new file mode 100644 index 0000000..5582841 --- /dev/null +++ b/backend/db/queries/event_consumer.sql @@ -0,0 +1,63 @@ +-- Records that a consumer applies an event, in the transaction of the effect. +-- It returns 0 rows when the marker exists. While another transaction holds +-- an uncommitted marker for the same key, the insert waits for it: after a +-- commit it returns 0, after a rollback it inserts. So a concurrent duplicate +-- never runs the effect at the same time as the first delivery. +-- name: InsertProcessedEventMarker :execrows +INSERT INTO consumer_processed_events (consumer_name, event_id) +VALUES (sqlc.arg(consumer_name), sqlc.arg(event_id)) +ON CONFLICT (consumer_name, event_id) DO NOTHING; + +-- Stores a record that a consumer could not apply. A second delivery of the +-- same record (same position and value) refreshes the outcome of its row: +-- after a rewind the handler may fail differently. A different value at a +-- reused position, after the topic was recreated, gets its own row. +-- name: InsertConsumerDeadLetter :exec +INSERT INTO consumer_dead_letters ( + consumer_name, + topic, + kafka_partition, + kafka_offset, + event_id, + event_type, + error_class, + reason, + attempts, + value_size, + value_sha256 +) VALUES ( + sqlc.arg(consumer_name), + sqlc.arg(topic), + sqlc.arg(kafka_partition), + sqlc.arg(kafka_offset), + sqlc.narg(event_id), + sqlc.narg(event_type), + sqlc.arg(error_class), + sqlc.arg(reason), + sqlc.arg(attempts), + sqlc.arg(value_size), + sqlc.arg(value_sha256) +) +ON CONFLICT ( + consumer_name, topic, kafka_partition, kafka_offset, value_sha256 +) DO UPDATE SET + event_id = excluded.event_id, + event_type = excluded.event_type, + error_class = excluded.error_class, + reason = excluded.reason, + attempts = excluded.attempts, + dead_lettered_at = clock_timestamp(); + +-- Bounds a consumer transaction on the server, local to the transaction. +-- statement_timeout stops a slow statement; idle_in_transaction_session_timeout +-- ends the session of a process that froze or lost the network inside the +-- handler, which releases the processed-event marker that a concurrent +-- duplicate waits for. +-- name: SetConsumerTransactionTimeouts :exec +SELECT + set_config('statement_timeout', sqlc.arg(statement_timeout_ms)::text, true), + set_config( + 'idle_in_transaction_session_timeout', + sqlc.arg(idle_timeout_ms)::text, + true + ); diff --git a/backend/db/queries/evidence.sql b/backend/db/queries/evidence.sql new file mode 100644 index 0000000..f12a3a4 --- /dev/null +++ b/backend/db/queries/evidence.sql @@ -0,0 +1,150 @@ +-- Skill evidence reads. The projection tables hold no answer, score, item, +-- failure, or anti-cheat data, and none of these statements names the result, +-- attempt, or review tables: evidence is read from its own facts only. + +-- The candidate's own facts, hidden ones included, newest event first. Every +-- statement is scoped by the owner; the caller passes the continuation +-- position of the previous page, if any, and fetches one extra row. +-- name: ListCandidateEvidenceFacts :many +SELECT + fact.id, + fact.kind, + fact.source_type, + fact.event_id, + fact.result_id, + fact.attribution, + fact.trust, + fact.grade, + fact.basis, + fact.calibration_status, + fact.occurred_at, + fact.visibility, + COALESCE( + ( + SELECT array_agg(skill.skill_code ORDER BY skill.skill_code) + FROM skill_evidence_skills AS skill + WHERE skill.fact_id = fact.id + ), + '{}'::text [] + )::text [] AS skills +FROM skill_evidence_facts AS fact +WHERE + fact.candidate_id = sqlc.arg(candidate_id) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (fact.occurred_at, fact.id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY fact.occurred_at DESC, fact.id DESC +LIMIT sqlc.arg(row_limit); + +-- The evidence that one organization may read about one candidate: one fact +-- for each category of the card, the fact that supports the confirmed grade +-- of that category (the earliest one that passed exactly that grade, so a +-- lower grade or a retake adds nothing). The statement selects from the +-- effective publication view (published and backed by an unrevoked C2) and +-- excludes the candidates that hide the reading organization, so no row means +-- nothing to read, whatever the reason. The card must publish the categories +-- field and only visible measurements qualify. The categories come from the +-- caller as "specialization/grade" pairs taken from the card that was just +-- projected, so the answer never names a skill the card does not show. The columns are +-- an allowlist: no identifier of the fact, the event, the result, or the +-- candidate leaves, the instant is cut to the year, and the basis and the +-- calibration (the same for every candidate) say that the fact is a synthetic +-- demonstration. +-- name: ListOrganizationVisibleEvidence :many +SELECT DISTINCT ON (skill.skill_code) + skill.skill_code AS skill, + fact.grade, + fact.trust, + fact.basis, + fact.calibration_status, + extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year +FROM candidate_effective_publications AS effective +INNER JOIN skill_evidence_facts AS fact + ON effective.user_id = fact.candidate_id +INNER JOIN skill_evidence_skills AS skill + ON fact.id = skill.fact_id +WHERE + effective.user_id = sqlc.arg(candidate_id) + AND 'categories' = any(effective.fields) + AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text []) + AND fact.kind = 'measurement' + AND fact.visibility = 'visible' + AND NOT EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = effective.user_id + AND hidden.organization_id = sqlc.arg(organization_id) + ) +ORDER BY skill.skill_code, fact.occurred_at, fact.id; + +-- The same selection for the candidate's own card preview, so the candidate +-- sees what an organization would read. It is scoped by the owner and runs +-- after the caller locked the effective C2 and publication; it does not apply +-- an organization or a cohort. +-- name: ListCandidatePreviewEvidence :many +SELECT DISTINCT ON (skill.skill_code) + skill.skill_code AS skill, + fact.grade, + fact.trust, + fact.basis, + fact.calibration_status, + extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year +FROM skill_evidence_facts AS fact +INNER JOIN skill_evidence_skills AS skill + ON fact.id = skill.fact_id +WHERE + fact.candidate_id = sqlc.arg(candidate_id) + AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text []) + AND fact.kind = 'measurement' + AND fact.visibility = 'visible' +ORDER BY skill.skill_code, fact.occurred_at, fact.id; + +-- The same organization read for a whole candidate set, so a search reads the +-- evidence of every listed candidate in one statement. The pairs come from the +-- caller as two parallel arrays, one row per candidate and category of the card +-- that was just projected. The statement repeats every barrier of the single +-- read: the effective publication view, NOT EXISTS over the candidates that +-- hide the organization, the categories field, and only visible measurements. +-- The candidate identifier is returned for the caller to group by and never +-- leaves the server; the other columns are the same allowlist. +-- name: ListOrganizationVisibleEvidenceBatch :many +SELECT DISTINCT ON (wanted.candidate_id, skill.skill_code) + wanted.candidate_id::uuid AS candidate_id, + skill.skill_code AS skill, + fact.grade, + fact.trust, + fact.basis, + fact.calibration_status, + extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year +FROM ( + SELECT + candidate_ids.candidate_id, + wanted_categories.category + FROM unnest(sqlc.arg(candidate_ids)::uuid []) WITH ORDINALITY AS candidate_ids (candidate_id, position) + INNER JOIN unnest(sqlc.arg(categories)::text []) WITH ORDINALITY AS wanted_categories (category, position) + ON candidate_ids.position = wanted_categories.position +) AS wanted +INNER JOIN candidate_effective_publications AS effective + ON wanted.candidate_id = effective.user_id +INNER JOIN skill_evidence_facts AS fact + ON effective.user_id = fact.candidate_id +INNER JOIN skill_evidence_skills AS skill + ON fact.id = skill.fact_id +WHERE + 'categories' = any(effective.fields) + AND (skill.skill_code || '/' || fact.grade) = wanted.category + AND fact.kind = 'measurement' + AND fact.visibility = 'visible' + AND NOT EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = effective.user_id + AND hidden.organization_id = sqlc.arg(organization_id) + ) +ORDER BY wanted.candidate_id, skill.skill_code, fact.occurred_at, fact.id; diff --git a/backend/db/queries/holdings.sql b/backend/db/queries/holdings.sql new file mode 100644 index 0000000..ad0e9aa --- /dev/null +++ b/backend/db/queries/holdings.sql @@ -0,0 +1,20 @@ +-- Stores the holding of a founder account unless the account already has one. +-- A concurrent creation of the same account waits on the founder key until the +-- other transaction ends; then this insert does nothing, and the caller reads +-- the stored holding with GetHoldingIDByFounder. +-- name: InsertHoldingIfAbsent :exec +INSERT INTO holdings ( + id, + founder_account_id, + created_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(founder_account_id), + sqlc.arg(created_at) +) +ON CONFLICT (founder_account_id) DO NOTHING; + +-- name: GetHoldingIDByFounder :one +SELECT id +FROM holdings +WHERE founder_account_id = sqlc.arg(founder_account_id); diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql new file mode 100644 index 0000000..5ad2b29 --- /dev/null +++ b/backend/db/queries/identity.sql @@ -0,0 +1,718 @@ +-- name: InsertUser :exec +INSERT INTO users ( + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(email), + sqlc.arg(email_normalized), + sqlc.arg(password_hash), + sqlc.arg(scenario), + sqlc.arg(onboarding_step), + sqlc.narg(email_verified_at), + sqlc.arg(registration_version), + sqlc.arg(last_registered_at), + sqlc.arg(version), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- name: GetUserByID :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE id = sqlc.arg(id); + +-- name: GetUserByEmailNormalized :one +SELECT + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at +FROM users +WHERE email_normalized = sqlc.arg(email_normalized); + +-- Replaces the registration of an unverified account and advances the +-- registration version in the same statement, so no caller can choose it. +-- The version check rejects a writer that read an older row; a verified +-- account never changes. The same statement deletes the C1 that the earlier +-- registration of this account recorded, so the consent of an earlier +-- registrant never stands for the new one; the new registration records its +-- own C1 in the same transaction. A version conflict deletes nothing. +-- name: UpdateUserRegistration :one +WITH updated AS ( + UPDATE users + SET + email = sqlc.arg(email), + password_hash = sqlc.arg(password_hash), + scenario = sqlc.arg(scenario), + onboarding_step = sqlc.arg(onboarding_step), + registration_version = registration_version + 1, + last_registered_at = sqlc.arg(last_registered_at), + updated_at = sqlc.arg(updated_at), + version = version + 1 + WHERE + users.id = sqlc.arg(id) + AND users.version = sqlc.arg(expected_version) + AND users.email_verified_at IS NULL + RETURNING + users.id, + users.email, + users.email_normalized, + users.password_hash, + users.scenario, + users.onboarding_step, + users.email_verified_at, + users.registration_version, + users.last_registered_at, + users.version, + users.created_at, + users.updated_at +), + +discarded_consent AS ( + DELETE FROM consent_records + USING updated + WHERE + consent_records.subject_id = updated.id + AND consent_records.purpose = 'c1' + AND consent_records.source = 'registration' +) + +SELECT + updated.id, + updated.email, + updated.email_normalized, + updated.password_hash, + updated.scenario, + updated.onboarding_step, + updated.email_verified_at, + updated.registration_version, + updated.last_registered_at, + updated.version, + updated.created_at, + updated.updated_at +FROM updated; + +-- Verifies the email only for the registration version the consumed token +-- was issued for. +-- name: MarkUserEmailVerified :one +UPDATE users +SET + email_verified_at = sqlc.arg(verified_at), + updated_at = sqlc.arg(verified_at), + version = version + 1 +WHERE + id = sqlc.arg(id) + AND registration_version = sqlc.arg(registration_version) + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at; + +-- Applies the registration carried by its token and verifies the address in +-- one optimistic update. The caller holds the token lock and checks the +-- matching C1 in the same transaction. +-- name: ConfirmUserEmail :one +UPDATE users +SET + password_hash = sqlc.arg(password_hash), + scenario = sqlc.arg(scenario), + onboarding_step = sqlc.arg(onboarding_step), + email_verified_at = sqlc.arg(verified_at), + updated_at = sqlc.arg(verified_at), + version = version + 1 +WHERE + id = sqlc.arg(id) + AND registration_version = sqlc.arg(registration_version) + AND email_verified_at IS NULL +RETURNING + id, + email, + email_normalized, + password_hash, + scenario, + onboarding_step, + email_verified_at, + registration_version, + last_registered_at, + version, + created_at, + updated_at; + +-- Deletes one batch of accounts that stayed unverified since before cutoff, +-- oldest first, with their tokens, sessions, mail requests, mail deliveries +-- (and through the deliveries their attempts), and consent records. The +-- consent records reference the account with ON DELETE RESTRICT, so they are +-- deleted explicitly in the same statement: a registration never confirmed +-- by its email owner is not kept as consent evidence. Every lock is taken +-- with SKIP LOCKED, so the statement never waits: an account whose row is +-- locked, for example by a re-registration, a token insert, a delivery +-- insert, or a consent insert, is skipped, and so is an account with any +-- token, session, mail request, delivery, or consent row locked, for example +-- by a confirmation that consumed a token, the delivery consumer, or a +-- worker recording an attempt. Skipped accounts stay for the next run. +-- Taking the account lock before the token locks is the reverse of the +-- documented order, which is safe only because no lock here waits. +-- name: DeleteUnverifiedUsersRegisteredBefore :execrows +WITH candidate AS ( + SELECT stale.id + FROM users AS stale + WHERE + stale.email_verified_at IS NULL + AND stale.last_registered_at < sqlc.arg(cutoff) + ORDER BY stale.last_registered_at + LIMIT sqlc.arg(batch_limit) + FOR UPDATE SKIP LOCKED +), + +locked_token AS ( + SELECT token.user_id + FROM email_tokens AS token + WHERE token.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_session AS ( + SELECT session.user_id + FROM sessions AS session + WHERE session.user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_mail_request AS ( + SELECT request.recipient_user_id + FROM mail_requests AS request + WHERE request.recipient_user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_delivery AS ( + SELECT delivery.recipient_user_id + FROM deliveries AS delivery + WHERE delivery.recipient_user_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +locked_consent AS ( + SELECT consent.subject_id + FROM consent_records AS consent + WHERE consent.subject_id IN (SELECT candidate.id FROM candidate) + FOR UPDATE SKIP LOCKED +), + +-- An account qualifies only when every token, session, mail request, +-- delivery, and consent row visible to the statement was locked above. +deletable AS ( + SELECT candidate.id + FROM candidate + WHERE + ( + SELECT count(*) FROM email_tokens AS token + WHERE token.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_token + WHERE locked_token.user_id = candidate.id + ) + AND ( + SELECT count(*) FROM sessions AS session + WHERE session.user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_session + WHERE locked_session.user_id = candidate.id + ) + AND ( + SELECT count(*) FROM mail_requests AS request + WHERE request.recipient_user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_mail_request + WHERE locked_mail_request.recipient_user_id = candidate.id + ) + AND ( + SELECT count(*) FROM deliveries AS delivery + WHERE delivery.recipient_user_id = candidate.id + ) = ( + SELECT count(*) FROM locked_delivery + WHERE locked_delivery.recipient_user_id = candidate.id + ) + AND ( + SELECT count(*) FROM consent_records AS consent + WHERE consent.subject_id = candidate.id + ) = ( + SELECT count(*) FROM locked_consent + WHERE locked_consent.subject_id = candidate.id + ) +), + +-- The restricting foreign key is checked at the end of the statement, after +-- these rows are gone. +deleted_consent AS ( + DELETE FROM consent_records + USING deletable + WHERE consent_records.subject_id = deletable.id +) + +DELETE FROM users +USING deletable +WHERE users.id = deletable.id; + +-- name: InsertEmailToken :exec +INSERT INTO email_tokens ( + id, + user_id, + purpose, + token_hash, + registration_version, + created_at, + expires_at, + code_hash, + code_expires_at, + pending_password_hash, + pending_scenario, + pending_onboarding_step +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(purpose), + sqlc.arg(token_hash), + sqlc.arg(registration_version), + sqlc.arg(created_at), + sqlc.arg(expires_at), + sqlc.narg(code_hash), + sqlc.narg(code_expires_at), + sqlc.narg(pending_password_hash), + sqlc.narg(pending_scenario), + sqlc.narg(pending_onboarding_step) +); + +-- The pending credentials of the newest token of a registration, for a +-- resend, which issues its token with the same credentials. +-- name: GetLatestPendingRegistration :one +SELECT + pending_password_hash, + pending_scenario, + pending_onboarding_step +FROM email_tokens +WHERE + user_id = sqlc.arg(user_id) + AND purpose = sqlc.arg(purpose) + AND registration_version = sqlc.arg(registration_version) + AND pending_password_hash IS NOT NULL +ORDER BY created_at DESC, id DESC +LIMIT 1; + +-- Reads a token before password verification; Consume rechecks it in the +-- confirmation transaction and clears pending credentials when it succeeds. +-- name: GetEmailTokenByHash :one +SELECT + id, + user_id, + purpose, + token_hash, + registration_version, + created_at, + expires_at, + consumed_at, + invalidated_at, + code_hash, + code_expires_at, + code_failed_attempts, + pending_password_hash, + pending_scenario, + pending_onboarding_step +FROM email_tokens +WHERE token_hash = sqlc.arg(token_hash) + AND purpose = sqlc.arg(purpose); + +-- Reads the newest open verification token that carries a code for the +-- unverified account with this normalized address. The registration version +-- must be current, so a code of an earlier registration never matches. The +-- row is read before the code is compared; the consumption rechecks it. +-- name: GetOpenEmailCodeByAddress :one +SELECT + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at, + token.code_hash, + token.code_expires_at, + token.code_failed_attempts, + token.pending_password_hash, + token.pending_scenario, + token.pending_onboarding_step +FROM email_tokens AS token +INNER JOIN users AS owner ON owner.id = token.user_id +WHERE + owner.email_normalized = sqlc.arg(email_normalized) + AND owner.email_verified_at IS NULL + AND owner.registration_version = token.registration_version + AND token.purpose = sqlc.arg(purpose) + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.code_hash IS NOT NULL + AND token.pending_password_hash IS NOT NULL +ORDER BY token.created_at DESC, token.id DESC +LIMIT 1; + +-- Counts one failed code or password attempt against an open code. The +-- single UPDATE reads and writes the counter under the row lock, so concurrent +-- failures serialize and none is lost. The attempt that reaches the limit +-- invalidates the token and drops its code and pending credentials, so the +-- code and the link both stop working. A token that is no longer open matches +-- no row and is left unchanged. +-- name: RecordFailedEmailCodeAttempt :one +UPDATE email_tokens +SET + code_failed_attempts = code_failed_attempts + 1, + invalidated_at = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN sqlc.arg(attempted_at) + ELSE invalidated_at + END, + code_hash = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE code_hash + END, + code_expires_at = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE code_expires_at + END, + pending_password_hash = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE pending_password_hash + END, + pending_scenario = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE pending_scenario + END, + pending_onboarding_step = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE pending_onboarding_step + END +WHERE + id = sqlc.arg(id) + AND consumed_at IS NULL + AND invalidated_at IS NULL + AND code_hash IS NOT NULL + AND code_failed_attempts < sqlc.arg(max_attempts) +RETURNING code_failed_attempts >= sqlc.arg(max_attempts) AS burned; + +-- Starts a new registration of an unverified account without touching its +-- credentials, scenario, or onboarding step: the new registration carries +-- them on its verification token. Advances the registration version, which +-- ends every earlier token, and deletes the registration C1 of the earlier +-- registrant like UpdateUserRegistration does. +-- name: AdvanceUserRegistration :one +WITH updated AS ( + UPDATE users + SET + registration_version = registration_version + 1, + last_registered_at = sqlc.arg(registered_at), + updated_at = sqlc.arg(registered_at), + version = version + 1 + WHERE + users.id = sqlc.arg(id) + AND users.version = sqlc.arg(expected_version) + AND users.email_verified_at IS NULL + RETURNING + users.id, + users.email, + users.email_normalized, + users.password_hash, + users.scenario, + users.onboarding_step, + users.email_verified_at, + users.registration_version, + users.last_registered_at, + users.version, + users.created_at, + users.updated_at +), + +discarded_consent AS ( + DELETE FROM consent_records + USING updated + WHERE + consent_records.subject_id = updated.id + AND consent_records.purpose = 'c1' + AND consent_records.source = 'registration' +) + +SELECT + updated.id, + updated.email, + updated.email_normalized, + updated.password_hash, + updated.scenario, + updated.onboarding_step, + updated.email_verified_at, + updated.registration_version, + updated.last_registered_at, + updated.version, + updated.created_at, + updated.updated_at +FROM updated; + +-- name: InvalidateActiveEmailTokens :execrows +UPDATE email_tokens +SET + invalidated_at = sqlc.arg(invalidated_at), + -- An invalidated token keeps no password hash or code: it can never be confirmed. + pending_password_hash = NULL, + pending_scenario = NULL, + pending_onboarding_step = NULL, + code_hash = NULL, + code_expires_at = NULL +WHERE + user_id = sqlc.arg(user_id) + AND purpose = sqlc.arg(purpose) + AND consumed_at IS NULL + AND invalidated_at IS NULL; + +-- Consumes a token in one statement. Concurrent callers queue on the token +-- row lock; under READ COMMITTED each waiter re-checks the WHERE clause +-- against the committed row, so exactly one of them updates it. The join +-- compares the registration version with the account row as the statement +-- reads it, without locking that row, so it rejects a token from an earlier +-- registration that already committed but not one that commits afterwards. +-- The confirmation guarantee therefore needs MarkUserEmailVerified with the +-- returned registration version in the same transaction, rolled back when it +-- matches no row. +-- name: ConsumeEmailToken :one +WITH candidate AS MATERIALIZED ( + SELECT + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.pending_password_hash, + token.pending_scenario, + token.pending_onboarding_step + FROM email_tokens AS token + INNER JOIN users AS owner ON owner.id = token.user_id + WHERE + token.token_hash = sqlc.arg(token_hash) + AND token.purpose = sqlc.arg(purpose) + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.expires_at > sqlc.arg(consumed_at) + AND owner.registration_version = token.registration_version + FOR UPDATE OF token +), + +consumed AS ( + UPDATE email_tokens AS token + SET + consumed_at = sqlc.arg(consumed_at), + pending_password_hash = NULL, + pending_scenario = NULL, + pending_onboarding_step = NULL, + code_hash = NULL, + code_expires_at = NULL + FROM candidate + WHERE token.id = candidate.id + RETURNING token.id, token.consumed_at, token.invalidated_at +) + +SELECT + candidate.id, + candidate.user_id, + candidate.purpose, + candidate.token_hash, + candidate.registration_version, + candidate.created_at, + candidate.expires_at, + consumed.consumed_at, + consumed.invalidated_at, + candidate.pending_password_hash, + candidate.pending_scenario, + candidate.pending_onboarding_step +FROM candidate +INNER JOIN consumed ON consumed.id = candidate.id; + +-- Explains why ConsumeEmailToken matched no row. +-- name: GetEmailTokenState :one +SELECT + token.consumed_at, + token.invalidated_at, + token.expires_at, + owner.registration_version = token.registration_version AS current_registration +FROM email_tokens AS token +INNER JOIN users AS owner ON token.user_id = owner.id +WHERE + token.token_hash = sqlc.arg(token_hash) + AND token.purpose = sqlc.arg(purpose); + +-- name: InsertSession :exec +INSERT INTO sessions ( + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(token_hash), + sqlc.arg(created_at), + sqlc.arg(last_seen_at), + sqlc.arg(expires_at) +); + +-- name: GetActiveSessionByTokenHash :one +SELECT + id, + user_id, + token_hash, + created_at, + last_seen_at, + expires_at, + revoked_at +FROM sessions +WHERE + token_hash = sqlc.arg(token_hash) + AND revoked_at IS NULL + AND expires_at > sqlc.arg(at) + AND last_seen_at > sqlc.arg(idle_cutoff); + +-- Records activity on an active session and reports whether it is active. +-- The row is written only when last_seen_at is older than touch_cutoff, so +-- frequent requests do not rewrite it. last_seen_at never moves back, and a +-- revoked, expired, or idle session is not revived; the update re-checks +-- those conditions against a concurrent change. +-- name: TouchSession :one +WITH active_session AS ( + SELECT candidate.id + FROM sessions AS candidate + WHERE + candidate.id = sqlc.arg(id) + AND candidate.revoked_at IS NULL + AND candidate.expires_at > sqlc.arg(at) + AND candidate.last_seen_at > sqlc.arg(idle_cutoff) +), + +touched AS ( + UPDATE sessions + SET last_seen_at = sqlc.arg(at) + WHERE + sessions.id = sqlc.arg(id) + AND sessions.revoked_at IS NULL + AND sessions.expires_at > sqlc.arg(at) + AND sessions.last_seen_at > sqlc.arg(idle_cutoff) + AND sessions.last_seen_at < sqlc.arg(touch_cutoff) + RETURNING sessions.id +) + +SELECT + exists(SELECT 1 FROM active_session) AS active, + exists(SELECT 1 FROM touched) AS touched; + +-- name: RevokeSession :execrows +UPDATE sessions +SET revoked_at = sqlc.arg(revoked_at) +WHERE + id = sqlc.arg(id) + AND revoked_at IS NULL; + +-- name: RevokeUserSessions :execrows +UPDATE sessions +SET revoked_at = sqlc.arg(revoked_at) +WHERE + user_id = sqlc.arg(user_id) + AND revoked_at IS NULL; + +-- Stores the replay record of a command. A record whose retention has passed +-- is replaced, so the key is accepted as new after the retention. A live +-- record is left as it is and nothing is returned; the caller then reads it +-- with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait +-- on the row of the first one until its transaction ends. +-- name: ReserveIdempotencyRecord :one +INSERT INTO idempotency_records ( + scope_hash, + fingerprint, + created_at, + expires_at +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(fingerprint), + sqlc.arg(created_at), + sqlc.arg(expires_at) +) +ON CONFLICT (scope_hash) DO UPDATE +SET + fingerprint = excluded.fingerprint, + created_at = excluded.created_at, + expires_at = excluded.expires_at +WHERE idempotency_records.expires_at <= excluded.created_at +RETURNING scope_hash, fingerprint, created_at, expires_at; + +-- name: GetLiveIdempotencyRecord :one +SELECT + scope_hash, + fingerprint, + created_at, + expires_at +FROM idempotency_records +WHERE + scope_hash = sqlc.arg(scope_hash) + AND expires_at > sqlc.arg(at); + +-- Deletes at most batch_limit expired records. Locked rows are skipped, so +-- the statement never waits for a concurrent reservation. +-- name: PurgeExpiredIdempotencyRecords :execrows +DELETE FROM idempotency_records +WHERE scope_hash IN ( + SELECT stale.scope_hash + FROM idempotency_records AS stale + WHERE stale.expires_at <= sqlc.arg(at) + ORDER BY stale.expires_at + LIMIT sqlc.arg(batch_limit) + FOR UPDATE SKIP LOCKED +); diff --git a/backend/db/queries/invitation_answers.sql b/backend/db/queries/invitation_answers.sql new file mode 100644 index 0000000..4334e59 --- /dev/null +++ b/backend/db/queries/invitation_answers.sql @@ -0,0 +1,168 @@ +-- Read one delivered invitation addressed to the candidate with the current +-- name of the organization that sent it. A draft and an invitation of +-- another candidate find nothing. +-- name: ReadCandidateInvitationEntry :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms, + organization.name AS organization_name +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +INNER JOIN organizations AS organization + ON organization.id = invitation.organization_id +WHERE + invitation.candidate_id = sqlc.arg(candidate_id) + AND invitation.id = sqlc.arg(invitation_id) + AND invitation.delivered_at IS NOT NULL; + +-- Lock one delivered invitation addressed to the candidate. Only the +-- invitation row is locked, never the organization. +-- name: LockCandidateInvitation :one +SELECT id +FROM invitations +WHERE + candidate_id = sqlc.arg(candidate_id) + AND id = sqlc.arg(invitation_id) + AND delivered_at IS NOT NULL +FOR UPDATE; + +-- The compare-and-swap of the first view: it applies only to a delivered +-- invitation at the version the caller read and before its deadline, and it +-- keeps the deadline. +-- name: RecordInvitationView :one +UPDATE invitations +SET + state = 'viewed', + version = sqlc.arg(next_version), + viewed_at = sqlc.arg(viewed_at), + updated_at = sqlc.arg(viewed_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state = 'delivered' + AND version = sqlc.arg(expected_version) + AND response_deadline_at > sqlc.arg(viewed_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- The compare-and-swap of a decline: it applies only to an answerable +-- invitation at the version the caller read and before its deadline. +-- name: DeclineInvitation :one +UPDATE invitations +SET + state = 'declined', + version = sqlc.arg(next_version), + responded_at = sqlc.arg(declined_at), + updated_at = sqlc.arg(declined_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state IN ('delivered', 'viewed', 'counter') + AND version = sqlc.arg(expected_version) + AND response_deadline_at > sqlc.arg(declined_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- name: InsertInvitationDecline :exec +INSERT INTO invitation_declines ( + invitation_id, + organization_id, + reason, + comment, + declined_at +) VALUES ( + sqlc.arg(invitation_id), + sqlc.arg(organization_id), + sqlc.arg(reason), + sqlc.narg(comment), + sqlc.arg(declined_at) +); + +-- name: ReadInvitationDecline :one +SELECT + invitation_id, + organization_id, + reason, + comment, + declined_at +FROM invitation_declines +WHERE + organization_id = sqlc.arg(organization_id) + AND invitation_id = sqlc.arg(invitation_id); + +-- name: InsertInvitationDeclineResult :exec +INSERT INTO invitation_decline_results ( + scope_hash, + invitation_id, + outcome +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(invitation_id), + sqlc.arg(outcome) +); + +-- name: GetInvitationDeclineResult :one +SELECT + invitation_id, + outcome +FROM invitation_decline_results +WHERE scope_hash = sqlc.arg(scope_hash); + +-- The compare-and-swap of an acceptance: it applies only to a delivered or +-- viewed invitation at the version and the terms version that the candidate +-- read, and before its deadline. The answer is the acceptance time, and the +-- deadline is kept. +-- name: AcceptInvitation :one +UPDATE invitations +SET + state = 'accepted', + version = sqlc.arg(next_version), + responded_at = sqlc.arg(accepted_at), + updated_at = sqlc.arg(accepted_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state IN ('delivered', 'viewed') + AND version = sqlc.arg(expected_version) + AND terms_version = sqlc.arg(terms_version) + AND response_deadline_at > sqlc.arg(accepted_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- name: InsertInvitationAcceptResult :exec +INSERT INTO invitation_accept_results ( + scope_hash, + invitation_id, + outcome +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(invitation_id), + sqlc.arg(outcome) +); + +-- name: GetInvitationAcceptResult :one +SELECT + invitation_id, + outcome +FROM invitation_accept_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/invitation_cooldowns.sql b/backend/db/queries/invitation_cooldowns.sql new file mode 100644 index 0000000..6522c85 --- /dev/null +++ b/backend/db/queries/invitation_cooldowns.sql @@ -0,0 +1,13 @@ +-- The time of the latest decline of one candidate by one organization, across +-- every need and every member of the organization. The pause that follows it is +-- applied by the send, from the policy in force. A candidate without a decline +-- finds no row. +-- name: LatestInvitationDecline :one +SELECT responded_at AS declined_at +FROM invitations +WHERE + organization_id = sqlc.arg(organization_id) + AND candidate_id = sqlc.arg(candidate_id) + AND state = 'declined' +ORDER BY responded_at DESC +LIMIT 1; diff --git a/backend/db/queries/invitation_delivery.sql b/backend/db/queries/invitation_delivery.sql new file mode 100644 index 0000000..6574404 --- /dev/null +++ b/backend/db/queries/invitation_delivery.sql @@ -0,0 +1,123 @@ +-- The conditional update is the compare-and-swap of a send: it applies only to +-- a draft whose version is still the one the caller read, records the first +-- delivery with its deadline, and advances the version by one. No row is +-- returned when it lost a race or the invitation is no longer a draft. +-- name: DeliverInvitation :one +UPDATE invitations +SET + state = 'delivered', + version = sqlc.arg(next_version), + delivered_at = sqlc.arg(delivered_at), + response_deadline_at = sqlc.arg(response_deadline_at), + updated_at = sqlc.arg(delivered_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state = 'draft' + AND version = sqlc.arg(expected_version) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- One bounded page of the candidate's inbox: every invitation delivered to +-- the candidate, in any later state, newest first by delivery time. Drafts +-- have no delivery and are never listed. The candidate scopes the rows, so +-- no identifier of another candidate can appear. +-- name: ListCandidateInvitations :many +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms, + organization.name AS organization_name +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +INNER JOIN organizations AS organization + ON organization.id = invitation.organization_id +WHERE + invitation.candidate_id = sqlc.arg(candidate_id) + AND invitation.delivered_at IS NOT NULL + AND ( + sqlc.narg(after_delivered_at)::timestamptz IS NULL + OR (invitation.delivered_at, invitation.id) < ( + sqlc.narg(after_delivered_at)::timestamptz, + sqlc.narg(after_invitation_id)::uuid + ) + ) +ORDER BY invitation.delivered_at DESC, invitation.id DESC +LIMIT sqlc.arg(row_limit); + +-- Read one delivered invitation addressed to the candidate. A draft and an +-- invitation of another candidate find nothing. +-- name: ReadCandidateInvitation :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.candidate_id = sqlc.arg(candidate_id) + AND invitation.id = sqlc.arg(invitation_id) + AND invitation.delivered_at IS NOT NULL; + +-- name: InsertInvitationSendResult :exec +INSERT INTO invitation_send_results ( + scope_hash, + organization_id, + invitation_id, + outcome, + snapshot +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(organization_id), + sqlc.arg(invitation_id), + sqlc.arg(outcome), + sqlc.narg(snapshot)::jsonb +); + +-- name: GetInvitationSendResult :one +SELECT + organization_id, + invitation_id, + outcome, + -- A refusal has no snapshot; the empty text stands for it. + coalesce(snapshot::text, '')::text AS snapshot +FROM invitation_send_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/invitation_expiry.sql b/backend/db/queries/invitation_expiry.sql new file mode 100644 index 0000000..98784fc --- /dev/null +++ b/backend/db/queries/invitation_expiry.sql @@ -0,0 +1,30 @@ +-- Takes the row lock of one invitation by its identifier alone. Only the +-- response deadline job reads an invitation without an organization or a +-- candidate of the request; it reads the organization from this row and then +-- reads the locked invitation with its scope. +-- name: LockInvitationByID :one +SELECT organization_id +FROM invitations +WHERE id = sqlc.arg(invitation_id) +FOR UPDATE; + +-- The compare-and-swap of the expiry: it applies only to a delivered or viewed +-- invitation at the version the caller read, whose deadline has passed at the +-- expiry time. It keeps the deadline, the terms, and every answer field, and it +-- sets the timeout reason. No row is returned when it lost a race or the +-- deadline has not passed. +-- name: ExpireInvitation :one +UPDATE invitations +SET + state = 'expired', + expiry_reason = 'invitation_timeout', + version = sqlc.arg(next_version), + updated_at = sqlc.arg(expired_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state IN ('delivered', 'viewed') + AND version = sqlc.arg(expected_version) + AND response_deadline_at <= sqlc.arg(expired_at) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; diff --git a/backend/db/queries/invitation_pending.sql b/backend/db/queries/invitation_pending.sql new file mode 100644 index 0000000..470670f --- /dev/null +++ b/backend/db/queries/invitation_pending.sql @@ -0,0 +1,11 @@ +-- Counts the invitations of one organization need that wait for an answer: +-- delivered, viewed, or the planned counter offer. The send counts them under +-- the organization lock, which every send takes first, so no other send can +-- add a waiting invitation between the count and its own delivery. +-- name: CountPendingNeedInvitations :one +SELECT count(*)::bigint AS pending +FROM invitations +WHERE + organization_id = sqlc.arg(organization_id) + AND need_id = sqlc.arg(need_id) + AND state IN ('delivered', 'viewed', 'counter'); diff --git a/backend/db/queries/invitations.sql b/backend/db/queries/invitations.sql new file mode 100644 index 0000000..a202050 --- /dev/null +++ b/backend/db/queries/invitations.sql @@ -0,0 +1,224 @@ +-- The invitation row, its first terms version, and its first audit event are +-- inserted in one caller-owned transaction. The deferred reference to the +-- current terms version is checked when the transaction commits. +-- name: InsertInvitation :exec +INSERT INTO invitations ( + id, + organization_id, + candidate_id, + need_id, + need_requirements_version, + state, + version, + terms_version, + response_period_days, + policy_version_id, + created_by, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(organization_id), + sqlc.arg(candidate_id), + sqlc.narg(need_id), + sqlc.narg(need_requirements_version), + sqlc.arg(state), + sqlc.arg(version), + sqlc.arg(terms_version), + sqlc.arg(response_period_days), + sqlc.arg(policy_version_id), + sqlc.arg(created_by), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- name: InsertInvitationTermsVersion :exec +INSERT INTO invitation_terms_versions ( + invitation_id, + organization_id, + version, + terms, + salary_from, + salary_to, + salary_currency, + salary_period, + salary_tax_basis, + created_at +) VALUES ( + sqlc.arg(invitation_id), + sqlc.arg(organization_id), + sqlc.arg(version), + sqlc.arg(terms)::jsonb, + sqlc.arg(salary_from), + sqlc.arg(salary_to), + sqlc.arg(salary_currency), + sqlc.arg(salary_period), + sqlc.arg(salary_tax_basis), + sqlc.arg(created_at) +); + +-- name: InsertInvitationEvent :exec +INSERT INTO invitation_events ( + id, + invitation_id, + organization_id, + version, + terms_version, + kind, + actor_id, + changed_fields, + occurred_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(invitation_id), + sqlc.arg(organization_id), + sqlc.arg(version), + sqlc.arg(terms_version), + sqlc.arg(kind), + sqlc.arg(actor_id), + sqlc.arg(changed_fields)::text [], + sqlc.arg(occurred_at) +); + +-- Read one current invitation with its terms snapshot. Both the organization +-- and the invitation scope the row, so another organization's identifier +-- finds nothing. +-- name: ReadInvitation :one +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.organization_id = sqlc.arg(organization_id) + AND invitation.id = sqlc.arg(invitation_id); + +-- Takes the row lock of one invitation. It is a statement of its own, ahead of +-- ReadInvitation, because a locking read that joins the terms table is +-- re-checked against the new row version after a wait and then pairs the +-- updated terms_version with the terms row it fetched before the wait, which +-- finds nothing. Once the lock is held, the following read sees the committed +-- state and no writer can change it. +-- name: LockInvitation :one +SELECT id +FROM invitations +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) +FOR UPDATE; + +-- Read one historical terms version of one invitation of one organization. +-- name: ReadInvitationTermsVersion :one +SELECT terms::text AS terms +FROM invitation_terms_versions +WHERE + organization_id = sqlc.arg(organization_id) + AND invitation_id = sqlc.arg(invitation_id) + AND version = sqlc.arg(version); + +-- One bounded newest-first page. Both the organization scope and the tuple +-- cursor are applied before the limit. +-- name: ListInvitations :many +SELECT + invitation.id, + invitation.organization_id, + invitation.candidate_id, + invitation.need_id, + invitation.need_requirements_version, + invitation.state, + invitation.expiry_reason, + invitation.version, + invitation.terms_version, + invitation.response_period_days, + invitation.policy_version_id, + invitation.response_deadline_at, + invitation.salary_raise_used, + invitation.created_by, + invitation.created_at, + invitation.updated_at, + invitation.delivered_at, + invitation.viewed_at, + invitation.responded_at, + terms.terms::text AS terms +FROM invitations AS invitation +INNER JOIN invitation_terms_versions AS terms + ON terms.invitation_id = invitation.id + AND terms.version = invitation.terms_version +WHERE + invitation.organization_id = sqlc.arg(organization_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (invitation.created_at, invitation.id) < ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_invitation_id)::uuid + ) + ) +ORDER BY invitation.created_at DESC, invitation.id DESC +LIMIT sqlc.arg(row_limit); + +-- The conditional update is the compare-and-swap of a draft: it applies only +-- to a draft whose version is still the one the caller read, and advances the +-- version by one. No row is returned when it lost a race or the invitation +-- left the draft state. +-- name: AdvanceInvitationDraft :one +UPDATE invitations +SET + need_id = sqlc.narg(need_id), + need_requirements_version = sqlc.narg(need_requirements_version), + response_period_days = sqlc.arg(response_period_days), + policy_version_id = sqlc.arg(policy_version_id), + terms_version = sqlc.arg(terms_version), + version = sqlc.arg(next_version), + updated_at = sqlc.arg(updated_at) +WHERE + organization_id = sqlc.arg(organization_id) + AND id = sqlc.arg(invitation_id) + AND state = 'draft' + AND version = sqlc.arg(expected_version) + AND sqlc.arg(next_version)::bigint = sqlc.arg(expected_version)::bigint + 1 +RETURNING id; + +-- A requirements version that a need of the organization has had is the +-- version number of a stored snapshot whose own requirements version is that +-- number, so a later edit that only renamed the need is not accepted. +-- name: InvitationNeedVersionExists :one +SELECT EXISTS ( + SELECT 1 + FROM organization_need_versions + WHERE + organization_id = sqlc.arg(organization_id) + AND need_id = sqlc.arg(need_id) + AND version = sqlc.arg(requirements_version)::bigint + AND snapshot ->> 'requirements_version' = sqlc.arg(requirements_version)::bigint::text +) AS found; + +-- name: SaveInvitationCreationResult :exec +INSERT INTO invitation_creation_results (scope_hash, snapshot) +VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot; + +-- name: GetInvitationCreationResult :one +SELECT snapshot::text AS snapshot +FROM invitation_creation_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/mail_quota.sql b/backend/db/queries/mail_quota.sql new file mode 100644 index 0000000..6d19cae --- /dev/null +++ b/backend/db/queries/mail_quota.sql @@ -0,0 +1,193 @@ +-- Lock order. Every transaction that writes mail_quota_usage first creates +-- and locks all the usage rows it will touch with EnsureMailQuotaRows and +-- LockMailQuotaRows, which both work in (period_kind, period_start) order, +-- and only then writes them or a mail_quota_reservations row. Later UPDATE +-- statements of the same transaction find their rows locked already, so the +-- scan order of an UPDATE never decides the lock order. + +-- Creates the listed window rows of a provider account with no usage when +-- they do not exist yet, in (period_kind, period_start) order. A window key +-- is "/". A concurrent insert of the same row waits +-- for the first transaction and then inserts nothing. Existing rows are +-- neither changed nor locked here. +-- name: EnsureMailQuotaRows :exec +INSERT INTO mail_quota_usage ( + provider, + provider_account, + period_kind, + period_start, + used_recipients, + updated_at +) +SELECT + sqlc.arg(provider)::text, + sqlc.arg(provider_account)::text, + split_part(window_key, '/', 1), + split_part(window_key, '/', 2)::date, + 0, + sqlc.arg(updated_at)::timestamptz +FROM unnest(sqlc.arg(window_keys)::text []) AS window_key +ORDER BY split_part(window_key, '/', 1), split_part(window_key, '/', 2)::date +ON CONFLICT ( + provider, provider_account, period_kind, period_start +) DO NOTHING; + +-- Locks the listed window rows until the transaction ends, in +-- (period_kind, period_start) order, the same order for every caller, and +-- returns their usage. Under READ COMMITTED a waiting caller reads the usage +-- the first caller committed. period_starts narrows the index scan; +-- window_keys selects the exact rows. +-- name: LockMailQuotaRows :many +SELECT + period_kind, + period_start, + used_recipients +FROM mail_quota_usage +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND period_start = any(sqlc.arg(period_starts)::date []) + AND period_kind || '/' || to_char(period_start, 'YYYY-MM-DD') + = any(sqlc.arg(window_keys)::text []) +ORDER BY period_kind, period_start +FOR UPDATE; + +-- Adds recipients to the day and the month row. The caller holds their +-- locks from LockMailQuotaRows and has checked both limits. +-- name: AddMailQuotaUsage :execrows +UPDATE mail_quota_usage +SET + used_recipients = mail_quota_usage.used_recipients + + sqlc.arg(recipients)::bigint, + updated_at = sqlc.arg(updated_at) +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND ( + (period_kind = 'day' AND period_start = sqlc.arg(day_start)) + OR (period_kind = 'month' AND period_start = sqlc.arg(month_start)) + ); + +-- Gives back recipients of a released reservation. The caller holds the row +-- locks. A window that the provider reported exhausted keeps its usage: the +-- provider's answer outranks the local count until the window resets. The +-- count never drops below zero. +-- name: ReleaseMailQuotaUsage :execrows +UPDATE mail_quota_usage +SET + used_recipients = greatest( + mail_quota_usage.used_recipients - sqlc.arg(recipients)::bigint, 0 + ), + updated_at = sqlc.arg(updated_at) +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND provider_exhausted_at IS NULL + AND ( + (period_kind = 'day' AND period_start = sqlc.arg(day_start)) + OR (period_kind = 'month' AND period_start = sqlc.arg(month_start)) + ); + +-- Records that the provider refused a send because the quota of a window is +-- used up: the usage rises to at least the configured limit, so the local +-- gate stops admitting sends until the window resets or an operator raises +-- the limit. The caller holds the row lock. +-- name: MarkMailQuotaExhausted :execrows +UPDATE mail_quota_usage +SET + used_recipients = greatest( + mail_quota_usage.used_recipients, sqlc.arg(limit_recipients)::bigint + ), + provider_exhausted_at = sqlc.arg(exhausted_at), + updated_at = sqlc.arg(exhausted_at) +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND period_kind = sqlc.arg(period_kind) + AND period_start = sqlc.arg(period_start); + +-- name: InsertMailQuotaReservation :exec +INSERT INTO mail_quota_reservations ( + id, + delivery_id, + provider, + provider_account, + day_start, + month_start, + recipients, + reserved_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(delivery_id), + sqlc.arg(provider), + sqlc.arg(provider_account), + sqlc.arg(day_start), + sqlc.arg(month_start), + sqlc.arg(recipients), + sqlc.arg(reserved_at) +); + +-- Returns the newest open reservation of a delivery under a provider account +-- made at or after reserved_since. A retry of the delivery inside the +-- provider's idempotency window reuses it instead of counting again. +-- name: FindOpenMailQuotaReservation :one +SELECT + id, + day_start, + month_start, + recipients, + reserved_at +FROM mail_quota_reservations +WHERE + delivery_id = sqlc.arg(delivery_id) + AND provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND released_at IS NULL + AND reserved_at >= sqlc.arg(reserved_since) +ORDER BY reserved_at DESC +LIMIT 1; + +-- Marks a reservation released. It matches only an open reservation, so a +-- repeated release changes nothing and returns 0 rows. +-- name: ReleaseMailQuotaReservation :execrows +UPDATE mail_quota_reservations +SET released_at = sqlc.arg(released_at) +WHERE + id = sqlc.arg(id) + AND released_at IS NULL; + +-- Records the latest settled outcome of a send under the reservation. +-- name: RecordMailQuotaOutcome :execrows +UPDATE mail_quota_reservations +SET + settled_outcome = sqlc.arg(settled_outcome), + settled_at = sqlc.arg(settled_at) +WHERE id = sqlc.arg(id); + +-- Reads the usage of the day and the month window without locking. +-- name: GetMailQuotaUsage :many +SELECT + period_kind, + used_recipients, + provider_exhausted_at +FROM mail_quota_usage +WHERE + provider = sqlc.arg(provider) + AND provider_account = sqlc.arg(provider_account) + AND ( + (period_kind = 'day' AND period_start = sqlc.arg(day_start)) + OR (period_kind = 'month' AND period_start = sqlc.arg(month_start)) + ); + +-- Lists the other accounts of a provider that have usage in a month, so +-- startup can warn about a renamed EMAIL_ACCOUNT. +-- name: ListOtherMailQuotaAccounts :many +SELECT DISTINCT provider_account +FROM mail_quota_usage +WHERE + provider = sqlc.arg(provider) + AND provider_account <> sqlc.arg(provider_account) + AND period_kind = 'month' + AND period_start = sqlc.arg(month_start) + AND used_recipients > 0 +ORDER BY provider_account; diff --git a/backend/db/queries/needs.sql b/backend/db/queries/needs.sql new file mode 100644 index 0000000..261b02d --- /dev/null +++ b/backend/db/queries/needs.sql @@ -0,0 +1,146 @@ +-- The parent and first immutable snapshot are inserted in one caller-owned +-- transaction. Deferred version references are checked when it commits. +-- name: InsertOrganizationNeed :exec +INSERT INTO organization_needs ( + id, + organization_id, + current_version, + requirements_version, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(organization_id), + sqlc.arg(current_version), + sqlc.arg(requirements_version), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- name: InsertOrganizationNeedVersion :exec +INSERT INTO organization_need_versions ( + organization_id, + need_id, + version, + snapshot +) VALUES ( + sqlc.arg(organization_id), + sqlc.arg(need_id), + sqlc.arg(version), + sqlc.arg(snapshot)::jsonb +); + +-- Read one current version with its organization-scoped parent metadata. +-- name: ReadCurrentOrganizationNeed :one +SELECT + need.organization_id, + need.id AS need_id, + need.current_version, + need.requirements_version, + need.created_at, + need.updated_at, + version.snapshot::text AS snapshot +FROM organization_needs AS need +INNER JOIN organization_need_versions AS version + ON version.organization_id = need.organization_id + AND version.need_id = need.id + AND version.version = need.current_version +WHERE + need.organization_id = sqlc.arg(organization_id) + AND need.id = sqlc.arg(need_id); + +-- Read one historical version without exposing another organization's record. +-- name: ReadOrganizationNeedVersion :one +SELECT snapshot::text AS snapshot +FROM organization_need_versions +WHERE + organization_id = sqlc.arg(organization_id) + AND need_id = sqlc.arg(need_id) + AND version = sqlc.arg(version); + +-- Read one bounded newest-first page of current needs. Both the organization +-- scope and the tuple cursor are applied before the limit. +-- name: ListOrganizationNeeds :many +SELECT + need.organization_id, + need.id AS need_id, + need.current_version, + need.requirements_version, + need.created_at, + need.updated_at, + version.snapshot::text AS snapshot +FROM organization_needs AS need +INNER JOIN organization_need_versions AS version + ON version.organization_id = need.organization_id + AND version.need_id = need.id + AND version.version = need.current_version +WHERE + need.organization_id = sqlc.arg(organization_id) + AND ( + sqlc.narg(after_created_at)::timestamptz IS NULL + OR (need.created_at, need.id) < ( + sqlc.narg(after_created_at)::timestamptz, + sqlc.narg(after_need_id)::uuid + ) + ) +ORDER BY need.created_at DESC, need.id DESC +LIMIT sqlc.arg(row_limit); + +-- The conditional parent update is the compare-and-swap. Appending the +-- snapshot is part of the same SQL statement, so a failed insert leaves the +-- parent pointer unchanged even before the surrounding transaction rolls +-- back. No row is returned when the expected version lost a race. +-- name: AdvanceOrganizationNeed :one +WITH advanced AS ( + UPDATE organization_needs + SET + current_version = organization_needs.current_version + 1, + requirements_version = sqlc.arg(requirements_version), + updated_at = sqlc.arg(updated_at) + WHERE + organization_needs.organization_id = sqlc.arg(organization_id) + AND organization_needs.id = sqlc.arg(need_id) + AND organization_needs.current_version = sqlc.arg(expected_version) + AND sqlc.arg(next_version)::bigint = organization_needs.current_version + 1 + AND ( + sqlc.arg(requirements_version)::bigint = organization_needs.requirements_version + OR sqlc.arg(requirements_version)::bigint = organization_needs.current_version + 1 + ) + RETURNING organization_needs.organization_id, organization_needs.id, organization_needs.current_version +), appended AS ( + INSERT INTO organization_need_versions ( + organization_id, + need_id, + version, + snapshot + ) + SELECT + advanced.organization_id, + advanced.id, + advanced.current_version, + sqlc.arg(snapshot)::jsonb + FROM advanced + RETURNING + organization_need_versions.organization_id, + organization_need_versions.need_id, + organization_need_versions.version, + organization_need_versions.snapshot::text AS snapshot +) +SELECT appended.snapshot +FROM appended; + +-- The generic idempotency scope serializes retries. Replacing the child row +-- is safe only in the transaction that reserves an expired scope for a new +-- create; live retries read and return the stored response without writing. +-- name: SaveOrganizationNeedCreationResult :exec +INSERT INTO organization_need_creation_results (scope_hash, snapshot) +VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot; + +-- Read only the immutable original response. The current need may have moved +-- to a later version since this result was created. +-- name: GetOrganizationNeedCreationResult :one +SELECT snapshot::text AS snapshot +FROM organization_need_creation_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/notification_inbox.sql b/backend/db/queries/notification_inbox.sql new file mode 100644 index 0000000..b66d095 --- /dev/null +++ b/backend/db/queries/notification_inbox.sql @@ -0,0 +1,125 @@ +-- Store one recipient's reference to a delivered invitation event. The +-- unique key absorbs at-least-once redelivery without copying event content. +-- name: InsertNotificationInboxEvent :execrows +INSERT INTO notification_inbox_events ( + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at +) VALUES ( + sqlc.arg(recipient_user_id), + sqlc.arg(event_id), + sqlc.arg(organization_id), + sqlc.arg(event_type), + sqlc.arg(schema_version), + sqlc.arg(source_type), + sqlc.arg(source_id), + sqlc.arg(occurred_at) +) +ON CONFLICT (recipient_user_id, event_id) DO NOTHING; + +-- Read the existing row after a duplicate insert so the repository can reject +-- an event ID whose immutable metadata changed on redelivery. +-- name: GetNotificationInboxEvent :one +SELECT + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at, + read_at +FROM notification_inbox_events +WHERE recipient_user_id = sqlc.arg(recipient_user_id) + AND event_id = sqlc.arg(event_id); + +-- List only the authenticated recipient's rows, optionally narrowed to one +-- organization context. The caller resolves current source visibility before +-- returning content. +-- name: ListNotificationInboxEvents :many +SELECT + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at, + read_at +FROM notification_inbox_events +WHERE recipient_user_id = sqlc.arg(recipient_user_id) + AND ( + sqlc.narg(organization_id)::uuid IS NULL + OR organization_id = sqlc.narg(organization_id)::uuid + ) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (occurred_at, event_id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_event_id)::uuid + ) + ) +ORDER BY occurred_at DESC, event_id DESC +LIMIT sqlc.arg(page_limit); + +-- Persist the first read time for the recipient, optionally under one exact +-- organization context. A missing organization is the candidate cabinet, +-- which spans the organizations that sent to it; the employer cabinet always +-- names its organization. Repeated calls preserve the original read +-- timestamp. +-- name: MarkNotificationInboxEventRead :one +UPDATE notification_inbox_events +SET read_at = COALESCE(read_at, sqlc.arg(read_at)::timestamptz) +WHERE recipient_user_id = sqlc.arg(recipient_user_id) + AND ( + sqlc.narg(organization_id)::uuid IS NULL + OR organization_id = sqlc.narg(organization_id)::uuid + ) + AND event_id = sqlc.arg(event_id) +RETURNING + recipient_user_id, + event_id, + organization_id, + event_type, + schema_version, + source_type, + source_id, + occurred_at, + read_at; + +-- Resolve the sender organization of a synthetic notice under the recipient's +-- current standing, so the notice never outlives that standing. A candidate +-- sees the name only while the organization is not hidden from them; an +-- employer sees it only while they are an active member. No row means the +-- content is no longer visible to this recipient. +-- name: GetNotificationOrganizationNameForRecipient :one +SELECT organizations.name +FROM organizations +INNER JOIN users ON users.id = sqlc.arg(recipient_user_id) +WHERE organizations.id = sqlc.arg(organization_id) + AND ( + ( + users.scenario = 'candidate' + AND NOT EXISTS ( + SELECT 1 FROM candidate_hidden_organizations + WHERE candidate_hidden_organizations.user_id = users.id + AND candidate_hidden_organizations.organization_id = organizations.id + ) + ) + OR ( + users.scenario = 'employer' + AND EXISTS ( + SELECT 1 FROM memberships + WHERE memberships.user_id = users.id + AND memberships.organization_id = organizations.id + AND memberships.state = 'active' + ) + ) + ); diff --git a/backend/db/queries/notification_rights.sql b/backend/db/queries/notification_rights.sql new file mode 100644 index 0000000..31c4aa5 --- /dev/null +++ b/backend/db/queries/notification_rights.sql @@ -0,0 +1,37 @@ +-- Reads the standing of an invitation notice in one statement, for the rights +-- check before the send. The recipient is matched by ID; the invitation must +-- be addressed to that recipient and belong to the organization of the +-- subject, otherwise it is not found. It reads no address and no contact: +-- the recipient address is returned only as its comparison key. The hiding +-- is the candidate's own current state. The publication is read through the +-- effective view, so a publication whose C2 consent was revoked does not count +-- as current. A missing account or invitation gives false flags and NULL +-- columns. +-- name: GetInvitationNoticeStanding :one +SELECT + (recipient.id IS NOT NULL)::boolean AS recipient_found, + coalesce(recipient.email_verified_at IS NOT NULL, false)::boolean AS recipient_email_verified, + coalesce(recipient.email_normalized, '')::text AS recipient_email_key, + (invitation.id IS NOT NULL)::boolean AS invitation_found, + invitation.organization_id AS invitation_organization_id, + coalesce(invitation.state, '')::text AS invitation_state, + invitation.response_deadline_at AS invitation_response_deadline_at, + EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = sqlc.arg(recipient_user_id) + AND hidden.organization_id = sqlc.arg(organization_id) + )::boolean AS organization_hidden, + EXISTS ( + SELECT 1 + FROM candidate_effective_publications AS publication + WHERE publication.user_id = sqlc.arg(recipient_user_id) + )::boolean AS publication_published +FROM (SELECT sqlc.arg(recipient_user_id)::uuid AS user_id) AS target +LEFT JOIN users AS recipient + ON recipient.id = target.user_id +LEFT JOIN invitations AS invitation + ON invitation.id = sqlc.arg(invitation_id) + AND invitation.candidate_id = target.user_id + AND invitation.organization_id = sqlc.arg(organization_id); diff --git a/backend/db/queries/organizations.sql b/backend/db/queries/organizations.sql new file mode 100644 index 0000000..c79b699 --- /dev/null +++ b/backend/db/queries/organizations.sql @@ -0,0 +1,269 @@ +-- Stores a new organization with the verification level that the domain +-- gave it and the holding of its creator. The deferred constraint +-- organizations_owner_required fails the transaction at commit unless an +-- active owner membership was inserted in it too. +-- name: InsertOrganization :exec +INSERT INTO organizations ( + id, + name, + description, + sphere, + contact_website, + contact_email, + contact_phone, + contact_telegram, + verification_level, + verification_basis, + verification_changed_at, + version, + created_at, + updated_at, + holding_id +) VALUES ( + sqlc.arg(id), + sqlc.arg(name), + sqlc.narg(description), + sqlc.narg(sphere), + sqlc.narg(contact_website), + sqlc.narg(contact_email), + sqlc.narg(contact_phone), + sqlc.narg(contact_telegram), + sqlc.arg(verification_level), + sqlc.arg(verification_basis), + sqlc.arg(verification_changed_at), + sqlc.arg(version), + sqlc.arg(created_at), + sqlc.arg(updated_at), + sqlc.arg(holding_id) +); + +-- Stores one representative at its position in the list. The adapter calls it +-- once per representative after it deleted the previous list, in the same +-- transaction. +-- name: InsertOrganizationRepresentative :exec +INSERT INTO organization_representatives ( + organization_id, + ordinal, + name, + job_title +) VALUES ( + sqlc.arg(organization_id), + sqlc.arg(ordinal), + sqlc.arg(name), + sqlc.arg(job_title) +); + +-- name: DeleteOrganizationRepresentatives :exec +DELETE FROM organization_representatives +WHERE organization_id = sqlc.arg(organization_id); + +-- Reads an organization together with the membership of one account in it +-- and its representatives in list order, as one statement, so the profile and +-- the list come from one snapshot. Only an active membership matches, so an +-- unknown organization, an account that is no member, and a suspended, +-- removed, or left member all return no row and cannot be told apart. +-- name: GetOrganizationForMember :one +SELECT + organization.id, + organization.name, + organization.description, + organization.sphere, + organization.contact_website, + organization.contact_email, + organization.contact_phone, + organization.contact_telegram, + organization.verification_level, + organization.verification_basis, + organization.verification_changed_at, + organization.version, + organization.created_at, + organization.updated_at, + coalesce(( + SELECT + jsonb_agg( + jsonb_build_object('name', representative.name, 'job_title', representative.job_title) + ORDER BY representative.ordinal + ) + FROM organization_representatives AS representative + WHERE representative.organization_id = organization.id + ), '[]'::jsonb)::text AS representatives, + membership.id AS membership_id, + membership.role AS membership_role, + membership.state AS membership_state, + membership.created_at AS membership_created_at, + membership.updated_at AS membership_updated_at +FROM organizations AS organization +INNER JOIN memberships AS membership ON organization.id = membership.organization_id +WHERE + organization.id = sqlc.arg(organization_id) + AND membership.user_id = sqlc.arg(user_id) + AND membership.state = 'active'; + +-- Locks the organization first and then the active membership, using the +-- same order as organization profile writes. A company operation keeps both +-- share locks until its transaction commits, so a concurrent revocation +-- cannot authorize a write after it has committed. +-- name: LockActiveMembership :one +WITH locked_organization AS MATERIALIZED ( + SELECT organizations.id + FROM organizations + WHERE organizations.id = sqlc.arg(organization_id) + FOR SHARE +) +SELECT + membership.id AS membership_id, + membership.organization_id, + membership.user_id, + membership.role, + membership.state, + membership.created_at, + membership.updated_at +FROM memberships AS membership +INNER JOIN locked_organization ON locked_organization.id = membership.organization_id +WHERE + membership.user_id = sqlc.arg(user_id) + AND membership.state = 'active' +FOR SHARE OF membership; + +-- Changes the profile of an organization over the version the caller read +-- and advances the version in the same statement. It names no verification +-- column, so a profile update cannot move the trust level. The change +-- applies only for an account whose active membership has one of the +-- manager roles, checked in the statement itself so that a membership that +-- ended after the caller's read still stops the write. The statement locks +-- the organization row first and then the actor's membership row FOR SHARE, +-- so a revocation that commits while the statement waits is seen again +-- (EvalPlanQual) and stops the write; the order organizations, then +-- memberships, is the lock order of every writer (member management must +-- follow it). No row returns for a stale version, an account that is no +-- active manager, or an unknown organization; the adapter reads the +-- membership to tell them apart. +-- name: UpdateOrganizationProfile :one +WITH target AS ( + SELECT id FROM organizations + WHERE + id = sqlc.arg(id) + AND version = sqlc.arg(expected_version) + FOR UPDATE +), + +actor AS ( + SELECT memberships.id FROM memberships + INNER JOIN target ON memberships.organization_id = target.id + WHERE + memberships.user_id = sqlc.arg(actor_id) + AND memberships.state = 'active' + AND memberships.role = any(sqlc.arg(manager_roles)::text []) + FOR SHARE OF memberships +) + +UPDATE organizations +SET + name = sqlc.arg(name), + description = sqlc.narg(description), + sphere = sqlc.narg(sphere), + contact_website = sqlc.narg(contact_website), + contact_email = sqlc.narg(contact_email), + contact_phone = sqlc.narg(contact_phone), + contact_telegram = sqlc.narg(contact_telegram), + updated_at = sqlc.arg(updated_at), + version = organizations.version + 1 +FROM actor +WHERE + organizations.id = sqlc.arg(id) + AND organizations.version = sqlc.arg(expected_version) +RETURNING + organizations.id, + organizations.name, + organizations.description, + organizations.sphere, + organizations.contact_website, + organizations.contact_email, + organizations.contact_phone, + organizations.contact_telegram, + organizations.verification_level, + organizations.verification_basis, + organizations.verification_changed_at, + organizations.version, + organizations.created_at, + organizations.updated_at; + +-- Lists the organizations where an account has an active membership, +-- newest membership first. The page continues after the (membership +-- creation time, organization ID) position of the last item of the +-- previous page. Only the active memberships of the given account match. +-- name: ListOrganizationsForUser :many +SELECT + organization.id, + organization.name, + organization.verification_level, + membership.id AS membership_id, + membership.role AS membership_role, + membership.state AS membership_state, + membership.created_at AS membership_created_at, + membership.updated_at AS membership_updated_at +FROM memberships AS membership +INNER JOIN organizations AS organization ON membership.organization_id = organization.id +WHERE + membership.user_id = sqlc.arg(user_id) + AND membership.state = 'active' + AND ( + sqlc.narg(after_joined_at)::timestamptz IS NULL + OR (membership.created_at, membership.organization_id) < ( + sqlc.narg(after_joined_at)::timestamptz, + sqlc.narg(after_organization_id)::uuid + ) + ) +ORDER BY membership.created_at DESC, membership.organization_id DESC +LIMIT sqlc.arg(row_limit); + +-- name: InsertMembership :exec +INSERT INTO memberships ( + id, + organization_id, + user_id, + role, + state, + created_at, + updated_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(organization_id), + sqlc.arg(user_id), + sqlc.arg(role), + sqlc.arg(state), + sqlc.arg(created_at), + sqlc.arg(updated_at) +); + +-- Reads the membership of one account in one organization, in any state. +-- name: GetMembership :one +SELECT + id, + organization_id, + user_id, + role, + state, + created_at, + updated_at +FROM memberships +WHERE + organization_id = sqlc.arg(organization_id) + AND user_id = sqlc.arg(user_id); + +-- Stores the immutable domain snapshot of a successful create command. The +-- generic idempotency row and this result are committed with the organization +-- and owner membership. A reused expired scope replaces the snapshot in the +-- same transaction as the new organization. +-- name: SaveOrganizationCreationResult :exec +INSERT INTO organization_creation_results (scope_hash, snapshot) +VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)) +ON CONFLICT (scope_hash) DO UPDATE +SET snapshot = excluded.snapshot; + +-- Reads only the historical result. It intentionally does not join the live +-- organization or membership, whose profile and state may have since changed. +-- name: GetOrganizationCreationResult :one +SELECT snapshot +FROM organization_creation_results +WHERE scope_hash = sqlc.arg(scope_hash); diff --git a/backend/db/queries/outbox.sql b/backend/db/queries/outbox.sql new file mode 100644 index 0000000..2af8e55 --- /dev/null +++ b/backend/db/queries/outbox.sql @@ -0,0 +1,97 @@ +-- name: InsertOutboxEvent :exec +INSERT INTO outbox_events ( + event_id, + event_type, + schema_version, + aggregate_type, + aggregate_id, + aggregate_version, + payload +) VALUES ( + sqlc.arg(event_id), + sqlc.arg(event_type), + sqlc.arg(schema_version), + sqlc.arg(aggregate_type), + sqlc.arg(aggregate_id), + sqlc.arg(aggregate_version), + sqlc.arg(payload) +); + +-- Locks the next relay batch. For each aggregate only its earliest unpublished +-- event (lowest aggregate_version, then position) qualifies, so a relay never +-- holds a later version while an earlier one is still pending, whether that +-- earlier row is locked by another relay or was just rolled back. Rows locked +-- by another relay are skipped without waiting. The statement snapshot can +-- only see a later version after the earlier version's transaction committed, +-- because aggregate writers check the expected version, so scanning without a +-- position watermark cannot overtake an earlier version. +-- name: LockPendingOutboxEvents :many +SELECT + pending.event_id, + pending.event_type, + pending.schema_version, + pending.aggregate_type, + pending.aggregate_id, + pending.aggregate_version, + pending.payload, + pending.occurred_at +FROM outbox_events AS pending +WHERE + pending.published_at IS NULL + AND NOT EXISTS ( + SELECT 1 + FROM outbox_events AS earlier + WHERE + earlier.aggregate_type = pending.aggregate_type + AND earlier.aggregate_id = pending.aggregate_id + AND earlier.published_at IS NULL + AND (earlier.aggregate_version, earlier.position) + < (pending.aggregate_version, pending.position) + ) +ORDER BY pending.position +LIMIT sqlc.arg(batch_limit) +FOR UPDATE OF pending SKIP LOCKED; + +-- Marks the events that the broker acknowledged. The relay passes only IDs +-- whose rows its own transaction locked, so the statement never waits and the +-- count equals the number of distinct IDs. +-- name: MarkOutboxEventsPublished :execrows +UPDATE outbox_events +SET published_at = clock_timestamp() +WHERE + event_id = ANY(sqlc.arg(event_ids)::uuid []) + AND published_at IS NULL; + +-- Reads the relay backlog for metrics without locking. Both subqueries use +-- the partial index on unpublished positions, so the cost follows the backlog +-- size, not the table size. The age comes from the database clock, the same +-- clock that set occurred_at. +-- name: GetOutboxBacklog :one +SELECT + ( + SELECT count(*) + FROM outbox_events AS pending + WHERE pending.published_at IS NULL + )::bigint AS pending_events, + coalesce(( + SELECT extract(EPOCH FROM clock_timestamp() - oldest.occurred_at) + FROM outbox_events AS oldest + WHERE oldest.published_at IS NULL + ORDER BY oldest.position + LIMIT 1 + ), 0)::float8 AS oldest_pending_age_seconds; + +-- Bounds the claim transaction on the server. statement_timeout stops a +-- statement that runs too long; idle_in_transaction_session_timeout ends the +-- session, and with it the transaction and its row locks, when the client +-- stays silent longer than a publish may take, for example after the process +-- froze or lost the network without closing the connection. Both settings +-- are local to the transaction. +-- name: SetRelayTransactionTimeouts :exec +SELECT + set_config('statement_timeout', sqlc.arg(statement_timeout_ms)::text, true), + set_config( + 'idle_in_transaction_session_timeout', + sqlc.arg(idle_timeout_ms)::text, + true + ); diff --git a/backend/db/queries/policy.sql b/backend/db/queries/policy.sql new file mode 100644 index 0000000..5fd8201 --- /dev/null +++ b/backend/db/queries/policy.sql @@ -0,0 +1,96 @@ +-- Stores a version and returns the stored row with the publication time and +-- effective time set by the stamp trigger. A taken ID or version number +-- returns no row instead of an error, so a conflict does not abort the +-- surrounding transaction. created_at is never taken from the caller, and a +-- NULL effective_at means "at publication". +-- name: InsertPolicyVersion :one +INSERT INTO policy_versions ( + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256 +) VALUES ( + sqlc.arg(id), + sqlc.arg(policy_key), + sqlc.arg(version), + sqlc.arg(kind), + sqlc.narg(effective_at), + sqlc.arg(author), + sqlc.arg(document), + sqlc.arg(document_sha256) +) +ON CONFLICT DO NOTHING +RETURNING + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at; + +-- name: GetPolicyVersionByID :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE id = sqlc.arg(id); + +-- Among the versions of a family already effective at a time, the newest +-- publication wins. A version scheduled for later therefore never undoes a +-- version published after it. The unique (policy_key, version) index serves +-- the backward scan. +-- name: GetEffectivePolicyVersion :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE + policy_key = sqlc.arg(policy_key) + AND effective_at <= sqlc.arg(at) +ORDER BY version DESC +LIMIT 1; + +-- name: GetLatestPolicyVersion :one +SELECT + id, + policy_key, + version, + kind, + effective_at, + author, + document, + document_sha256, + created_at +FROM policy_versions +WHERE policy_key = sqlc.arg(policy_key) +ORDER BY version DESC +LIMIT 1; + +-- Reports whether a family has any version without reading a document, so a +-- caller that only needs presence never depends on decoding. +-- name: PolicyVersionExists :one +SELECT exists( + SELECT 1 FROM policy_versions + WHERE policy_key = sqlc.arg(policy_key) +) AS present; diff --git a/backend/db/queries/privacy.sql b/backend/db/queries/privacy.sql new file mode 100644 index 0000000..5fa3159 --- /dev/null +++ b/backend/db/queries/privacy.sql @@ -0,0 +1,425 @@ +-- Queries of the candidate visibility settings: the publication of +-- the card, the search status, the hidden organizations, and the history of +-- these settings. Every statement is scoped by the candidate's user_id, and +-- no statement selects another account's row. No statement reads or writes a +-- profile value, a name, or a contact. A candidate with no row is closed, not +-- looking, and hides nobody; no statement creates a row except an explicit +-- act of the candidate. + +-- Reads the candidate-owned settings and hidden count from one statement +-- snapshot. Missing setting rows are restored as the closed/not-looking +-- defaults in the adapter. The account row scopes the result but does not +-- expose private profile values. +-- name: ReadCandidatePrivacySettings :one +SELECT + users.id AS user_id, + candidate_publications.state AS publication_state, + candidate_publications.fields AS publication_fields, + candidate_publications.consent_record_id AS publication_consent_record_id, + candidate_publications.published_at AS publication_published_at, + candidate_publications.closed_at AS publication_closed_at, + candidate_publications.version AS publication_version, + consent_records.revoked_at AS publication_consent_revoked_at, + candidate_search_statuses.status AS search_status, + candidate_search_statuses.confirmed_at AS search_confirmed_at, + candidate_search_statuses.lapses_at AS search_lapses_at, + candidate_search_statuses.policy_version_id AS search_policy_version_id, + candidate_search_statuses.version AS search_version, + ( + SELECT count(*) + FROM candidate_hidden_organizations + WHERE candidate_hidden_organizations.user_id = users.id + ) AS hidden_count +FROM users +LEFT JOIN candidate_publications + ON candidate_publications.user_id = users.id +LEFT JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +LEFT JOIN candidate_search_statuses + ON candidate_search_statuses.user_id = users.id +WHERE users.id = sqlc.arg(user_id); + +-- Reads the publication with the revocation state of the C2 record behind it +-- in one statement, so the stored setting and the ledger come from one +-- snapshot. The effective state is computed from them: published only while +-- consent_revoked_at is NULL. No row means the candidate never published. +-- name: ReadCandidatePublication :one +SELECT + candidate_publications.user_id, + candidate_publications.state, + candidate_publications.fields, + candidate_publications.consent_record_id, + candidate_publications.published_at, + candidate_publications.closed_at, + candidate_publications.version, + candidate_publications.created_at, + candidate_publications.updated_at, + consent_records.revoked_at AS consent_revoked_at +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE candidate_publications.user_id = sqlc.arg(user_id); + +-- Stores the first publication at version 1. No row returns when the account +-- already has a row, so a first publication that lost a race with another +-- one is answered as a version conflict. The foreign key refuses a record +-- that is not a C2 record of this account. +-- name: InsertCandidatePublication :one +INSERT INTO candidate_publications ( + user_id, + state, + fields, + consent_record_id, + published_at, + closed_at, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(state), + sqlc.arg(fields), + sqlc.arg(consent_record_id), + sqlc.arg(published_at), + sqlc.narg(closed_at), + 1, + sqlc.arg(at), + sqlc.arg(at) +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version; + +-- Replaces the publication over the version the caller read and advances the +-- version in the same statement. No row returns for a stale version, which +-- the caller answers as a version conflict. The update time never moves back, +-- as in the profile. +-- name: UpdateCandidatePublication :one +UPDATE candidate_publications +SET + state = sqlc.arg(state), + fields = sqlc.arg(fields), + consent_record_id = sqlc.arg(consent_record_id), + published_at = sqlc.arg(published_at), + closed_at = sqlc.narg(closed_at), + version = candidate_publications.version + 1, + updated_at = greatest(candidate_publications.updated_at, sqlc.arg(at)) +WHERE + candidate_publications.user_id = sqlc.arg(user_id) + AND candidate_publications.version = sqlc.arg(expected_version) +RETURNING user_id, version; + +-- No row means the status was never set, which reads as not looking. The +-- lapse is computed by the caller from lapses_at and its clock and is never +-- written. +-- name: ReadCandidateSearchStatus :one +SELECT + user_id, + status, + confirmed_at, + lapses_at, + policy_version_id, + version, + created_at, + updated_at +FROM candidate_search_statuses +WHERE user_id = sqlc.arg(user_id); + +-- Stores the first status at version 1; no row returns when one exists. +-- name: InsertCandidateSearchStatus :one +INSERT INTO candidate_search_statuses ( + user_id, + status, + confirmed_at, + lapses_at, + policy_version_id, + version, + created_at, + updated_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(status), + sqlc.narg(confirmed_at), + sqlc.narg(lapses_at), + sqlc.narg(policy_version_id), + 1, + sqlc.arg(at), + sqlc.arg(at) +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version; + +-- Replaces the status over the version the caller read. Looking also stores +-- the new confirmation, lapse time, and policy version; not looking clears +-- them. It never names the publication or the hidden organizations. +-- name: UpdateCandidateSearchStatus :one +UPDATE candidate_search_statuses +SET + status = sqlc.arg(status), + confirmed_at = sqlc.narg(confirmed_at), + lapses_at = sqlc.narg(lapses_at), + policy_version_id = sqlc.narg(policy_version_id), + version = candidate_search_statuses.version + 1, + updated_at = greatest(candidate_search_statuses.updated_at, sqlc.arg(at)) +WHERE + candidate_search_statuses.user_id = sqlc.arg(user_id) + AND candidate_search_statuses.version = sqlc.arg(expected_version) +RETURNING user_id, version; + +-- Hides one organization. No row returns when the pair already exists, and +-- the caller reads the existing record with its original time. The foreign key +-- refuses an unknown organization (SQLSTATE 23503); the caller answers it +-- exactly like an organization the candidate cannot see. The trigger refuses +-- the 1001st record (candidate_hidden_organizations_limit). The trigger runs +-- before the conflict check, so the caller reads the existing record first +-- and a repeat at the limit is never refused. +-- name: InsertCandidateHiddenOrganization :one +INSERT INTO candidate_hidden_organizations ( + user_id, + organization_id, + hidden_at +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(organization_id), + sqlc.arg(at) +) +ON CONFLICT (user_id, organization_id) DO NOTHING +RETURNING user_id, organization_id, hidden_at; + +-- Reads one hiding of the candidate with the current name of the +-- organization. +-- name: GetCandidateHiddenOrganization :one +SELECT + candidate_hidden_organizations.organization_id, + organizations.name AS organization_name, + candidate_hidden_organizations.hidden_at +FROM candidate_hidden_organizations +INNER JOIN organizations + ON organizations.id = candidate_hidden_organizations.organization_id +WHERE + candidate_hidden_organizations.user_id = sqlc.arg(user_id) + AND candidate_hidden_organizations.organization_id = sqlc.arg(organization_id); + +-- Lifts one hiding. No row returns when the organization was not hidden, so +-- the caller writes the history event only for a real deletion and answers +-- 204 either way. +-- name: DeleteCandidateHiddenOrganization :one +DELETE FROM candidate_hidden_organizations +WHERE user_id = sqlc.arg(user_id) AND organization_id = sqlc.arg(organization_id) +RETURNING organization_id; + +-- One page of the candidate's hidden organizations, newest first with the +-- organization identifier as the tie-breaker. The page continues after the +-- (hidden_at, organization_id) position of the last record of the previous +-- page. +-- name: ListCandidateHiddenOrganizations :many +SELECT + candidate_hidden_organizations.organization_id, + organizations.name AS organization_name, + candidate_hidden_organizations.hidden_at +FROM candidate_hidden_organizations +INNER JOIN organizations + ON organizations.id = candidate_hidden_organizations.organization_id +WHERE + candidate_hidden_organizations.user_id = sqlc.arg(user_id) + AND ( + sqlc.narg(after_hidden_at)::timestamptz IS NULL + OR ( + candidate_hidden_organizations.hidden_at, + candidate_hidden_organizations.organization_id + ) < ( + sqlc.narg(after_hidden_at)::timestamptz, + sqlc.narg(after_organization_id)::uuid + ) + ) +ORDER BY + candidate_hidden_organizations.hidden_at DESC, + candidate_hidden_organizations.organization_id DESC +LIMIT sqlc.arg(row_limit); + +-- Counts the hiding records of one candidate for the settings read. +-- name: CountCandidateHiddenOrganizations :one +SELECT count(*) AS total +FROM candidate_hidden_organizations +WHERE user_id = sqlc.arg(user_id); + +-- Appends one event to the settings history. The row holds identifiers, card +-- field codes, and times, never a name; the caller +-- writes it in the transaction of the change it records. +-- name: InsertCandidatePrivacyEvent :exec +INSERT INTO candidate_privacy_events ( + id, + user_id, + kind, + occurred_at, + fields, + consent_record_id, + organization_id +) VALUES ( + sqlc.arg(id), + sqlc.arg(user_id), + sqlc.arg(kind), + sqlc.arg(occurred_at), + sqlc.narg(fields), + sqlc.narg(consent_record_id), + sqlc.narg(organization_id) +); + +-- One page of the candidate's settings history, newest first with the event +-- identifier as the tie-breaker. The organization name is resolved here, at +-- read time, and is the current name. The page continues after the +-- (occurred_at, id) position of the last event of the previous page. +-- name: ListCandidatePrivacyEvents :many +SELECT + candidate_privacy_events.id, + candidate_privacy_events.kind, + candidate_privacy_events.occurred_at, + candidate_privacy_events.fields, + candidate_privacy_events.consent_record_id, + candidate_privacy_events.organization_id, + organizations.name AS organization_name +FROM candidate_privacy_events +LEFT JOIN organizations + ON organizations.id = candidate_privacy_events.organization_id +WHERE + candidate_privacy_events.user_id = sqlc.arg(user_id) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (candidate_privacy_events.occurred_at, candidate_privacy_events.id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY + candidate_privacy_events.occurred_at DESC, + candidate_privacy_events.id DESC +LIMIT sqlc.arg(row_limit); + +-- Takes the candidate's current unrevoked C2 record for a publication and +-- keeps it locked until the transaction ends. The share lock conflicts with +-- the revocation stamp (an UPDATE of the row), so a revocation either commits +-- before this statement, which then returns no row and the publication is +-- refused, or waits until the publication transaction commits and closes the +-- card right after. The caller must run it in the transaction that writes the +-- publication and must re-read the effective state (ReadCandidatePublication) +-- in that transaction to build its response. +-- name: LockCurrentC2Record :one +SELECT id +FROM consent_records +WHERE + subject_id = sqlc.arg(subject_id) + AND purpose = 'c2' + AND revoked_at IS NULL +ORDER BY granted_at DESC, id DESC +LIMIT 1 +FOR SHARE; + +-- Locks the candidate's published row only when it refers to a C2 record +-- revoked by this transaction. The setting remains linked to that immutable +-- record; ReadCandidatePublication computes the effective closed state and +-- keeps the consent-revoked reason after later grants. The returned time is +-- the effective close time used by the privacy history event. +-- name: LockCandidatePublicationForConsentRevocation :one +SELECT greatest(candidate_publications.published_at, consent_records.revoked_at)::timestamptz AS closed_at +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE + candidate_publications.user_id = sqlc.arg(user_id) + AND candidate_publications.state = 'published' + AND consent_records.id = ANY(sqlc.arg(consent_record_ids)::uuid []) + AND consent_records.subject_id = candidate_publications.user_id + AND consent_records.purpose = 'c2' + AND consent_records.revoked_at IS NOT NULL +FOR UPDATE OF candidate_publications; + +-- The organization-facing read of a candidate's publication: the effective +-- view (published and backed by an unrevoked C2) and no hiding of the reading +-- organization. No row means the organization reads nothing, whichever of +-- the reasons applies, so it cannot tell a hidden candidate from an +-- unpublished one. Every organization-facing read of a publication starts +-- from this shape. +-- name: ReadPublicationVisibleToOrganization :one +SELECT + effective.user_id, + effective.fields, + effective.published_at +FROM candidate_effective_publications AS effective +WHERE + effective.user_id = sqlc.arg(user_id) + AND NOT exists( + SELECT 1 FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = effective.user_id + AND hidden.organization_id = sqlc.arg(organization_id) + ); + +-- Records a successfully authorized view after visibility and quota checks. +-- The audit contains only identities, the access kind, published field codes, +-- and time; it never receives the projection content, ranking, or filters. +-- name: InsertCandidateCardAccessEvent :exec +INSERT INTO candidate_card_access_events ( + id, + candidate_id, + organization_id, + actor_id, + kind, + field_codes, + occurred_at +) VALUES ( + sqlc.arg(id), + sqlc.arg(candidate_id), + sqlc.arg(organization_id), + sqlc.narg(actor_id), + sqlc.arg(kind), + sqlc.arg(field_codes), + sqlc.arg(occurred_at) +); + +-- Lists only the current candidate's own access history. It deliberately +-- omits the employee, requested card fields, and search context. The privacy +-- read adapter resolves an organization name only through this recorded +-- access relation, which is already visible to the candidate. +-- name: ListCandidateCardAccessEvents :many +SELECT + candidate_card_access_events.id, + candidate_card_access_events.candidate_id, + candidate_card_access_events.organization_id, + candidate_card_access_events.actor_id, + candidate_card_access_events.kind, + candidate_card_access_events.field_codes, + candidate_card_access_events.occurred_at, + organizations.name AS organization_name +FROM candidate_card_access_events +INNER JOIN organizations + ON organizations.id = candidate_card_access_events.organization_id +WHERE + candidate_card_access_events.candidate_id = sqlc.arg(candidate_id) + AND ( + sqlc.narg(after_occurred_at)::timestamptz IS NULL + OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < ( + sqlc.narg(after_occurred_at)::timestamptz, + sqlc.narg(after_id)::uuid + ) + ) +ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC +LIMIT sqlc.arg(row_limit); + +-- The candidate may name an organization in privacy settings only if that +-- organization already appears in their own access history or is already +-- hidden. Unknown and unseen organizations produce the same no-row result. +-- name: CandidateCanSeeOrganization :one +SELECT organizations.id, organizations.name +FROM organizations +WHERE organizations.id = sqlc.arg(organization_id) + AND ( + EXISTS ( + SELECT 1 FROM candidate_card_access_events + WHERE candidate_card_access_events.candidate_id = sqlc.arg(user_id) + AND candidate_card_access_events.organization_id = organizations.id + ) + OR EXISTS ( + SELECT 1 FROM candidate_hidden_organizations + WHERE candidate_hidden_organizations.user_id = sqlc.arg(user_id) + AND candidate_hidden_organizations.organization_id = organizations.id + ) + ); diff --git a/backend/db/queries/privacy_cohort.sql b/backend/db/queries/privacy_cohort.sql new file mode 100644 index 0000000..e0d5d21 --- /dev/null +++ b/backend/db/queries/privacy_cohort.sql @@ -0,0 +1,235 @@ +-- Organization-facing anonymous candidate projection inputs. The calling +-- usecase has already authorized the active organization membership. This +-- single statement snapshot filters both revoked/unpublished C2 states and +-- candidates hidden from this organization before any profile value is read. +-- The projection reads only stack, declared role, experience dates, and +-- projects with the keys of their verified repositories. It deliberately +-- excludes names, contacts, salary, location, soft skills, employer names, +-- summaries, and imported excerpts; the repository address of a project stays +-- in the private input and never reaches the card. The only assessment data +-- is the current category (specialization and grade) of the separate current +-- category table; it carries no attempt, score, review, policy, or history. +-- name: ListVisibleCandidateViewSources :many +SELECT + effective.user_id, + effective.fields, + claim.kind, + claim.ordinal, + CASE + WHEN claim.kind = 'experience' THEN jsonb_build_object( + 'employer_name', NULL::text, + 'specialization', claim.value ->> 'specialization', + 'started_on', claim.value ->> 'started_on', + 'ended_on', claim.value -> 'ended_on', + 'summary', NULL::text + ) + ELSE claim.value + END AS safe_value, + claim.status, + claim.origin, + claim.trust_level, + claim.extraction_version, + claim.confirmed_at, + COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats, + COALESCE( + ( + SELECT jsonb_agg( + jsonb_build_object( + 'first_index', overlap.first_index, + 'second_index', overlap.second_index, + 'first_period', jsonb_build_object( + 'started_on', overlap.first_started_on, + 'ended_on', overlap.first_ended_on + ), + 'second_period', jsonb_build_object( + 'started_on', overlap.second_started_on, + 'ended_on', overlap.second_ended_on + ) + ) ORDER BY overlap.first_index, overlap.second_index + )::text + FROM candidate_profile_overlap_confirmations AS overlap + WHERE overlap.user_id = effective.user_id + ), + '[]'::text + ) AS parallel_period_acknowledgements, + COALESCE( + ( + SELECT jsonb_agg( + jsonb_build_object( + 'specialization', category.specialization, + 'grade', category.grade, + 'source', category.source + ) + ORDER BY category.specialization + )::text + FROM candidate_assessment_categories AS category + WHERE category.candidate_id = effective.user_id + ), + '[]'::text + ) AS confirmed_categories, + COALESCE( + ( + SELECT array_agg(repository.repository_key ORDER BY repository.repository_key) + FROM candidate_project_repositories AS repository + WHERE + repository.candidate_id = effective.user_id + AND repository.state = 'verified' + ), + '{}'::text [] + )::text [] AS verified_repositories +FROM candidate_effective_publications AS effective +LEFT JOIN candidate_profile_claims AS claim + ON claim.user_id = effective.user_id + AND claim.kind IN ('stack', 'role', 'experience', 'project') +LEFT JOIN candidate_questionnaires AS questionnaire + ON questionnaire.user_id = effective.user_id +WHERE NOT EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE hidden.user_id = effective.user_id + AND hidden.organization_id = sqlc.arg(organization_id) +) +ORDER BY effective.user_id, claim.kind, claim.ordinal; + +-- Lock the account before an organization checks candidate visibility. The +-- hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so +-- a hide either commits before the later visibility recheck or waits for the +-- read transaction to finish. +-- name: LockCandidateAccountForView :one +SELECT users.id +FROM users +WHERE users.id = sqlc.arg(candidate_id) +FOR SHARE; + +-- Lock the current C2 before locking the publication. C2 revocation updates +-- this row before it locks the publication, so preserving this order avoids +-- a lock inversion and makes the current consent stable through the read. +-- name: LockCurrentC2ForView :one +SELECT consent_records.id +FROM consent_records +WHERE + consent_records.subject_id = sqlc.arg(candidate_id) + AND consent_records.purpose = 'c2' + AND consent_records.revoked_at IS NULL +ORDER BY consent_records.granted_at DESC, consent_records.id DESC +LIMIT 1 +FOR SHARE; + +-- Lock and recheck one candidate's exact current publication only after the +-- active C2 row is share-locked. No row includes unpublished, revoked, stale +-- publication, and organization-hidden states. +-- name: LockVisiblePublicationForView :one +SELECT candidate_publications.user_id +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE + candidate_publications.user_id = sqlc.arg(candidate_id) + AND candidate_publications.state = 'published' + AND candidate_publications.consent_record_id = sqlc.arg(consent_record_id) + AND consent_records.subject_id = candidate_publications.user_id + AND consent_records.purpose = 'c2' + AND consent_records.revoked_at IS NULL + AND NOT EXISTS ( + SELECT 1 + FROM candidate_hidden_organizations AS hidden + WHERE + hidden.user_id = candidate_publications.user_id + AND hidden.organization_id = sqlc.arg(organization_id) + ) +FOR SHARE OF candidate_publications, consent_records; + +-- Lock a candidate's current publication for the private preview. This has +-- no organization context and never enters the employer read quota or audit. +-- name: LockPublicationForCandidatePreview :one +SELECT candidate_publications.user_id +FROM candidate_publications +INNER JOIN consent_records + ON consent_records.id = candidate_publications.consent_record_id +WHERE + candidate_publications.user_id = sqlc.arg(candidate_id) + AND candidate_publications.state = 'published' + AND consent_records.subject_id = candidate_publications.user_id + AND consent_records.purpose = 'c2' + AND consent_records.revoked_at IS NULL +FOR SHARE OF candidate_publications, consent_records; + +-- Read the candidate's current private projection inputs after the caller +-- locks its active C2 and publication. It selects only fields allowed in the +-- anonymous-card projection and is never used for employer visibility. +-- name: ReadCandidateViewSourceForPreview :many +SELECT + effective.user_id, + effective.fields, + claim.kind, + claim.ordinal, + CASE + WHEN claim.kind = 'experience' THEN jsonb_build_object( + 'employer_name', NULL::text, + 'specialization', claim.value ->> 'specialization', + 'started_on', claim.value ->> 'started_on', + 'ended_on', claim.value -> 'ended_on', + 'summary', NULL::text + ) + ELSE claim.value + END AS safe_value, + claim.status, + claim.origin, + claim.trust_level, + claim.extraction_version, + claim.confirmed_at, + COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats, + COALESCE( + ( + SELECT jsonb_agg( + jsonb_build_object( + 'first_index', overlap.first_index, + 'second_index', overlap.second_index, + 'first_period', jsonb_build_object( + 'started_on', overlap.first_started_on, + 'ended_on', overlap.first_ended_on + ), + 'second_period', jsonb_build_object( + 'started_on', overlap.second_started_on, + 'ended_on', overlap.second_ended_on + ) + ) ORDER BY overlap.first_index, overlap.second_index + )::text + FROM candidate_profile_overlap_confirmations AS overlap + WHERE overlap.user_id = effective.user_id + ), + '[]'::text + ) AS parallel_period_acknowledgements, + COALESCE( + ( + SELECT jsonb_agg( + jsonb_build_object( + 'specialization', category.specialization, + 'grade', category.grade, + 'source', category.source + ) + ORDER BY category.specialization + )::text + FROM candidate_assessment_categories AS category + WHERE category.candidate_id = effective.user_id + ), + '[]'::text + ) AS confirmed_categories, + COALESCE( + ( + SELECT array_agg(repository.repository_key ORDER BY repository.repository_key) + FROM candidate_project_repositories AS repository + WHERE + repository.candidate_id = effective.user_id + AND repository.state = 'verified' + ), + '{}'::text [] + )::text [] AS verified_repositories +FROM candidate_effective_publications AS effective +LEFT JOIN candidate_profile_claims AS claim + ON claim.user_id = effective.user_id + AND claim.kind IN ('stack', 'role', 'experience', 'project') +LEFT JOIN candidate_questionnaires AS questionnaire + ON questionnaire.user_id = effective.user_id +WHERE effective.user_id = sqlc.arg(candidate_id) +ORDER BY effective.user_id, claim.kind, claim.ordinal; diff --git a/backend/db/queries/project_repositories.sql b/backend/db/queries/project_repositories.sql new file mode 100644 index 0000000..29cd48a --- /dev/null +++ b/backend/db/queries/project_repositories.sql @@ -0,0 +1,62 @@ +-- Server checks of the GitHub repositories that candidate projects link. +-- Every statement is scoped by the candidate. + +-- name: ListCandidateProjectRepositories :many +SELECT + candidate_id, repository_key, state, github_id, description, topics, + languages, readme_excerpt, repository_etag, readme_etag, failure_class, + checked_at, requested_at, created_at, updated_at +FROM candidate_project_repositories +WHERE candidate_id = sqlc.arg(candidate_id) +ORDER BY repository_key; + +-- name: GetCandidateProjectRepositoryForUpdate :one +SELECT + candidate_id, repository_key, state, github_id, description, topics, + languages, readme_excerpt, repository_etag, readme_etag, failure_class, + checked_at, requested_at, created_at, updated_at +FROM candidate_project_repositories +WHERE candidate_id = sqlc.arg(candidate_id) AND repository_key = sqlc.arg(repository_key) +FOR UPDATE; + +-- A new repository starts pending; a known one only records the request. +-- name: RequestCandidateProjectRepositoryCheck :exec +INSERT INTO candidate_project_repositories ( + candidate_id, repository_key, state, requested_at, created_at, updated_at +) VALUES ( + sqlc.arg(candidate_id), sqlc.arg(repository_key), 'pending', sqlc.arg(requested_at), + sqlc.arg(requested_at), sqlc.arg(requested_at) +) +ON CONFLICT (candidate_id, repository_key) DO UPDATE +SET + requested_at = excluded.requested_at, + updated_at = GREATEST(candidate_project_repositories.updated_at, excluded.updated_at); + +-- name: SaveCandidateProjectRepositoryCheck :exec +UPDATE candidate_project_repositories +SET + state = sqlc.arg(state), + github_id = sqlc.narg(github_id), + description = sqlc.narg(description), + topics = sqlc.arg(topics), + languages = sqlc.arg(languages), + readme_excerpt = sqlc.narg(readme_excerpt), + repository_etag = sqlc.narg(repository_etag), + readme_etag = sqlc.narg(readme_etag), + failure_class = sqlc.narg(failure_class), + checked_at = sqlc.arg(checked_at), + updated_at = GREATEST(updated_at, sqlc.arg(checked_at)) +WHERE candidate_id = sqlc.arg(candidate_id) AND repository_key = sqlc.arg(repository_key); + +-- Removes the checks of repositories that no project links any more. +-- name: DeleteUnlinkedCandidateProjectRepositories :exec +DELETE FROM candidate_project_repositories +WHERE + candidate_id = sqlc.arg(candidate_id) + AND NOT (repository_key = ANY(sqlc.arg(linked_keys)::text [])); + +-- The latest check request of a candidate, for the per-candidate limit. +-- name: GetLatestRepositoryCheckRequest :one +SELECT MAX(requested_at)::timestamptz AS requested_at +FROM candidate_project_repositories +WHERE candidate_id = sqlc.arg(candidate_id); diff --git a/backend/db/queries/questionnaire.sql b/backend/db/queries/questionnaire.sql new file mode 100644 index 0000000..82a420d --- /dev/null +++ b/backend/db/queries/questionnaire.sql @@ -0,0 +1,181 @@ +-- Creates the first saved questionnaire. A missing row is version zero; +-- concurrent first saves race on the primary key and exactly one returns a row. +-- name: InsertCandidateQuestionnaire :one +INSERT INTO candidate_questionnaires ( + user_id, + version, + work_formats, + created_at, + updated_at +) VALUES ( + sqlc.arg(user_id), + 1, + sqlc.arg(work_formats), + sqlc.arg(at)::timestamptz, + sqlc.arg(at)::timestamptz +) +ON CONFLICT (user_id) DO NOTHING +RETURNING user_id, version, work_formats, created_at, updated_at; + +-- Advances an existing questionnaire only at the version read by the caller. +-- The row lock serializes saves for one user; a stale writer returns no row. +-- name: AdvanceCandidateQuestionnaireVersion :one +UPDATE candidate_questionnaires +SET + version = candidate_questionnaires.version + 1, + work_formats = sqlc.arg(work_formats), + updated_at = GREATEST(candidate_questionnaires.updated_at, sqlc.arg(at)::timestamptz) +WHERE + candidate_questionnaires.user_id = sqlc.arg(user_id) + AND candidate_questionnaires.version = sqlc.arg(expected_version) +RETURNING user_id, version, work_formats, created_at, updated_at; + +-- Reads the aggregate and its ordered specializations in one statement so a +-- response never pairs a version with another version's answers. +-- name: ReadCandidateQuestionnaire :one +SELECT + questionnaire.user_id, + questionnaire.version, + questionnaire.work_formats, + questionnaire.created_at, + questionnaire.updated_at, + COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'ordinal', specialization.ordinal, + 'specialization', specialization.specialization, + 'self_assessed_grade', specialization.self_assessed_grade, + 'task_languages', specialization.task_languages, + 'stack', specialization.stack, + 'commercial_months', specialization.commercial_months, + 'academic_months', specialization.academic_months + ) ORDER BY specialization.ordinal + ) + FROM candidate_questionnaire_specializations AS specialization + WHERE specialization.user_id = questionnaire.user_id + ), '[]'::jsonb)::text AS specializations +FROM candidate_questionnaires AS questionnaire +WHERE questionnaire.user_id = sqlc.arg(user_id); + +-- Replaces all specialization answers after the version row advanced in the +-- same transaction. +-- name: DeleteCandidateQuestionnaireSpecializations :exec +DELETE FROM candidate_questionnaire_specializations +WHERE user_id = sqlc.arg(user_id); + +-- name: InsertCandidateQuestionnaireSpecialization :exec +INSERT INTO candidate_questionnaire_specializations ( + user_id, + ordinal, + specialization, + self_assessed_grade, + task_languages, + stack, + commercial_months, + academic_months +) VALUES ( + sqlc.arg(user_id), + sqlc.arg(ordinal), + sqlc.arg(specialization), + sqlc.arg(self_assessed_grade), + sqlc.arg(task_languages), + sqlc.arg(stack), + sqlc.narg(commercial_months), + sqlc.narg(academic_months) +); + +-- Stores an explicit mapping against a newly-created immutable opening. The +-- insert trigger checks the opening, declared reviewer, current policy, and +-- live coverage; the adapter supplies the fingerprint of the published set. +-- name: InsertAssessmentCategoryCatalogBinding :exec +INSERT INTO assessment_category_catalog_bindings ( + opening_id, + specialization, + grade, + task_languages, + published_manifest_sha256, + reviewed_by, + reviewed_at +) VALUES ( + sqlc.arg(opening_id), + sqlc.arg(specialization), + sqlc.arg(grade), + sqlc.arg(task_languages), + sqlc.arg(published_manifest_sha256), + sqlc.arg(reviewed_by), + clock_timestamp() +); + +-- Lists the exact published bank manifest while the category advisory lock is +-- held by OpenCategory. Published families have passed the independent-review +-- constraint before this read. +-- name: ReadPublishedAssessmentCategoryManifest :many +SELECT family_key, version, content_sha256 +FROM assessment_families +WHERE category = sqlc.arg(category) AND lifecycle = 'published' +ORDER BY family_key, version; + +-- Produces current catalog availability in one PostgreSQL statement snapshot. +-- The adapter compares the ordered live family manifest with the pinned +-- fingerprint; stale bindings are omitted fail-closed. +-- name: ListCurrentSpecializationAvailability :many +WITH current_policy AS ( + SELECT id + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= statement_timestamp() + ORDER BY version DESC + LIMIT 1 +), current_openings AS ( + SELECT DISTINCT ON (category) + id, + category, + policy_version_id, + required_families, + opened_at + FROM assessment_category_openings + ORDER BY category, opened_at DESC, id DESC +) +SELECT + opening.id AS opening_id, + opening.category, + opening.policy_version_id, + opening.required_families, + COALESCE(( + SELECT count(DISTINCT family.family_key)::integer + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), 0)::integer AS published_count, + policy.id AS effective_policy_id, + binding.specialization, + binding.grade, + binding.task_languages, + binding.published_manifest_sha256, + COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'family_key', family.family_key, + 'version', family.version, + 'content_sha256', encode(family.content_sha256, 'hex') + ) ORDER BY family.family_key, family.version + ) + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), '[]'::jsonb)::text AS published_manifest +FROM current_openings AS opening +JOIN assessment_category_catalog_bindings AS binding + ON binding.opening_id = opening.id +LEFT JOIN current_policy AS policy ON true +ORDER BY opening.category; + +-- A questionnaire save advances onboarding only from its own step. +-- name: AdvanceCandidateOnboardingAfterQuestionnaire :exec +UPDATE users +SET + onboarding_step = 'candidate_assessment', + version = users.version + 1, + updated_at = GREATEST(users.updated_at, sqlc.arg(at)::timestamptz) +WHERE + users.id = sqlc.arg(user_id) + AND users.scenario = 'candidate' + AND users.email_verified_at IS NOT NULL + AND users.onboarding_step = 'candidate_questionnaire'; diff --git a/backend/db/queries/scheduled_job.sql b/backend/db/queries/scheduled_job.sql new file mode 100644 index 0000000..76c290b --- /dev/null +++ b/backend/db/queries/scheduled_job.sql @@ -0,0 +1,288 @@ +-- Lock order. A job handler runs while its transaction holds the row lock +-- of the job, and may then lock product rows. A business transaction that +-- cancels a job should cancel it before it locks the product rows the +-- handler touches, so both take the locks in the same order. + +-- Schedules a job in the caller's transaction. The first schedule of a +-- (kind, dedup_key) wins: a repeat, also after the job finished or was +-- canceled, inserts nothing and reports 0 rows, so a repeated command never +-- moves a deadline. A concurrent insert of the same key waits for the first +-- transaction and then inserts nothing, or inserts after its rollback. +-- name: InsertScheduledJob :execrows +INSERT INTO scheduled_jobs ( + kind, + dedup_key, + payload, + due_at, + available_at, + status, + attempts, + max_attempts +) VALUES ( + sqlc.arg(kind), + sqlc.arg(dedup_key), + sqlc.arg(payload), + sqlc.arg(due_at), + sqlc.arg(due_at), + 'pending', + 0, + sqlc.narg(max_attempts) +) +ON CONFLICT (kind, dedup_key) DO NOTHING; + +-- Cancels a job that has not finished. A job whose handler transaction is +-- in progress holds its row lock, so the statement waits for it: after the +-- handler committed the job is done and nothing is canceled; otherwise the +-- worker finds its lease gone and does not run or complete the job. +-- name: CancelScheduledJob :execrows +UPDATE scheduled_jobs +SET + status = 'cancelled', + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = clock_timestamp() +WHERE + kind = sqlc.arg(kind) + AND dedup_key = sqlc.arg(dedup_key) + AND status IN ('pending', 'failed', 'running'); + +-- Claims up to batch_limit jobs of the listed kinds in one statement: jobs +-- whose available_at has passed, and running jobs whose lease expired +-- because their worker stopped without finishing them. Rows that another +-- worker locks are skipped without waiting. Each claimed job gets the lease +-- of lease_owner and one more attempt, except a job whose expired attempt +-- never started its handler: that attempt is reused, so a worker that was +-- busy with other jobs of its batch costs the job nothing. A job whose +-- started attempt was abandoned on its last allowed attempt becomes dead +-- with lease_expired instead, so a job that keeps crashing its worker +-- stops. now is the application clock. +-- +-- The kind filter applies after the index on available_at; when many waiting +-- jobs belong to kinds without a handler in the claiming process, an index +-- on (kind, available_at, id) is the next step. +-- name: ClaimScheduledJobs :many +WITH candidates AS ( + SELECT + candidate.id, + ( + candidate.status = 'running' + AND candidate.started_at IS NULL + ) AS unstarted, + ( + candidate.status = 'running' + AND candidate.started_at IS NOT NULL + AND candidate.attempts >= coalesce( + candidate.max_attempts, + sqlc.arg(default_max_attempts)::integer + ) + ) AS exhausted + FROM scheduled_jobs AS candidate + WHERE + candidate.kind = any(sqlc.arg(kinds)::text []) + AND ( + ( + candidate.status IN ('pending', 'failed') + AND candidate.available_at <= sqlc.arg(now)::timestamptz + ) + OR ( + candidate.status = 'running' + AND candidate.lease_expires_at <= sqlc.arg(now)::timestamptz + ) + ) + ORDER BY candidate.available_at, candidate.id + LIMIT sqlc.arg(batch_limit) + FOR UPDATE SKIP LOCKED +) + +UPDATE scheduled_jobs AS job +SET + status = CASE WHEN candidates.exhausted THEN 'dead' ELSE 'running' END, + attempts = CASE + WHEN candidates.exhausted OR candidates.unstarted THEN job.attempts + ELSE job.attempts + 1 + END, + lease_owner = CASE + WHEN candidates.exhausted THEN NULL ELSE sqlc.arg(lease_owner)::uuid + END, + lease_expires_at = CASE + WHEN + candidates.exhausted + THEN NULL + ELSE sqlc.arg(lease_expires_at)::timestamptz + END, + started_at = NULL, + last_error_class = CASE + WHEN + job.status = 'running' AND NOT candidates.unstarted + THEN 'lease_expired' + ELSE job.last_error_class + END, + updated_at = clock_timestamp() +FROM candidates +WHERE job.id = candidates.id +RETURNING + job.id, + job.kind, + job.dedup_key, + job.payload, + job.due_at, + job.attempts, + coalesce( + job.max_attempts, sqlc.arg(default_max_attempts)::integer + )::integer AS max_attempts, + candidates.exhausted; + +-- Starts a claimed attempt right before its handler transaction: it renews +-- the lease from now and records the start, committed on its own. It +-- changes nothing when the lease already expired by now or no longer +-- belongs to this attempt, so a job whose turn in the batch came too late is +-- never started on a lease that another worker may take over. now is the +-- application clock. +-- name: StartScheduledJob :execrows +UPDATE scheduled_jobs +SET + lease_expires_at = sqlc.arg(lease_expires_at), + started_at = sqlc.arg(now), + updated_at = clock_timestamp() +WHERE + id = sqlc.arg(id) + AND status = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND attempts = sqlc.arg(attempt) + AND lease_expires_at > sqlc.arg(now); + +-- Locks a claimed job for its handler transaction and checks that the lease +-- still belongs to this attempt. It returns no row when the job was +-- canceled, or reclaimed after the lease expired. While the lock is held, +-- other workers skip the row, so the handler never runs twice at once. +-- name: LockClaimedScheduledJob :one +SELECT job.id +FROM scheduled_jobs AS job +WHERE + job.id = sqlc.arg(id) + AND job.status = 'running' + AND job.lease_owner = sqlc.arg(lease_owner) + AND job.attempts = sqlc.arg(attempt) +FOR UPDATE; + +-- Completes a job in the transaction of its handler effect. The guard is +-- the lease owner and the attempt, so a worker that lost its lease cannot +-- complete the job. +-- name: CompleteScheduledJob :execrows +UPDATE scheduled_jobs +SET + status = 'done', + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = clock_timestamp() +WHERE + id = sqlc.arg(id) + AND status = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND attempts = sqlc.arg(attempt); + +-- Records a failed attempt after its handler transaction rolled back: the +-- job waits for its retry at retry_at (status failed) or is dead, with a +-- NULL retry_at. due_at keeps the deadline. The same guard as the +-- completion applies. +-- name: FailScheduledJob :execrows +UPDATE scheduled_jobs +SET + status = sqlc.arg(status), + available_at = coalesce(sqlc.narg(retry_at), available_at), + last_error_class = sqlc.arg(error_class), + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = clock_timestamp() +WHERE + id = sqlc.arg(id) + AND status = 'running' + AND lease_owner = sqlc.arg(lease_owner) + AND attempts = sqlc.arg(attempt); + +-- Returns claimed jobs that did not finish, at shutdown or after a database +-- failure outside the handler, so another worker can run them at once +-- instead of after the lease expires. The attempt is not counted, because +-- the job did not cause the failure. The same guard as the completion +-- applies, one (id, attempt) pair per job. It returns the IDs it released. +-- name: ReleaseScheduledJobs :many +UPDATE scheduled_jobs AS job +SET + status = CASE + WHEN job.last_error_class IS NULL THEN 'pending' ELSE 'failed' + END, + attempts = job.attempts - 1, + lease_owner = NULL, + lease_expires_at = NULL, + started_at = NULL, + updated_at = clock_timestamp() +FROM ( + -- Set-returning functions in one select list advance together, so the + -- arrays pair up by position. The two-argument unnest(ids, attempts) + -- would say the same, but the sqlc analyzer cannot type it, and + -- sqlfluff cannot parse ROWS FROM. + SELECT + unnest(sqlc.arg(ids)::bigint []) AS id, + unnest(sqlc.arg(attempts)::integer []) AS attempt +) AS released +WHERE + job.id = released.id + AND job.attempts = released.attempt + AND job.status = 'running' + AND job.lease_owner = sqlc.arg(lease_owner) +RETURNING job.id; + +-- Reads the status of a job whose completion found it changed, inside +-- the handler transaction that holds its row lock: only that transaction +-- can have changed it, for example by canceling its own job. +-- name: GetScheduledJobStatus :one +SELECT job.status +FROM scheduled_jobs AS job +WHERE job.id = sqlc.arg(id); + +-- Reads the backlog for metrics without locking: jobs that a worker may +-- claim at now, how long the earliest of them has waited, and the dead +-- jobs. The +-- partial indexes keep the cost proportional to those rows. now is the +-- application clock. +-- name: GetScheduledJobBacklog :one +SELECT + ( + SELECT count(*) + FROM scheduled_jobs AS due + WHERE + due.status IN ('pending', 'failed') + AND due.available_at <= sqlc.arg(now)::timestamptz + )::bigint AS due_jobs, + coalesce(( + SELECT + extract(EPOCH FROM sqlc.arg(now)::timestamptz - oldest.available_at) + FROM scheduled_jobs AS oldest + WHERE + oldest.status IN ('pending', 'failed') + AND oldest.available_at <= sqlc.arg(now)::timestamptz + ORDER BY oldest.available_at + LIMIT 1 + ), 0)::float8 AS oldest_due_age_seconds, + ( + SELECT count(*) + FROM scheduled_jobs AS dead + WHERE dead.status = 'dead' + )::bigint AS dead_jobs; + +-- Bounds a handler transaction on the server, local to the transaction. +-- statement_timeout stops a slow statement; idle_in_transaction_session_timeout +-- ends the session of a worker that froze or lost the network inside the +-- handler, which releases the job row lock so the job can be reclaimed once +-- its lease expires. +-- name: SetScheduledJobTransactionTimeouts :exec +SELECT + set_config('statement_timeout', sqlc.arg(statement_timeout_ms)::text, true), + set_config( + 'idle_in_transaction_session_timeout', + sqlc.arg(idle_timeout_ms)::text, + true + ); diff --git a/backend/db/queries/semantic.sql b/backend/db/queries/semantic.sql new file mode 100644 index 0000000..1055f2b --- /dev/null +++ b/backend/db/queries/semantic.sql @@ -0,0 +1,110 @@ +-- Stored embedding vectors. A candidate keeps one set of rows for a model: +-- the job deletes every other row of the candidate and model before it +-- inserts the new set, in one transaction. A need keeps the rows of its +-- latest computed requirements snapshot the same way. + +-- name: DeleteSemanticVectorsOfModel :exec +DELETE FROM semantic_vectors +WHERE + subject_kind = sqlc.arg(subject_kind) + AND subject_id = sqlc.arg(subject_id) + AND model_id = sqlc.arg(model_id) + AND model_revision = sqlc.arg(model_revision) + AND prompt_version = sqlc.arg(prompt_version); + +-- Removes every vector of a subject, of any model: a closed card or a need +-- without requirements keeps no derived data. +-- name: DeleteSemanticVectorsOfSubject :exec +DELETE FROM semantic_vectors +WHERE subject_kind = sqlc.arg(subject_kind) AND subject_id = sqlc.arg(subject_id); + +-- name: InsertSemanticVector :exec +INSERT INTO semantic_vectors ( + subject_kind, subject_id, candidate_id, need_id, model_id, model_revision, + prompt_version, item_key, content_sha256, label_sha256, dimension, vector, + computed_at +) VALUES ( + sqlc.arg(subject_kind), sqlc.arg(subject_id), sqlc.narg(candidate_id), + sqlc.narg(need_id), sqlc.arg(model_id), sqlc.arg(model_revision), + sqlc.arg(prompt_version), sqlc.arg(item_key), sqlc.arg(content_sha256), + sqlc.narg(label_sha256), sqlc.arg(dimension), sqlc.arg(vector), + sqlc.arg(computed_at) +); + +-- The digests of the stored rows of a subject and model, for the job that +-- decides whether anything changed. +-- name: ListSemanticVectorDigests :many +SELECT item_key, content_sha256 +FROM semantic_vectors +WHERE + subject_kind = sqlc.arg(subject_kind) + AND subject_id = sqlc.arg(subject_id) + AND model_id = sqlc.arg(model_id) + AND model_revision = sqlc.arg(model_revision) + AND prompt_version = sqlc.arg(prompt_version) +ORDER BY item_key, content_sha256; + +-- The whole-view vectors of the candidates of one search. +-- name: ListCandidateWholeVectors :many +SELECT candidate_id, dimension, vector +FROM semantic_vectors +WHERE + subject_kind = 'candidate' + AND item_key = 'whole' + AND model_id = sqlc.arg(model_id) + AND model_revision = sqlc.arg(model_revision) + AND prompt_version = sqlc.arg(prompt_version) + AND candidate_id = ANY(sqlc.arg(candidate_ids)::uuid []) +ORDER BY candidate_id; + +-- The item vectors of the candidates that a search returns, at most a few +-- dozen candidates. +-- name: ListCandidateItemVectors :many +SELECT candidate_id, item_key, label_sha256, dimension, vector +FROM semantic_vectors +WHERE + subject_kind = 'candidate' + AND item_key <> 'whole' + AND model_id = sqlc.arg(model_id) + AND model_revision = sqlc.arg(model_revision) + AND prompt_version = sqlc.arg(prompt_version) + AND candidate_id = ANY(sqlc.arg(candidate_ids)::uuid []) +ORDER BY candidate_id, item_key; + +-- The vectors of a need whose texts match the given digests of the +-- requirements snapshot that the search renders. +-- name: ListNeedVectors :many +SELECT item_key, content_sha256, dimension, vector +FROM semantic_vectors +WHERE + subject_kind = 'need' + AND need_id = sqlc.arg(need_id) + AND model_id = sqlc.arg(model_id) + AND model_revision = sqlc.arg(model_revision) + AND prompt_version = sqlc.arg(prompt_version) + AND content_sha256 = ANY(sqlc.arg(content_digests)::bytea []) +ORDER BY item_key; + +-- Candidates with a saved profile for the backfill, in identifier order +-- after a cursor. The job of a candidate who is not published removes the +-- stored vectors, so a backfill also cleans up after a closed card. +-- name: ListProfileCandidatesAfter :many +SELECT profiles.user_id +FROM candidate_profiles AS profiles +WHERE profiles.user_id > sqlc.arg(after_id) +ORDER BY profiles.user_id +LIMIT sqlc.arg(page_size); + +-- Needs and their current requirements snapshot for the backfill. +-- name: ListNeedsAfter :many +SELECT id, organization_id, requirements_version +FROM organization_needs +WHERE id > sqlc.arg(after_id) +ORDER BY id +LIMIT sqlc.arg(page_size); + +-- Serializes the vector jobs of one subject: a job takes this lock before it +-- reads the subject, so the job that runs last also read last and its vectors +-- describe the latest committed state. User requests never take it. +-- name: LockSemanticSubject :exec +SELECT pg_advisory_xact_lock(sqlc.arg(lock_key)::bigint); diff --git a/backend/db/queries/support_cases.sql b/backend/db/queries/support_cases.sql new file mode 100644 index 0000000..b1c8f6b --- /dev/null +++ b/backend/db/queries/support_cases.sql @@ -0,0 +1,154 @@ +-- Case numbers are monotonic and never reused. Sequence gaps on a rolled-back +-- request are expected and do not expose request contents. +-- name: NextSupportCaseNumber :one +WITH next_value AS MATERIALIZED ( + SELECT nextval('support_case_number_seq') AS value +) +SELECT + 'SC-' || sqlc.arg(utc_year)::text || '-' || + CASE + WHEN next_value.value < 1000000 THEN lpad(next_value.value::text, 6, '0') + ELSE next_value.value::text + END::text AS case_number +FROM next_value; + +-- The initial public history is inserted in the caller's case transaction. +-- Any unique business conflict leaves the transaction usable so the caller can +-- store the immutable 409 outcome under the request's idempotency key. +-- name: InsertSupportCase :execrows +INSERT INTO support_cases ( + id, case_number, owner_id, case_type, status, description, + object_type, object_id, assessment_specialization, assessment_grade, + complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id, + target_business_days, target_due_at, + target_answered_at, target_policy_version, target_calendar_version, + decision_outcome, decision_reason, decision_at, created_at, updated_at +) VALUES ( + sqlc.arg(id), sqlc.arg(case_number), sqlc.arg(owner_id), sqlc.arg(case_type), + sqlc.arg(status), sqlc.arg(description), sqlc.narg(object_type), sqlc.narg(object_id), + sqlc.narg(assessment_specialization), sqlc.narg(assessment_grade), + sqlc.narg(complaint_reason), sqlc.narg(rubric_version), sqlc.narg(rubric_opening_id), + sqlc.narg(rubric_policy_version_id), sqlc.arg(target_business_days), + sqlc.arg(target_due_at), sqlc.narg(target_answered_at), sqlc.arg(target_policy_version), + sqlc.arg(target_calendar_version), sqlc.narg(decision_outcome), sqlc.narg(decision_reason), + sqlc.narg(decision_at), sqlc.arg(created_at), sqlc.arg(updated_at) +) +ON CONFLICT DO NOTHING; + +-- name: InsertSupportCaseEvent :exec +INSERT INTO support_case_events ( + case_id, sequence, event_kind, actor_kind, occurred_at, status, message +) VALUES ( + sqlc.arg(case_id), sqlc.arg(sequence), sqlc.arg(event_kind), sqlc.arg(actor_kind), + sqlc.arg(occurred_at), sqlc.narg(status), sqlc.narg(message) +); + +-- Reads a full owner-scoped record. Object values are identifiers only. +-- name: ReadOwnedSupportCase :one +SELECT + id, case_number, owner_id, case_type, status, description, + object_type, object_id, assessment_specialization, assessment_grade, + complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id, + target_business_days, target_due_at, + target_answered_at, target_policy_version, target_calendar_version, + decision_outcome, decision_reason, decision_at, created_at, updated_at +FROM support_cases +WHERE id = sqlc.arg(case_id) AND owner_id = sqlc.arg(owner_id); + +-- Reads the immutable public history only after the case owner has matched. +-- name: ReadSupportCaseEvents :many +SELECT sequence, event_kind, actor_kind, occurred_at, status, message +FROM support_case_events +WHERE case_id = sqlc.arg(case_id) +ORDER BY sequence; + +-- Owner-scoped newest-first list. It omits descriptions, complaint reason, +-- and event history. The tuple cursor matches the composite sort key. +-- name: ListOwnedSupportCases :many +WITH cursor_input AS MATERIALIZED ( + SELECT + sqlc.narg(after_created_at)::timestamptz AS after_created_at, + sqlc.narg(after_id)::uuid AS after_id +) +SELECT + id, case_number, case_type, status, object_type, object_id, + assessment_specialization, assessment_grade, target_business_days, + target_due_at, target_answered_at, target_policy_version, + target_calendar_version, decision_outcome, created_at, updated_at +FROM support_cases +CROSS JOIN cursor_input +WHERE owner_id = sqlc.arg(owner_id) + AND ( + cursor_input.after_created_at IS NULL + OR (created_at, id) < ( + cursor_input.after_created_at, + cursor_input.after_id + ) + ) +ORDER BY created_at DESC, id DESC +LIMIT sqlc.arg(row_limit); + +-- No raw Idempotency-Key or request body reaches these statements. Failure +-- responses pass {} as case_snapshot and the CASE stores SQL NULL instead. +-- name: DeleteSupportCaseCreateOutcome :exec +DELETE FROM support_case_create_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- name: InsertSupportCaseCreateOutcome :exec +INSERT INTO support_case_create_outcomes ( + scope_hash, outcome_kind, case_snapshot, target_was_late, created_at +) VALUES ( + sqlc.arg(scope_hash), sqlc.arg(outcome_kind), + CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(case_snapshot)::jsonb END, + CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(target_was_late)::boolean END, + sqlc.arg(created_at) +); + +-- name: ReadSupportCaseCreateOutcome :one +SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late +FROM support_case_create_outcomes +WHERE scope_hash = sqlc.arg(scope_hash); + +-- Serialize per-owner budget checks even before the first event exists. +-- name: LockSupportCaseRequestBudget :exec +SELECT pg_advisory_xact_lock( + hashtextextended('lincodex.support.case.requests:' || sqlc.arg(owner_id)::uuid::text, 0) +); + +-- Read the latest serialized event so a temporarily regressing application +-- clock cannot make the next request fall before an event already counted. +-- name: LatestSupportCaseRequestEvent :one +SELECT requested_at +FROM support_case_request_events +WHERE owner_id = sqlc.arg(owner_id) +ORDER BY requested_at DESC, id DESC +LIMIT 1; + +-- Keep up to the maximum supported window, regardless of the current policy. +-- The bounded delete prevents one create from doing unbounded cleanup work. +-- name: PruneSupportCaseRequestEvents :execrows +WITH expired AS MATERIALIZED ( + SELECT source.id + FROM support_case_request_events AS source + WHERE source.owner_id = sqlc.arg(owner_id) + AND source.requested_at <= sqlc.arg(at)::timestamptz - interval '24 hours' + ORDER BY source.requested_at, source.id + LIMIT 100 + FOR UPDATE SKIP LOCKED +) +DELETE FROM support_case_request_events AS event +USING expired +WHERE event.id = expired.id; + +-- The strict lower boundary means an event exactly one window old no longer +-- counts. The use case derives Retry-After from first_in_window. +-- name: CountSupportCaseRequestEvents :one +SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window +FROM support_case_request_events +WHERE owner_id = sqlc.arg(owner_id) + AND requested_at > sqlc.arg(window_start)::timestamptz + AND requested_at <= sqlc.arg(at)::timestamptz; + +-- name: InsertSupportCaseRequestEvent :exec +INSERT INTO support_case_request_events (owner_id, requested_at) +VALUES (sqlc.arg(owner_id), sqlc.arg(requested_at)); diff --git a/backend/db/queries/support_rubrics.sql b/backend/db/queries/support_rubrics.sql new file mode 100644 index 0000000..799e6d1 --- /dev/null +++ b/backend/db/queries/support_rubrics.sql @@ -0,0 +1,53 @@ +-- Lists every current reviewed category binding for one exact public target. +-- Manual support cases have no task-language selector, so the use case must +-- accept a rubric only when one distinct current opening matches. +-- name: ResolveCurrentSupportCaseRubrics :many +WITH current_openings AS ( + SELECT DISTINCT ON (category) + id, + category, + policy_version_id, + required_families + FROM assessment_category_openings + ORDER BY category, opened_at DESC, id DESC +), current_policy AS ( + SELECT id, version + FROM policy_versions + WHERE policy_key = 'product' AND effective_at <= statement_timestamp() + ORDER BY version DESC + LIMIT 1 +) +SELECT + opening.id AS opening_id, + opening.category, + opening.policy_version_id, + opening.required_families, + COALESCE(( + SELECT count(DISTINCT family.family_key)::integer + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), 0)::integer AS published_count, + policy.id AS effective_policy_id, + policy.version AS effective_policy_version, + binding.specialization, + binding.grade, + binding.task_languages, + binding.published_manifest_sha256, + COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'family_key', family.family_key, + 'version', family.version, + 'content_sha256', encode(family.content_sha256, 'hex') + ) ORDER BY family.family_key, family.version + ) + FROM assessment_families AS family + WHERE family.category = opening.category AND family.lifecycle = 'published' + ), '[]'::jsonb)::text AS published_manifest +FROM current_openings AS opening +JOIN assessment_category_catalog_bindings AS binding + ON binding.opening_id = opening.id +LEFT JOIN current_policy AS policy ON true +WHERE binding.specialization = sqlc.arg(specialization) + AND binding.grade = sqlc.arg(grade) +ORDER BY opening.category; diff --git a/backend/go.mod b/backend/go.mod index f6067a8..ee20b6f 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -1,6 +1,6 @@ module lincodex/backend -go 1.26.8 +go 1.26.9 require ( github.com/aws/aws-sdk-go-v2 v1.47.1 @@ -12,18 +12,28 @@ require ( github.com/go-faster/errors v0.8.0 github.com/go-faster/jx v1.2.0 github.com/goforj/wire v1.2.0 + github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 + github.com/moby/moby/client v0.5.1 github.com/ogen-go/ogen v1.24.0 + github.com/pressly/goose/v3 v3.28.0 github.com/prometheus/client_golang v1.24.1 github.com/redis/go-redis/v9 v9.22.0 github.com/testcontainers/testcontainers-go v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 + github.com/twmb/franz-go v1.22.1 + github.com/twmb/franz-go/pkg/kadm v1.19.0 + github.com/twmb/franz-go/pkg/kmsg v1.14.0 github.com/wahrwelt-kit/go-cachekit v0.7.0 github.com/wahrwelt-kit/go-httpkit v0.7.0 github.com/wahrwelt-kit/go-logkit v0.6.0 go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/metric v1.47.0 go.opentelemetry.io/otel/trace v1.47.0 + go.yaml.in/yaml/v3 v3.0.5 + golang.org/x/crypto v0.57.0 + golang.org/x/sync v0.23.0 + golang.org/x/text v0.42.0 ) require ( @@ -182,7 +192,6 @@ require ( github.com/google/cel-go v0.28.0 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/subcommands v1.2.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/gordonklaus/ineffassign v0.2.0 // indirect github.com/gostaticanalysis/analysisutil v0.7.1 // indirect github.com/gostaticanalysis/comment v1.5.0 // indirect @@ -208,7 +217,7 @@ require ( github.com/karamaru-alpha/copyloopvar v1.2.2 // indirect github.com/kisielk/errcheck v1.20.0 // indirect github.com/kkHAIKE/contextcheck v1.1.6 // indirect - github.com/klauspost/compress v1.19.2 // indirect + github.com/klauspost/compress v1.20.0 // indirect github.com/knadh/koanf/maps v0.1.2 // indirect github.com/knadh/koanf/parsers/yaml v1.1.0 // indirect github.com/knadh/koanf/providers/env v1.1.0 // indirect @@ -249,7 +258,6 @@ require ( github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/go-archive v0.3.0 // indirect github.com/moby/moby/api v1.55.0 // indirect - github.com/moby/moby/client v0.5.1 // indirect github.com/moby/patternmatcher v0.6.1 // indirect github.com/moby/sys/sequential v0.7.0 // indirect github.com/moby/sys/user v0.4.1 // indirect @@ -274,7 +282,7 @@ require ( github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/pelletier/go-toml/v2 v2.4.3 // indirect github.com/pganalyze/pg_query_go/v6 v6.2.2 // indirect - github.com/pierrec/lz4/v4 v4.1.29 // indirect + github.com/pierrec/lz4/v4 v4.1.30 // indirect github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee // indirect github.com/pingcap/failpoint v0.0.0-20240528011301-b51a646c7c86 // indirect github.com/pingcap/log v1.1.0 // indirect @@ -283,7 +291,6 @@ require ( github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect - github.com/pressly/goose/v3 v3.28.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect github.com/prometheus/common v0.72.0 // indirect github.com/prometheus/procfs v0.22.0 // indirect @@ -374,17 +381,13 @@ require ( go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect - go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect - golang.org/x/crypto v0.57.0 // indirect golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect golang.org/x/mod v0.41.0 // indirect - golang.org/x/net v0.59.0 // indirect - golang.org/x/sync v0.23.0 // indirect + golang.org/x/net v0.60.0 // indirect golang.org/x/sys v0.48.0 // indirect golang.org/x/term v0.46.0 // indirect - golang.org/x/text v0.42.0 // indirect golang.org/x/tools v0.50.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260831171406-18b4a7587f8a // indirect diff --git a/backend/go.sum b/backend/go.sum index ee61b24..0336bd8 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -483,8 +483,8 @@ github.com/kisielk/errcheck v1.20.0 h1:9rwHBNKzd4wkDWcROy3DvFGNqEPlkxBg305rvk7Ha github.com/kisielk/errcheck v1.20.0/go.mod h1:O+f80MKNwX8Oor2jwgpeQ9An7uJm+hRSgT+h22knRJU= github.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/ttjfJCE= github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg= -github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= -github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.0 h1:a3C1ke2ohxFymNlb2HWAHjDeKCI90scRskErZkR0ezA= +github.com/klauspost/compress v1.20.0/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= github.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo= @@ -643,8 +643,8 @@ github.com/pelletier/go-toml/v2 v2.4.3 h1:GTRvJQutkOSftxIFD5xw9aepkYNuPWmVJpffdD github.com/pelletier/go-toml/v2 v2.4.3/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pganalyze/pg_query_go/v6 v6.2.2 h1:O0L6zMC226R82RF3X5n0Ki6HjytDsoAzuzp4ATVAHNo= github.com/pganalyze/pg_query_go/v6 v6.2.2/go.mod h1:Cn6+j4870kJz3iYNsb0VsNG04vpSWgEvBwc590J4qD0= -github.com/pierrec/lz4/v4 v4.1.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg= -github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= +github.com/pierrec/lz4/v4 v4.1.30 h1:cchX8N2DVP668WkElI9QMwVyoNabLkq1LofDHFeIrdg= +github.com/pierrec/lz4/v4 v4.1.30/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4= github.com/pingcap/errors v0.11.0/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee h1:/IDPbpzkzA97t1/Z1+C3KlxbevjMeaI6BQYxvivu4u8= github.com/pingcap/errors v0.11.5-0.20250523034308-74f78ae071ee/go.mod h1:X2r9ueLEUZgtx2cIogM0v4Zj5uvvzhuuiu7Pn8HzMPg= @@ -807,6 +807,12 @@ github.com/tommy-muehle/go-mnd/v2 v2.5.1 h1:NowYhSdyE/1zwK9QCLeRb6USWdoif80Ie+v+ github.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw= github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60 h1:TfQEwhr0Q9t+Bgs0TNk2eHZ9EGD107Mimic0kcoGS1M= github.com/tursodatabase/libsql-client-go v0.0.0-20260528064733-9d5d30a29a60/go.mod h1:08inkKyguB6CGGssc/JzhmQWwBgFQBgjlYFjxjRh7nU= +github.com/twmb/franz-go v1.22.1 h1:J7Xixbb7k0Itl39eaBot5PIblZh9IL3ZKYgo2yzlf40= +github.com/twmb/franz-go v1.22.1/go.mod h1:b2qISbZgMTJRcIsltVqPz4+Bb2Lw/9bN+/Gd0C07kYw= +github.com/twmb/franz-go/pkg/kadm v1.19.0 h1:5Nx/WWFkpNUi8Z55Skxvn9x5HOCjw+BUntSNB1kLglk= +github.com/twmb/franz-go/pkg/kadm v1.19.0/go.mod h1:emmsx5J7YPU9A7UHcSoz0fBMYVmCcJO2etylJeU0VHU= +github.com/twmb/franz-go/pkg/kmsg v1.14.0 h1:gSxrBEKWl3qnsx3QKWol5OEVujuPmIoDkhMt3didFKM= +github.com/twmb/franz-go/pkg/kmsg v1.14.0/go.mod h1:+DPt4NC8RmI6hqb8G09+3giKObE6uD2Eya6CfqBpeJY= github.com/ultraware/funlen v0.2.0 h1:gCHmCn+d2/1SemTdYMiKLAHFYxTYz7z9VIDRaTGyLkI= github.com/ultraware/funlen v0.2.0/go.mod h1:ZE0q4TsJ8T1SQcjmkhN/w+MceuatI6pBFSxxyteHIJA= github.com/ultraware/whitespace v0.2.0 h1:TYowo2m9Nfj1baEQBjuHzvMRbp19i+RCcRYrSWoFa+g= @@ -962,8 +968,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/backend/integration_test/assessment_answer_http_test.go b/backend/integration_test/assessment_answer_http_test.go new file mode 100644 index 0000000..e5e6d5d --- /dev/null +++ b/backend/integration_test/assessment_answer_http_test.go @@ -0,0 +1,476 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/domain" +) + +func TestAssessmentAnswerAndResultPersistAcrossRouterReconstruction(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "answer-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234") + + create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, + "answer-flow-create", "203.0.113.43:1234") + if create.Code != http.StatusCreated { + t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String()) + } + var publicAttempt assessmentAnswerHTTPAttempt + if err := json.Unmarshal(create.Body.Bytes(), &publicAttempt); err != nil || publicAttempt.ID == uuid.Nil || publicAttempt.CurrentItem == nil { + t.Fatalf("created attempt = %+v, decode error %v", publicAttempt, err) + } + items := readAssessmentAnswerHTTPItems(t, ctx, harness, publicAttempt.ID) + if len(items) < 2 || items[0].ID != publicAttempt.CurrentItem.ID { + t.Fatalf("frozen item count/current item = %d/%s, want ordered item list starting at current item", len(items), publicAttempt.CurrentItem.ID) + } + + finalizePath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + "/finalize" + finalizeBody, err := json.Marshal(map[string]int64{"expected_version": publicAttempt.Version}) + if err != nil { + t.Fatalf("marshal early finalize: %v", err) + } + earlyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234") + var pendingProblem struct { + Code string `json:"code"` + PendingItemIDs []uuid.UUID `json:"pending_item_ids"` + } + if earlyFinalize.Code != http.StatusConflict || json.Unmarshal(earlyFinalize.Body.Bytes(), &pendingProblem) != nil || + pendingProblem.Code != "state_conflict" || len(pendingProblem.PendingItemIDs) != len(items) { + t.Fatalf("early finalize = %d %s, want state_conflict with %d pending item IDs", earlyFinalize.Code, earlyFinalize.Body.String(), len(items)) + } + for index, item := range items { + if pendingProblem.PendingItemIDs[index] != item.ID { + t.Fatalf("pending item %d = %s, want frozen item %s", index, pendingProblem.PendingItemIDs[index], item.ID) + } + } + finalizeReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-early-finalize", "203.0.113.44:1234") + if finalizeReplay.Code != earlyFinalize.Code || + assessmentHTTPBodyWithoutTraceID(t, finalizeReplay.Body.String()) != assessmentHTTPBodyWithoutTraceID(t, earlyFinalize.Body.String()) { + t.Fatalf("early finalize replay = %d %s, want stored %d %s", finalizeReplay.Code, finalizeReplay.Body.String(), earlyFinalize.Code, earlyFinalize.Body.String()) + } + + firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, publicAttempt.Version, items[0], false) + withClientScore := strings.TrimSuffix(string(firstAnswer), "}") + `,"score":100}` + clientScore := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", withClientScore, + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234") + if clientScore.Code != http.StatusBadRequest { + t.Fatalf("answer with client score = %d %s, want rejected request", clientScore.Code, clientScore.Body.String()) + } + answerScope := harness.keyring.IdempotencyScope("assessment_attempt.answer", "answer-flow-first", candidate.ID.String()) + var badScoreOutcomeCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash=$1", answerScope[:]).Scan(&badScoreOutcomeCount); err != nil || badScoreOutcomeCount != 0 { + t.Fatalf("invalid client score reserved idempotency row count=%d error=%v, want zero", badScoreOutcomeCount, err) + } + + firstAccepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234") + var firstSnapshot assessmentAnswerHTTPAttempt + if firstAccepted.Code != http.StatusOK || json.Unmarshal(firstAccepted.Body.Bytes(), &firstSnapshot) != nil || + firstSnapshot.Version != publicAttempt.Version+1 || firstSnapshot.CurrentItem == nil || firstSnapshot.CurrentItem.ID != items[1].ID { + t.Fatalf("first answer = %d %s, want next frozen item and incremented version", firstAccepted.Code, firstAccepted.Body.String()) + } + storedAnswer, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID) + if len(storedAnswer) == 0 || answeredAt.IsZero() { + t.Fatalf("first answer storage = bytes %d, answered_at %s; want canonical answer and server time", len(storedAnswer), answeredAt) + } + answerReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(firstAnswer), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-first", "203.0.113.45:1234") + if answerReplay.Code != firstAccepted.Code || answerReplay.Body.String() != firstAccepted.Body.String() { + t.Fatalf("answer replay = %d %s, want stored %d %s", answerReplay.Code, answerReplay.Body.String(), firstAccepted.Code, firstAccepted.Body.String()) + } + + // A reconstructed service graph and router read the committed answer and + // its server timestamp from PostgreSQL, not the old handler's memory. + harness.pool.Close() + harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + readPath := "/api/v1/me/assessment-attempts/" + publicAttempt.ID.String() + reconstructedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, readPath, "", "", + cookie.Value, "", "", "203.0.113.46:1234") + var reconstructedAttempt assessmentAnswerHTTPAttempt + if reconstructedRead.Code != http.StatusOK || json.Unmarshal(reconstructedRead.Body.Bytes(), &reconstructedAttempt) != nil || + reconstructedAttempt.Version != firstSnapshot.Version || reconstructedAttempt.CurrentItem == nil || + reconstructedAttempt.CurrentItem.ID != firstSnapshot.CurrentItem.ID { + t.Fatalf("GET after router reconstruction = %d %s, want version %d and item %s", reconstructedRead.Code, reconstructedRead.Body.String(), firstSnapshot.Version, firstSnapshot.CurrentItem.ID) + } + reconstructedAnswer, reconstructedAnsweredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, publicAttempt.ID, items[0].ID) + if string(reconstructedAnswer) != string(storedAnswer) || !reconstructedAnsweredAt.Equal(answeredAt) { + t.Fatalf("answer after router reconstruction differs: bytes equal=%v timestamp=%s want %s", string(reconstructedAnswer) == string(storedAnswer), reconstructedAnsweredAt, answeredAt) + } + + currentVersion := reconstructedAttempt.Version + for _, item := range items[1:] { + body := assessmentAnswerHTTPBody(t, currentVersion, item) + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+publicAttempt.ID.String()+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-item-%d", item.Ordinal), + fmt.Sprintf("203.0.113.%d:1234", 50+item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != currentVersion+1 { + t.Fatalf("answer frozen item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), currentVersion+1) + } + if item.Ordinal < int32(len(items)) && (next.CurrentItem == nil || next.CurrentItem.ID != items[item.Ordinal].ID) { + t.Fatalf("answer item %d returned current item %+v, want %s", item.Ordinal, next.CurrentItem, items[item.Ordinal].ID) + } + if item.Ordinal == int32(len(items)) && (next.State != "ready_to_finalize" || next.CurrentItem != nil) { + t.Fatalf("final answer returned state=%s current_item=%+v, want ready_to_finalize", next.State, next.CurrentItem) + } + currentVersion = next.Version + } + + finalizeBody, err = json.Marshal(map[string]int64{"expected_version": currentVersion}) + if err != nil { + t.Fatalf("marshal finalization: %v", err) + } + finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.90:1234") + var completed assessmentAnswerHTTPAttempt + if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" { + t.Fatalf("finalize complete attempt = %d %s, want completed", finalized.Code, finalized.Body.String()) + } + resultPath := readPath + "/result" + resultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "", + cookie.Value, "", "", "203.0.113.91:1234") + var realResult map[string]any + if resultResponse.Code != http.StatusOK || json.Unmarshal(resultResponse.Body.Bytes(), &realResult) != nil || + realResult["attempt_id"] != publicAttempt.ID.String() || realResult["outcome"] != "confirmed" { + t.Fatalf("read completed result = %d %s, want persisted confirmed result", resultResponse.Code, resultResponse.Body.String()) + } + score, ok := realResult["basic_score"].(map[string]any) + points, pointsOK := score["points"].(float64) + maxPoints, maxPointsOK := score["max_points"].(float64) + if !ok || !pointsOK || !maxPointsOK || points != maxPoints-1 || score["pass_points"] == nil { + t.Fatalf("real result basic score = %#v, want one incorrect server-scored item", realResult["basic_score"]) + } + sameKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize", "203.0.113.94:1234") + if sameKeyFinalize.Code != finalized.Code || sameKeyFinalize.Body.String() != finalized.Body.String() { + t.Fatalf("completed finalize replay = %d %s, want stored %d %s", sameKeyFinalize.Code, sameKeyFinalize.Body.String(), finalized.Code, finalized.Body.String()) + } + newFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": completed.Version}) + if err != nil { + t.Fatalf("marshal completed finalize retry: %v", err) + } + newKeyFinalize := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, finalizePath, string(newFinalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-finalize-again", "203.0.113.95:1234") + if newKeyFinalize.Code != finalized.Code || newKeyFinalize.Body.String() != finalized.Body.String() { + t.Fatalf("new-key completed finalize = %d %s, want existing terminal projection %d %s", newKeyFinalize.Code, newKeyFinalize.Body.String(), finalized.Code, finalized.Body.String()) + } + var resultRowCount int64 + var persistedVersion int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempt_results WHERE attempt_id=$1", publicAttempt.ID).Scan(&resultRowCount); err != nil { + t.Fatalf("count immutable result rows: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT version FROM assessment_attempts WHERE id=$1", publicAttempt.ID).Scan(&persistedVersion); err != nil { + t.Fatalf("read finalized attempt version: %v", err) + } + if resultRowCount != 1 || persistedVersion != completed.Version { + t.Fatalf("finalize retries left %d result rows and version %d, want one row and version %d", resultRowCount, persistedVersion, completed.Version) + } + resultSnapshot, productPolicyID, openingID, rawScore, passMark, rawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, publicAttempt.ID) + if resultSnapshot["outcome"] != "confirmed" || !rawScoreValid || rawScore != int16(score["points"].(float64)) { + t.Fatalf("stored result outcome/score = %v/%d (valid %v), API result = %v/%v", resultSnapshot["outcome"], rawScore, rawScoreValid, realResult["outcome"], score["points"]) + } + pins, ok := resultSnapshot["pins"].(map[string]any) + if !ok || pins["product_policy_version_id"] != productPolicyID.String() || pins["opening_id"] != openingID.String() || + !strings.Contains(stringMustJSON(t, resultSnapshot), `"product_policy_version_id":"`+productPolicyID.String()+`"`) { + t.Fatalf("stored result pin IDs are not UUID strings: %#v", resultSnapshot["pins"]) + } + if passMark < 1 || strings.Contains(resultResponse.Body.String(), "ReferenceAnswer") || strings.Contains(resultResponse.Body.String(), "answer_key") { + t.Fatalf("result exposed private source or lost its stored pass mark: body=%s pass_mark=%d", resultResponse.Body.String(), passMark) + } + + // The result projection is read from the immutable stored snapshot after a + // second router/pool reconstruction and stays byte-for-byte stable. + harness.pool.Close() + harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + restartedResult := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, resultPath, "", "", + cookie.Value, "", "", "203.0.113.92:1234") + if restartedResult.Code != http.StatusOK || restartedResult.Body.String() != resultResponse.Body.String() { + t.Fatalf("result after router reconstruction = %d %s, want stored projection %s", restartedResult.Code, restartedResult.Body.String(), resultResponse.Body.String()) + } + + var rootAttemptsBeforeExpress int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsBeforeExpress); err != nil { + t.Fatalf("count real attempts before express completion: %v", err) + } + trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-create", "203.0.113.93:1234") + var training assessmentAnswerHTTPAttempt + if trainingCreate.Code != http.StatusCreated || json.Unmarshal(trainingCreate.Body.Bytes(), &training) != nil || training.ID == uuid.Nil { + t.Fatalf("create express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String()) + } + trainingItems := readAssessmentAnswerHTTPItems(t, ctx, harness, training.ID) + trainingVersion := training.Version + for _, item := range trainingItems { + body := assessmentAnswerHTTPBody(t, trainingVersion, item) + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+training.ID.String()+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("answer-flow-express-%d", item.Ordinal), + fmt.Sprintf("203.0.113.%d:1234", 100+item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != trainingVersion+1 { + t.Fatalf("answer express item %d = %d %s", item.Ordinal, response.Code, response.Body.String()) + } + trainingVersion = next.Version + } + trainingFinalizeBody, err := json.Marshal(map[string]int64{"expected_version": trainingVersion}) + if err != nil { + t.Fatalf("marshal express finalization: %v", err) + } + trainingFinalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+training.ID.String()+"/finalize", string(trainingFinalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "answer-flow-express-finalize", "203.0.113.110:1234") + if trainingFinalized.Code != http.StatusOK { + t.Fatalf("finalize express attempt = %d %s", trainingFinalized.Code, trainingFinalized.Body.String()) + } + trainingResultResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, + "/api/v1/me/assessment-attempts/"+training.ID.String()+"/result", "", "", cookie.Value, "", "", "203.0.113.111:1234") + var trainingResult map[string]any + if trainingResultResponse.Code != http.StatusOK || json.Unmarshal(trainingResultResponse.Body.Bytes(), &trainingResult) != nil || + trainingResult["outcome"] != "demonstration" || trainingResult["mode"] != "demo_express" || + trainingResult["basic_score"] != nil || trainingResult["confirmed_grade"] != nil || trainingResult["specialization"] != nil { + t.Fatalf("express result = %d %s, want demonstration without score or grade", trainingResultResponse.Code, trainingResultResponse.Body.String()) + } + _, _, _, expressRawScore, _, expressRawScoreValid := readAssessmentAttemptHTTPResult(t, ctx, harness, training.ID) + if expressRawScoreValid { + t.Fatalf("express result stored raw score %d, want SQL NULL", expressRawScore) + } + var rootAttemptsAfterExpress int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", candidate.ID).Scan(&rootAttemptsAfterExpress); err != nil { + t.Fatalf("count real attempts after express completion: %v", err) + } + if rootAttemptsAfterExpress != rootAttemptsBeforeExpress { + t.Fatalf("express completion changed real root quota count from %d to %d", rootAttemptsBeforeExpress, rootAttemptsAfterExpress) + } +} + +type assessmentAnswerHTTPAttempt struct { + ID uuid.UUID `json:"id"` + Version int64 `json:"version"` + State string `json:"state"` + CurrentItem *struct { + ID uuid.UUID `json:"id"` + } `json:"current_item"` +} + +type assessmentAnswerHTTPItem struct { + ID uuid.UUID + Ordinal int32 + Variant domain.AssessmentVariant +} + +func readAssessmentAnswerHTTPItems( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, +) []assessmentAnswerHTTPItem { + t.Helper() + rows, err := harness.pool.Query(ctx, `SELECT id, ordinal, variant FROM assessment_attempt_items WHERE attempt_id=$1 ORDER BY ordinal`, attemptID) + if err != nil { + t.Fatalf("read frozen assessment items: %v", err) + } + defer rows.Close() + items := make([]assessmentAnswerHTTPItem, 0) + for rows.Next() { + var item assessmentAnswerHTTPItem + var encoded []byte + if err := rows.Scan(&item.ID, &item.Ordinal, &encoded); err != nil { + t.Fatalf("scan frozen assessment item: %v", err) + } + item.Variant, err = domain.UnmarshalAssessmentAttemptVariant(encoded) + if err != nil { + t.Fatalf("restore frozen assessment variant: %v", err) + } + items = append(items, item) + } + if err := rows.Err(); err != nil { + t.Fatalf("iterate frozen assessment items: %v", err) + } + return items +} + +func readAssessmentAnswerHTTPItem( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID, itemID uuid.UUID, +) ([]byte, time.Time) { + t.Helper() + var answer []byte + var answeredAt time.Time + if err := harness.pool.QueryRow(ctx, `SELECT answer, answered_at FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2`, + attemptID, itemID).Scan(&answer, &answeredAt); err != nil { + t.Fatalf("read stored answer and server time: %v", err) + } + return answer, answeredAt.UTC() +} + +func assessmentAnswerHTTPBody(t *testing.T, version int64, item assessmentAnswerHTTPItem) []byte { + return assessmentAnswerHTTPBodyWithCorrectness(t, version, item, true) +} + +func assessmentAnswerHTTPBodyWithCorrectness( + t *testing.T, + version int64, + item assessmentAnswerHTTPItem, + wantCorrect bool, +) []byte { + t.Helper() + var answer []byte + switch item.Variant.AnswerFormat { + case domain.AnswerFormatInteger: + reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64) + if err != nil { + t.Fatalf("parse frozen answer key %q: %v", item.Variant.ReferenceAnswer, err) + } + if !wantCorrect { + reference++ + } + answer = []byte(fmt.Sprintf(`{"format":"number","number":%d}`, reference)) + case domain.AnswerFormatIntegerSequence: + parts := strings.Fields(item.Variant.ReferenceAnswer) + if !wantCorrect && len(parts) < 2 { + t.Fatalf("frozen sequence answer %q has fewer than two tasks", item.Variant.ReferenceAnswer) + } + elements := make([]string, 0, len(parts)) + for _, part := range parts { + elements = append(elements, "job_"+part) + } + if !wantCorrect { + elements[0], elements[1] = elements[1], elements[0] + } + var err error + answer, err = json.Marshal(struct { + Format string `json:"format"` + ElementIDs []string `json:"element_ids"` + }{Format: "order", ElementIDs: elements}) + if err != nil { + t.Fatalf("marshal order answer: %v", err) + } + case domain.AnswerFormatChoice: + chosen, err := strconv.Atoi(item.Variant.ReferenceAnswer) + if err != nil || chosen < 0 || chosen >= len(item.Variant.Options) { + t.Fatalf("frozen choice key %q does not name one of %d options", item.Variant.ReferenceAnswer, len(item.Variant.Options)) + } + if !wantCorrect { + chosen = (chosen + 1) % len(item.Variant.Options) + } + answer, err = json.Marshal(struct { + Format string `json:"format"` + OptionIDs []string `json:"option_ids"` + }{Format: "choice", OptionIDs: []string{item.Variant.Options[chosen].ID}}) + if err != nil { + t.Fatalf("marshal choice answer: %v", err) + } + default: + t.Fatalf("unsupported fixture answer format %q", item.Variant.AnswerFormat) + } + _, correct, err := domain.CanonicalAssessmentAnswerForVariant(answer, item.Variant) + if err != nil || correct != wantCorrect { + t.Fatalf("fixture answer for item %s has correctness %v, want %v: error %v", item.ID, correct, wantCorrect, err) + } + body, err := json.Marshal(struct { + ExpectedVersion int64 `json:"expected_version"` + ItemID uuid.UUID `json:"item_id"` + Answer json.RawMessage `json:"answer"` + }{ExpectedVersion: version, ItemID: item.ID, Answer: answer}) + if err != nil { + t.Fatalf("marshal answer command: %v", err) + } + return body +} + +func readAssessmentAttemptHTTPResult( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, +) (map[string]any, uuid.UUID, uuid.UUID, int16, int32, bool) { + t.Helper() + var encoded []byte + var productPolicyID uuid.UUID + var storedOpeningID pgtype.UUID + var rawScore pgtype.Int2 + var passMark pgtype.Int4 + if err := harness.pool.QueryRow(ctx, ` + SELECT result_snapshot, product_policy_version_id, opening_id, raw_score, pass_mark_basis_points + FROM assessment_attempt_results WHERE attempt_id=$1`, attemptID). + Scan(&encoded, &productPolicyID, &storedOpeningID, &rawScore, &passMark); err != nil { + t.Fatalf("read immutable assessment result row: %v", err) + } + var openingID uuid.UUID + if storedOpeningID.Valid { + openingID = uuid.UUID(storedOpeningID.Bytes) + } + var document map[string]any + if err := json.Unmarshal(encoded, &document); err != nil { + t.Fatalf("decode immutable assessment result document: %v", err) + } + if !rawScore.Valid || !passMark.Valid { + return document, productPolicyID, openingID, 0, 0, rawScore.Valid + } + return document, productPolicyID, openingID, rawScore.Int16, passMark.Int32, rawScore.Valid +} + +func stringMustJSON(t *testing.T, value any) string { + t.Helper() + encoded, err := json.Marshal(value) + if err != nil { + t.Fatalf("marshal result snapshot for assertion: %v", err) + } + return string(encoded) +} + +func assessmentHTTPBodyWithoutTraceID(t *testing.T, body string) string { + t.Helper() + var document map[string]json.RawMessage + if err := json.Unmarshal([]byte(body), &document); err != nil { + t.Fatalf("decode HTTP problem response: %v", err) + } + delete(document, "trace_id") + encoded, err := json.Marshal(document) + if err != nil { + t.Fatalf("marshal HTTP problem response: %v", err) + } + return string(encoded) +} diff --git a/backend/integration_test/assessment_attempt_http_test.go b/backend/integration_test/assessment_attempt_http_test.go new file mode 100644 index 0000000..b76983b --- /dev/null +++ b/backend/integration_test/assessment_attempt_http_test.go @@ -0,0 +1,1265 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + apiadapter "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" + questionnaireusecase "lincodex/backend/internal/usecase/questionnaire" +) + +const assessmentAttemptHTTPTimeout = 6 * time.Minute + +func TestAssessmentAttemptOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + registeredAt := harness.clock.Now() + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-owner@example.test", passwordHash, true) + missingConsent := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-no-consent@example.test", passwordHash, true) + otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-other@example.test", passwordHash, true) + employer := createQuestionnaireHTTPEmployer(ctx, t, harness.sessionHTTPHarness, "attempt-employer@example.test", passwordHash, registeredAt) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = ANY($1)", + []uuid.UUID{candidate.ID, missingConsent.ID, otherCandidate.ID}); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.241:1234") + missingCookie, missingCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, missingConsent.Email.Address(), "192.0.2.242:1234") + otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.243:1234") + employerCookie, employerCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.244:1234") + + backendBody := assessmentAttemptCreateBody(t, "backend") + guestCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody, + sessionHTTPTestOrigin, "", "", "guest-create", "192.0.2.245:1234") + requireSessionProblem(t, guestCreate, http.StatusUnauthorized, "unauthenticated") + employerCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody, + sessionHTTPTestOrigin, employerCookie.Value, employerCSRF, "employer-create", "192.0.2.246:1234") + requireSessionProblem(t, employerCreate, http.StatusForbidden, "forbidden") + missingC3Create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", backendBody, + sessionHTTPTestOrigin, missingCookie.Value, missingCSRF, "missing-c3-create", "192.0.2.247:1234") + requireSessionProblem(t, missingC3Create, http.StatusForbidden, "forbidden") + assertAttemptCount(t, ctx, harness.pool, 0) + + if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "192.0.2.248:1234"); response.Code != http.StatusOK { + t.Fatalf("save two-specialization questionnaire = %d %s", response.Code, response.Body.String()) + } + trainingBody := `{"kind":"demo_express"}` + trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "192.0.2.248:1235") + if trainingCreate.Code != http.StatusCreated { + t.Fatalf("create reviewed express attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String()) + } + var trainingSnapshot struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + Mode string `json:"mode"` + State string `json:"state"` + } + if err := json.Unmarshal(trainingCreate.Body.Bytes(), &trainingSnapshot); err != nil || trainingSnapshot.ID == uuid.Nil || + trainingSnapshot.Kind != "demo_express" || trainingSnapshot.Mode != "demo_express" || trainingSnapshot.State != "in_progress" { + t.Fatalf("express attempt = %+v, decode error %v", trainingSnapshot, err) + } + assertAttemptCount(t, ctx, harness.pool, 1) + grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "192.0.2.249:1234") + + // Both requests pass the same candidate-wide root quota through different + // specialization locks. Exactly one can reserve the only root slot. + requests := []struct { + key string + body string + addr string + }{ + {key: "attempt-backend-root", body: backendBody, addr: "192.0.2.250:1234"}, + {key: "attempt-frontend-root", body: assessmentAttemptCreateBody(t, "frontend"), addr: "192.0.2.251:1234"}, + } + responses := make([]*httptest.ResponseRecorder, len(requests)) + start := make(chan struct{}) + var wait sync.WaitGroup + for index := range requests { + wait.Add(1) + go func(index int) { + defer wait.Done() + <-start + request := requests[index] + responses[index] = assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", request.body, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, request.key, request.addr) + }(index) + } + close(start) + wait.Wait() + + accepted := -1 + conflicted := -1 + for index, response := range responses { + switch response.Code { + case http.StatusCreated: + accepted = index + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("created attempt Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + case http.StatusConflict: + requireSessionProblem(t, response, http.StatusConflict, "state_conflict") + conflicted = index + default: + t.Fatalf("concurrent create %s = %d %s, want one 201 and one 409", requests[index].key, response.Code, response.Body.String()) + } + } + if accepted < 0 || conflicted < 0 || accepted == conflicted { + t.Fatalf("concurrent root results accepted=%d conflicted=%d, want one of each", accepted, conflicted) + } + for index, response := range responses { + replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", requests[index].body, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, requests[index].key, requests[index].addr) + assertAssessmentAttemptReplay(t, requests[index].key, response, replay) + } + var acceptedAttempt struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + Version int64 `json:"version"` + State string `json:"state"` + Specialization string `json:"specialization"` + } + if err := json.Unmarshal(responses[accepted].Body.Bytes(), &acceptedAttempt); err != nil || acceptedAttempt.ID == uuid.Nil || + acceptedAttempt.Kind != "root" || acceptedAttempt.Version != 1 || acceptedAttempt.State != "in_progress" { + t.Fatalf("created attempt = %+v, decode error %v", acceptedAttempt, err) + } + for _, privateField := range []string{`"answer_key"`, `"family_id"`, `"family_key"`, `"variant"`, `"variant_seed"`, `"solution"`} { + if strings.Contains(responses[accepted].Body.String(), privateField) { + t.Fatalf("public attempt response exposed %s", privateField) + } + } + assertAttemptCount(t, ctx, harness.pool, 2) + changedBody := assessmentAttemptCreateBody(t, "frontend") + if requests[accepted].body == changedBody { + changedBody = assessmentAttemptCreateBodyWithGrade(t, "backend", "middle") + } + keyReuse := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", changedBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, requests[accepted].key, "192.0.2.252:1234") + requireSessionProblem(t, keyReuse, http.StatusUnprocessableEntity, "idempotency_key_reused") + assertAttemptCount(t, ctx, harness.pool, 2) + + getPath := "/api/v1/me/assessment-attempts/" + acceptedAttempt.ID.String() + before := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID) + for range 2 { + read := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", candidateCookie.Value, "", "", "192.0.2.253:1234") + if read.Code != http.StatusOK || read.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("own attempt read = %d Cache-Control=%q: %s", read.Code, read.Header().Get("Cache-Control"), read.Body.String()) + } + if read.Body.String() != responses[accepted].Body.String() { + t.Fatalf("GET attempt projection differs from immutable create result: got %s want %s", read.Body.String(), responses[accepted].Body.String()) + } + } + if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before { + t.Fatalf("read-only GET changed attempt state: before=%+v after=%+v", before, after) + } + var createdProjection struct { + CurrentItem *struct { + ID uuid.UUID `json:"id"` + Prompt string `json:"prompt"` + } `json:"current_item"` + } + if err := json.Unmarshal(responses[accepted].Body.Bytes(), &createdProjection); err != nil || createdProjection.CurrentItem == nil || + createdProjection.CurrentItem.ID == uuid.Nil || createdProjection.CurrentItem.Prompt == "" { + t.Fatalf("decode created public item = %+v, error %v", createdProjection, err) + } + // A new pool, service graph, and router must read the same frozen item from + // PostgreSQL after reconstruction, not merely reuse an in-memory handler. + harness.pool.Close() + harness = newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + restartedRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", candidateCookie.Value, "", "", "198.51.100.0:1234") + var restartedProjection struct { + CurrentItem *struct { + ID uuid.UUID `json:"id"` + Prompt string `json:"prompt"` + } `json:"current_item"` + } + if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restartedProjection) != nil || + restartedProjection.CurrentItem == nil || restartedProjection.CurrentItem.ID != createdProjection.CurrentItem.ID || + restartedProjection.CurrentItem.Prompt != createdProjection.CurrentItem.Prompt || + restartedRead.Body.String() != responses[accepted].Body.String() { + t.Fatalf("GET after router reconstruction = %d %s, want item %s and original text", restartedRead.Code, restartedRead.Body.String(), createdProjection.CurrentItem.ID) + } + foreignRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", otherCookie.Value, "", "", "192.0.2.254:1234") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + unknownRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+uuid.NewString(), "", "", candidateCookie.Value, "", "", "192.0.2.255:1234") + requireSessionProblem(t, unknownRead, http.StatusNotFound, "not_found") + employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", employerCookie.Value, "", "", "198.51.100.1:1234") + requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden") + guestRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, getPath, "", "", "", "", "", "198.51.100.2:1234") + requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated") + + // Revocation wins before a session command and leaves both the attempt and + // its session budget unchanged. Restoring C3 permits the same key to run. + revokeC3 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c3", "", sessionHTTPTestOrigin, + candidateCookie.Value, candidateCSRF, "198.51.100.3:1234") + if revokeC3.Code != http.StatusNoContent { + t.Fatalf("revoke C3 before session = %d %s", revokeC3.Code, revokeC3.Body.String()) + } + sessionPath := getPath + "/sessions" + sessionBody := `{"expected_version":1}` + blockedSession := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-session-key", "198.51.100.4:1234") + requireSessionProblem(t, blockedSession, http.StatusForbidden, "forbidden") + if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before { + t.Fatalf("C3-denied session command changed attempt: before=%+v after=%+v", before, after) + } + grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "192.0.2.260:1234") + startRequests := []struct { + key string + addr string + }{ + {key: "attempt-session-key", addr: "198.51.100.5:1234"}, + {key: "attempt-session-key-two", addr: "198.51.100.6:1234"}, + } + startResponses := make([]*httptest.ResponseRecorder, len(startRequests)) + startGate := make(chan struct{}) + var startWait sync.WaitGroup + for index := range startRequests { + startWait.Add(1) + go func(index int) { + defer startWait.Done() + <-startGate + request := startRequests[index] + startResponses[index] = assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, request.key, request.addr) + }(index) + } + close(startGate) + startWait.Wait() + started := startResponses[0] + for index, response := range startResponses { + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("concurrent session start %s = %d Cache-Control=%q: %s", startRequests[index].key, response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + if response.Body.String() != started.Body.String() { + t.Fatalf("concurrent session starts returned different snapshots: %s != %s", response.Body.String(), started.Body.String()) + } + } + startedReplay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, sessionBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, startRequests[0].key, startRequests[0].addr) + if startedReplay.Code != started.Code || startedReplay.Body.String() != started.Body.String() { + t.Fatalf("session replay = %d %s, want stored %d %s", startedReplay.Code, startedReplay.Body.String(), started.Code, started.Body.String()) + } + var sessionSnapshot struct { + Version int64 `json:"version"` + Sessions struct { + Used int32 `json:"used"` + } `json:"sessions"` + } + if err := json.Unmarshal(started.Body.Bytes(), &sessionSnapshot); err != nil || sessionSnapshot.Version != 1 || sessionSnapshot.Sessions.Used != 1 { + t.Fatalf("same-active-session response = %+v, decode error %v; want version 1 and session 1", sessionSnapshot, err) + } + staleSession := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, sessionPath, `{"expected_version":2}`, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-stale-session", "198.51.100.7:1234") + requireSessionProblem(t, staleSession, http.StatusPreconditionFailed, "version_conflict") + if after := readAttemptStoredState(t, ctx, harness.pool, acceptedAttempt.ID); after != before { + t.Fatalf("stale session command changed attempt: before=%+v after=%+v", before, after) + } + + // The root owns a fixed 72-hour correction window. A terminal failed root + // can create one lower-grade correction without consuming another root + // quota slot, and the child keeps the root's exact deadline. + rootStartedAt, rootDeadline := readAttemptChainTiming(t, ctx, harness.pool, acceptedAttempt.ID) + if rootDeadline.Sub(rootStartedAt) != 72*time.Hour { + t.Fatalf("root chain deadline = %s, database started_at=%s; want 72 hours", rootDeadline, rootStartedAt) + } + terminalizeAttempt(t, ctx, harness.pool, acceptedAttempt.ID) + correctiveBody := assessmentAttemptCorrectiveBody(t, acceptedAttempt.Specialization, "intern", acceptedAttempt.ID) + corrective := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", correctiveBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-correction", "198.51.100.8:1234") + if corrective.Code != http.StatusCreated { + t.Fatalf("create lower-grade correction = %d %s", corrective.Code, corrective.Body.String()) + } + var correctiveSnapshot struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + RootAttemptID uuid.UUID `json:"root_attempt_id"` + } + if err := json.Unmarshal(corrective.Body.Bytes(), &correctiveSnapshot); err != nil || correctiveSnapshot.ID == uuid.Nil || + correctiveSnapshot.Kind != "corrective" || correctiveSnapshot.RootAttemptID != acceptedAttempt.ID { + t.Fatalf("corrective snapshot = %+v, decode error %v; want root linkage", correctiveSnapshot, err) + } + if _, correctiveDeadline := readAttemptChainTiming(t, ctx, harness.pool, correctiveSnapshot.ID); !correctiveDeadline.Equal(rootDeadline) { + t.Fatalf("corrective database chain deadline = %s, want exact root deadline %s", correctiveDeadline, rootDeadline) + } + var rootCount int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'`, candidate.ID).Scan(&rootCount); err != nil || rootCount != 1 { + t.Fatalf("candidate root attempt count = %d, error %v; corrective must not consume root quota", rootCount, err) + } + terminalizeAttempt(t, ctx, harness.pool, correctiveSnapshot.ID) + repeatedGrade := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", correctiveBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-correction-repeat", "198.51.100.9:1234") + if repeatedGrade.Code != http.StatusBadRequest || !strings.Contains(repeatedGrade.Body.String(), "/target_grade") { + t.Fatalf("repeat corrective grade = %d %s, want field error at target_grade", repeatedGrade.Code, repeatedGrade.Body.String()) + } + var correctionCount int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='corrective'`, candidate.ID).Scan(&correctionCount); err != nil || correctionCount != 1 { + t.Fatalf("candidate correction count = %d, error %v; repeated grade must not add a row", correctionCount, err) + } + + // The typed 201 training outcome is replaced only after its generic + // idempotency window expires; the active training attempt yields a new 409. + trainingScope := harness.keyring.IdempotencyScope("assessment_attempt.create", "attempt-training", candidate.ID.String()) + if _, err := harness.pool.Exec(ctx, ` + WITH stamp AS (SELECT clock_timestamp() AS at) + UPDATE idempotency_records + SET created_at=stamp.at-interval '2 minutes', expires_at=stamp.at-interval '1 second' + FROM stamp WHERE scope_hash=$1`, trainingScope[:]); err != nil { + t.Fatalf("expire training idempotency fixture: %v", err) + } + expiredTrainingKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "198.51.100.10:1234") + requireSessionProblem(t, expiredTrainingKey, http.StatusConflict, "state_conflict") + reusedTrainingKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", trainingBody, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "attempt-training", "198.51.100.10:1234") + assertAssessmentAttemptReplay(t, "attempt-training after expiry", expiredTrainingKey, reusedTrainingKey) + + // Fail the item insert after the attempt header and idempotency reservation + // have been written. A same-key retry after removing the trigger must work, + // proving that the entire PostgreSQL transaction rolled back. + if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "198.51.100.11:1234"); response.Code != http.StatusOK { + t.Fatalf("save rollback candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "198.51.100.12:1234") + if _, err := harness.pool.Exec(ctx, `CREATE FUNCTION reject_attempt_item_for_test() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION USING ERRCODE='23514', CONSTRAINT='test_attempt_item_rejected', MESSAGE='test failure'; END; $$`); err != nil { + t.Fatalf("create attempt-item rollback trigger function: %v", err) + } + if _, err := harness.pool.Exec(ctx, `CREATE TRIGGER reject_attempt_item_for_test BEFORE INSERT ON assessment_attempt_items FOR EACH ROW EXECUTE FUNCTION reject_attempt_item_for_test()`); err != nil { + t.Fatalf("create attempt-item rollback trigger: %v", err) + } + rollbackBody := assessmentAttemptCreateBody(t, "backend") + rollbackKey := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", rollbackBody, + sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "attempt-rollback-retry", "198.51.100.13:1234") + if rollbackKey.Code != http.StatusInternalServerError { + t.Fatalf("forced item insert failure = %d %s, want internal error", rollbackKey.Code, rollbackKey.Body.String()) + } + if _, err := harness.pool.Exec(ctx, `DROP TRIGGER reject_attempt_item_for_test ON assessment_attempt_items`); err != nil { + t.Fatalf("drop attempt-item rollback trigger: %v", err) + } + if _, err := harness.pool.Exec(ctx, `DROP FUNCTION reject_attempt_item_for_test()`); err != nil { + t.Fatalf("drop attempt-item rollback trigger function: %v", err) + } + assertAttemptCount(t, ctx, harness.pool, 3) + retryAfterRollback := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", rollbackBody, + sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "attempt-rollback-retry", "198.51.100.13:1234") + if retryAfterRollback.Code != http.StatusCreated { + t.Fatalf("same-key create after rollback = %d %s, want 201", retryAfterRollback.Code, retryAfterRollback.Body.String()) + } + assertAttemptCount(t, ctx, harness.pool, 4) + assertAttemptPinAndItemRowsAreImmutable(t, ctx, harness.pool, acceptedAttempt.ID) +} + +func TestAssessmentAttemptSessionUsesDatabaseTimeAfterRowLockWait(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "attempt-lock-wait@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set lock-wait candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.10:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.11:1234"); response.Code != http.StatusOK { + t.Fatalf("save lock-wait candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.12:1234") + created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", assessmentAttemptCreateBody(t, "backend"), + sessionHTTPTestOrigin, cookie.Value, csrf, "attempt-lock-wait-create", "203.0.113.13:1234") + if created.Code != http.StatusCreated { + t.Fatalf("create lock-wait attempt = %d %s", created.Code, created.Body.String()) + } + var attempt struct { + ID uuid.UUID `json:"id"` + } + if err := json.Unmarshal(created.Body.Bytes(), &attempt); err != nil || attempt.ID == uuid.Nil { + t.Fatalf("decode lock-wait attempt ID = %s, error %v", attempt.ID, err) + } + + lockConnection, err := harness.pool.Acquire(ctx) + if err != nil { + t.Fatalf("acquire row-lock connection: %v", err) + } + defer lockConnection.Release() + lockTx, err := lockConnection.Begin(ctx) + if err != nil { + t.Fatalf("begin row-lock transaction: %v", err) + } + defer func() { + if err := lockTx.Rollback(context.Background()); err != nil && !errors.Is(err, pgx.ErrTxClosed) { + t.Errorf("rollback row-lock transaction: %v", err) + } + }() + var lockPID int32 + if err := lockConnection.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&lockPID); err != nil { + t.Fatalf("read row-lock backend PID: %v", err) + } + var lockedID uuid.UUID + if err := lockTx.QueryRow(ctx, `SELECT id FROM assessment_attempts WHERE id=$1 FOR UPDATE`, attempt.ID).Scan(&lockedID); err != nil || lockedID != attempt.ID { + t.Fatalf("lock attempt row %s: got %s, error %v", attempt.ID, lockedID, err) + } + + type requestResult struct { + response *httptest.ResponseRecorder + } + result := make(chan requestResult, 1) + go func() { + response := assessmentAttemptHTTPRequestWithTimeout(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/sessions", `{"expected_version":1}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "attempt-lock-wait-session", "203.0.113.14:1234", 100*time.Second) + result <- requestResult{response: response} + }() + waitForAssessmentAttemptRowLock(t, ctx, harness.pool, lockPID) + waitForAttemptIdleDeadline(t, ctx, harness.pool, attempt.ID) + if err := lockTx.Commit(ctx); err != nil { + t.Fatalf("release row lock after idle timeout: %v", err) + } + select { + case completed := <-result: + if completed.response.Code != http.StatusOK { + t.Fatalf("session after lock-wait expiry = %d %s; server logs: %s", + completed.response.Code, completed.response.Body.String(), harness.logs.String()) + } + var snapshot struct { + Version int64 `json:"version"` + State string `json:"state"` + Sessions struct { + Used int32 `json:"used"` + } `json:"sessions"` + } + if err := json.Unmarshal(completed.response.Body.Bytes(), &snapshot); err != nil || snapshot.Version != 2 || + snapshot.State != "expired" || snapshot.Sessions.Used != 1 { + t.Fatalf("session response after deadline = %+v, error %v; want expired version 2 and one session", snapshot, err) + } + case <-time.After(30 * time.Second): + t.Fatal("session request did not finish after releasing attempt row lock") + } +} + +type assessmentAttemptHTTPHarness struct { + *sessionHTTPHarness + keyring *identity.Keyring +} + +func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *assessmentAttemptHTTPHarness { + t.Helper() + return newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, env, assessment.AssessmentCategoryDecisionSettings{}) +} + +// newAssessmentAttemptHTTPHarnessWithCategories builds the attempt router with +// explicit category assignment settings. The zero settings deny assignment. +func newAssessmentAttemptHTTPHarnessWithCategories( + ctx context.Context, + t *testing.T, + env *testEnvironment, + categories assessment.AssessmentCategoryDecisionSettings, +) *assessmentAttemptHTTPHarness { + t.Helper() + return newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env, categories, nil) +} + +// assessmentHarnessParts are the shared dependencies of the attempt router, for +// a scenario that mounts further business areas on the same router. +type assessmentHarnessParts struct { + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + keyring *identity.Keyring + clock *testClock +} + +// newAssessmentAttemptHTTPHarnessWithOptions builds the attempt router and adds +// the handler options that extra returns, if any. +func newAssessmentAttemptHTTPHarnessWithOptions( + ctx context.Context, + t *testing.T, + env *testEnvironment, + categories assessment.AssessmentCategoryDecisionSettings, + extra func(assessmentHarnessParts) []v1.HandlerOption, +) *assessmentAttemptHTTPHarness { + t.Helper() + return newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, categories, extra, nil) +} + +// newAssessmentAttemptHTTPHarnessWithMiddleware also mounts the operation +// middleware that middleware returns, after extra has built its handlers, so a +// scenario can add the owner company context to the same router. +func newAssessmentAttemptHTTPHarnessWithMiddleware( + ctx context.Context, + t *testing.T, + env *testEnvironment, + categories assessment.AssessmentCategoryDecisionSettings, + extra func(assessmentHarnessParts) []v1.HandlerOption, + middleware func() []apiadapter.Middleware, +) *assessmentAttemptHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + consentStore := postgresadapter.NewConsentStore(pool) + consentHandler := v1.NewConsentHandler( + consent.NewQueryService(consentStore, time.Now), consent.NewService(transactor, time.Now), + ) + questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now)) + catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor)) + attemptService, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock.Now, categories) + if err != nil { + t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err) + } + signalObserver, err := assessment.NewSignalObserver(keyring) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + attemptService.WithSignalObserver(signalObserver) + workSessions, err := assessment.NewWorkSessions(transactor, keyring) + if err != nil { + t.Fatalf("NewWorkSessions() error = %v", err) + } + workSessions.WithSignalObserver(signalObserver) + attemptService.WithWorkSessions(workSessions) + watermarker, err := assessment.NewWatermarker(keyring) + if err != nil { + t.Fatalf("NewWatermarker() error = %v", err) + } + attemptHandler := v1.NewAssessmentHandler(attemptService).WithPresenter(watermarker).WithWorkSessions(workSessions) + signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now) + if err != nil { + t.Fatalf("NewSignalService() error = %v", err) + } + signalService.WithSignalObserver(signalObserver) + signalHandler := v1.NewAssessmentSignalHandler(signalService).WithNotice(signalService) + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + options := []v1.HandlerOption{ + v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), + v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler), + v1.WithAssessment(attemptHandler), v1.WithAssessmentSignals(signalHandler), + } + if extra != nil { + options = append(options, extra(assessmentHarnessParts{pool: pool, transactor: transactor, keyring: keyring, clock: clock})...) + } + handler := v1.NewHandler(healthHandler, responder, options...) + var operationMiddleware []apiadapter.Middleware + if middleware != nil { + operationMiddleware = middleware() + } + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil, operationMiddleware...) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + base := &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} + return &assessmentAttemptHTTPHarness{sessionHTTPHarness: base, keyring: keyring} +} + +func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) { + t.Helper() + seedAssessmentAttemptHTTPBankWithSignals(ctx, t, pool, nil) +} + +// seedAssessmentAttemptHTTPBankWithSignals seeds the attempt fixture bank under +// a product policy that carries the given signal thresholds, or none. +func seedAssessmentAttemptHTTPBankWithSignals(ctx context.Context, t *testing.T, pool *pgxpool.Pool, signals *domain.AssessmentSignalPolicy) { + t.Helper() + seedAssessmentAttemptHTTPBankFrom(ctx, t, pool, signals, loadDemoBundleFile(t)) +} + +// seedAssessmentAttemptHTTPBankFrom seeds the attempt fixture bank from the +// families of the given bundle, which every fixture category repeats in turn. +func seedAssessmentAttemptHTTPBankFrom( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + signals *domain.AssessmentSignalPolicy, + sourceBundle assessment.Bundle, +) { + t.Helper() + transactor := postgresadapter.NewTransactor(pool) + bank := assessment.NewBank(transactor) + store := postgresadapter.NewAssessmentBankStore(pool) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now) + fixture := assessmentFixture{ + ctx: ctx, pool: pool, store: store, transactor: transactor, + bank: bank, publisher: publisher, demoBundle: sourceBundle, + } + productPolicy := integrationPolicy(11) + productPolicy.Assessment.MaxAttemptsPerWindow = 1 + demoAttemptPolicy := domain.DemoProductPolicyV2().Assessment + productPolicy.Assessment.Attempt = demoAttemptPolicy.Attempt + productPolicy.Assessment.Training = demoAttemptPolicy.Training + productPolicy.Assessment.Attempt.MaxSessions = 1 + productPolicy.Assessment.Attempt.IdleTimeoutSeconds = 60 + productPolicy.Assessment.Signals = signals + policyVersion, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, Policy: productPolicy, + }) + if err != nil { + t.Fatalf("Publish(attempt fixture policy) error = %v", err) + } + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + bundle := fixture.reviewedBundle(int(required)) + bundle.Name = "assessment-attempt-backend-fixture" + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle(backend attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, bundle) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("backend"), domain.SpecializationBackend, domain.GradeJunior) + + frontend := bundle + frontend.Name = "assessment-attempt-frontend-fixture" + frontend.Category = "frontend" + frontend.Families = append([]assessment.BundleFamily(nil), bundle.Families...) + for index := range frontend.Families { + frontend.Families[index].Key = fmt.Sprintf("attempt-frontend-%02d", index+1) + frontend.Families[index].Specialization = "frontend" + } + if _, err := bank.ImportBundle(ctx, frontend); err != nil { + t.Fatalf("ImportBundle(frontend attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, frontend) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("frontend"), domain.SpecializationFrontend, domain.GradeJunior) + + backendIntern := fixture.reviewedBundle(int(required)) + backendIntern.Name = "assessment-attempt-backend-intern-fixture" + backendIntern.Category = "backend-intern" + for index := range backendIntern.Families { + backendIntern.Families[index].Key = fmt.Sprintf("attempt-backend-intern-%02d", index+1) + } + if _, err := bank.ImportBundle(ctx, backendIntern); err != nil { + t.Fatalf("ImportBundle(backend intern attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, backendIntern) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("backend-intern"), domain.SpecializationBackend, domain.GradeIntern) + + frontendIntern := fixture.reviewedBundle(int(required)) + frontendIntern.Name = "assessment-attempt-frontend-intern-fixture" + frontendIntern.Category = "frontend-intern" + for index := range frontendIntern.Families { + frontendIntern.Families[index].Key = fmt.Sprintf("attempt-frontend-intern-%02d", index+1) + frontendIntern.Families[index].Specialization = "frontend" + } + if _, err := bank.ImportBundle(ctx, frontendIntern); err != nil { + t.Fatalf("ImportBundle(frontend intern attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, frontendIntern) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), domain.AssessmentCategory("frontend-intern"), domain.SpecializationFrontend, domain.GradeIntern) + + training := fixture.reviewedBundle(int(policyVersion.Policy().Assessment.Training.DemoExpressItemCount)) + training.Name = "assessment-attempt-training-fixture" + training.Category = "training-attempts" + for index := range training.Families { + training.Families[index].Key = fmt.Sprintf("attempt-training-%02d", index+1) + } + if _, err := bank.ImportBundle(ctx, training); err != nil { + t.Fatalf("ImportBundle(training attempt fixture) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, training) + seedAssessmentAttemptTrainingBinding(ctx, t, pool, policyVersion.ID().UUID(), training.Category, len(training.Families)) +} + +func publishAssessmentAttemptFixtureFamilies(ctx context.Context, t *testing.T, bank *assessment.Bank, bundle assessment.Bundle) { + t.Helper() + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } +} + +func openAssessmentAttemptFixtureCategory( + ctx context.Context, + t *testing.T, + bank *assessment.Bank, + policyID domain.PolicyVersionID, + category domain.AssessmentCategory, + specialization domain.SpecializationCode, + grade domain.GradeCode, +) { + t.Helper() + metadata, err := domain.NewAssessmentCategoryCatalogMetadata(specialization, grade, []domain.TaskLanguageCode{domain.TaskLanguageGo}) + if err != nil { + t.Fatalf("NewAssessmentCategoryCatalogMetadata(%s) error = %v", specialization, err) + } + if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: category, GradingPolicyID: policyID, OpenedBy: fixtureOpener, CatalogMetadata: &metadata, + }); err != nil { + t.Fatalf("OpenCategory(%s) error = %v", category, err) + } +} + +func seedAssessmentAttemptTrainingBinding( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + policyID uuid.UUID, + category string, + itemCount int, +) { + t.Helper() + type manifestEntry struct { + FamilyKey string `json:"family_key"` + Version int32 `json:"version"` + ContentSHA256 string `json:"content_sha256"` + } + type familyRecord struct { + ID uuid.UUID + Entry manifestEntry + Hash []byte + } + rows, err := pool.Query(ctx, ` + SELECT id, family_key, version, content_sha256 + FROM assessment_families + WHERE category=$1 AND lifecycle='published' + ORDER BY family_key, version`, category) + if err != nil { + t.Fatalf("read published training family fixture: %v", err) + } + var families []familyRecord + for rows.Next() { + var family familyRecord + if err := rows.Scan(&family.ID, &family.Entry.FamilyKey, &family.Entry.Version, &family.Hash); err != nil { + rows.Close() + t.Fatalf("scan training family fixture: %v", err) + } + family.Entry.ContentSHA256 = hex.EncodeToString(family.Hash) + families = append(families, family) + } + if err := rows.Err(); err != nil { + rows.Close() + t.Fatalf("iterate training family fixture: %v", err) + } + rows.Close() + if len(families) != itemCount { + t.Fatalf("published training family count = %d, want %d", len(families), itemCount) + } + manifest, err := json.Marshal(func() []manifestEntry { + entries := make([]manifestEntry, len(families)) + for index := range families { + entries[index] = families[index].Entry + } + return entries + }()) + if err != nil { + t.Fatalf("marshal training family manifest: %v", err) + } + canonical := []byte("lincodex.assessment.category-manifest.v1\x00") + for _, family := range families { + key := []byte(family.Entry.FamilyKey) + if len(key) > 64 || family.Entry.Version < 1 || len(family.Hash) != sha256.Size { + t.Fatalf("training family manifest entry is out of range") + } + canonical = binary.BigEndian.AppendUint32(canonical, uint32(len(key))) + canonical = append(canonical, key...) + canonical = binary.BigEndian.AppendUint32(canonical, uint32(family.Entry.Version)) + canonical = append(canonical, family.Hash...) + } + manifestHash := sha256.Sum256(canonical) + bindingID := uuid.New() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin reviewed training binding fixture: %v", err) + } + defer tx.Rollback(ctx) + if _, err := tx.Exec(ctx, ` + INSERT INTO assessment_training_bank_bindings ( + id, category, product_policy_version_id, item_count, manifest_sha256, family_manifest, reviewed_by, created_at + ) VALUES ($1,$2,$3,$4,$5,$6::jsonb,'operator:fixture-reviewer',clock_timestamp())`, + bindingID, category, policyID, itemCount, manifestHash[:], manifest); err != nil { + t.Fatalf("insert reviewed training binding fixture: %v", err) + } + for index, family := range families { + if _, err := tx.Exec(ctx, ` + INSERT INTO assessment_training_bank_binding_families ( + binding_id, ordinal, family_id, family_key, family_version, content_sha256 + ) VALUES ($1,$2,$3,$4,$5,$6)`, bindingID, index+1, family.ID, family.Entry.FamilyKey, family.Entry.Version, family.Hash); err != nil { + t.Fatalf("insert reviewed training family member %s: %v", family.Entry.FamilyKey, err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit reviewed training binding fixture: %v", err) + } + _, err = pool.Exec(ctx, ` + INSERT INTO assessment_category_openings ( + id, category, policy_version_id, opened_by, required_families, published_families, opened_at + ) VALUES (gen_random_uuid(), $1, $2, 'operator:fixture-opener', 1, $3, clock_timestamp())`, category, policyID, itemCount) + assertPgError(t, "open a training-only category for real assessments", err, "23514", "assessment_training_category_is_disjoint") +} + +func assessmentAttemptCreateBody(t *testing.T, specialization string) string { + t.Helper() + return assessmentAttemptCreateBodyWithGrade(t, specialization, "junior") +} + +func assessmentAttemptCreateBodyWithGrade(t *testing.T, specialization, grade string) string { + t.Helper() + body, err := json.Marshal(map[string]string{ + "kind": "root", "specialization": specialization, "target_grade": grade, "task_language": "go", + }) + if err != nil { + t.Fatalf("marshal assessment create body: %v", err) + } + return string(body) +} + +func assessmentAttemptCorrectiveBody(t *testing.T, specialization, grade string, rootID uuid.UUID) string { + t.Helper() + body, err := json.Marshal(map[string]string{ + "kind": "corrective", "specialization": specialization, "target_grade": grade, + "task_language": "go", "root_attempt_id": rootID.String(), + }) + if err != nil { + t.Fatalf("marshal corrective attempt body: %v", err) + } + return string(body) +} + +func assessmentAttemptQuestionnaireRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + cookie, csrf, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "specializations": []any{ + map[string]any{"specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, "stack": []string{}, "experience": nil}, + map[string]any{"specialization": "frontend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, "stack": []string{}, "experience": nil}, + }, + "work_context": map[string]any{"work_formats": []string{"remote"}}, + }) + if err != nil { + t.Fatalf("marshal attempt questionnaire: %v", err) + } + return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body), + sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr) +} + +func grantCurrentAttemptConsent( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + cookie *http.Cookie, + csrf, remoteAddr string, +) { + t.Helper() + textResponse := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/consent-texts/c3", "", + "", cookie.Value, "", "", remoteAddr) + var current struct { + TextVersion string `json:"text_version"` + } + if textResponse.Code != http.StatusOK || json.Unmarshal(textResponse.Body.Bytes(), ¤t) != nil || current.TextVersion == "" { + t.Fatalf("read current C3 text = %d %s", textResponse.Code, textResponse.Body.String()) + } + grant := consentGrantHTTP(t, harness.sessionHTTPHarness, cookie, csrf, "c3", current.TextVersion, sessionHTTPTestOrigin) + if grant.Code != http.StatusOK { + t.Fatalf("grant current C3 = %d %s", grant.Code, grant.Body.String()) + } +} + +func assessmentAttemptHTTPRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string, +) *httptest.ResponseRecorder { + return assessmentAttemptHTTPRequestWithTimeout(t, harness, method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr, 20*time.Second) +} + +func assessmentAttemptHTTPRequestWithTimeout( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string, + timeout time.Duration, +) *httptest.ResponseRecorder { + t.Helper() + return assessmentAttemptHTTPRequestWithHeaders(t, harness, method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr, timeout, nil) +} + +// assessmentAttemptHTTPRequestWithHeaders is the request of a candidate with +// extra headers, such as the page identifier or a User-Agent. +func assessmentAttemptHTTPRequestWithHeaders( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string, + timeout time.Duration, + headers map[string]string, +) *httptest.ResponseRecorder { + t.Helper() + requestContext, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + request := httptest.NewRequest(method, path, strings.NewReader(body)).WithContext(requestContext) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if origin != "" { + request.Header.Set("Origin", origin) + } + if cookie != "" { + request.Header.Set("Cookie", "__Host-lincodex_session="+cookie) + } + if csrf != "" { + request.Header.Set("X-CSRF-Token", csrf) + } + if idempotencyKey != "" { + request.Header.Set("Idempotency-Key", idempotencyKey) + } + for name, value := range headers { + request.Header.Set(name, value) + } + request.RemoteAddr = remoteAddr + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return recorder +} + +func assertAttemptCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want int64) { + t.Helper() + var got int64 + if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts").Scan(&got); err != nil { + t.Fatalf("count assessment attempts: %v", err) + } + if got != want { + t.Fatalf("assessment attempt rows = %d, want %d", got, want) + } +} + +func readAttemptChainTiming(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) (time.Time, time.Time) { + t.Helper() + var createdAt, deadline time.Time + if err := pool.QueryRow(ctx, `SELECT created_at, chain_deadline FROM assessment_attempts WHERE id=$1`, attemptID).Scan(&createdAt, &deadline); err != nil { + t.Fatalf("read assessment root chain deadline: %v", err) + } + return createdAt.UTC(), deadline.UTC() +} + +func terminalizeAttempt(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + command, err := pool.Exec(ctx, ` + WITH stamp AS ( + SELECT GREATEST(clock_timestamp(), last_activity_at) AS at + FROM assessment_attempts WHERE id=$1 + ) + UPDATE assessment_attempts AS attempt + SET state='completed', outcome='not_confirmed', ended_at=stamp.at, + updated_at=stamp.at, version=attempt.version+1 + FROM stamp + WHERE attempt.id=$1 AND attempt.state='in_progress'`, attemptID) + if err != nil || command.RowsAffected() != 1 { + t.Fatalf("terminalize assessment attempt = %d rows, error %v", command.RowsAffected(), err) + } +} + +func assertAttemptPinAndItemRowsAreImmutable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + _, err := pool.Exec(ctx, ` + UPDATE assessment_attempts + SET product_policy_version=product_policy_version+1, version=version+1, updated_at=clock_timestamp() + WHERE id=$1`, attemptID) + assertPgError(t, "change immutable attempt policy pin", err, "23000", "assessment_attempt_pins_immutable") + _, err = pool.Exec(ctx, ` + UPDATE assessment_attempt_items + SET variant=variant || '{"changed":true}'::jsonb + WHERE attempt_id=$1 AND ordinal=1`, attemptID) + assertPgError(t, "change immutable attempt item variant", err, "23000", "assessment_attempt_item_immutable") + _, err = pool.Exec(ctx, `DELETE FROM assessment_attempt_items WHERE attempt_id=$1 AND ordinal=1`, attemptID) + assertPgError(t, "delete immutable attempt item", err, "23000", "assessment_attempt_item_delete_forbidden") +} + +func assertAssessmentAttemptReplay(t *testing.T, key string, original, replay *httptest.ResponseRecorder) { + t.Helper() + if original.Code != replay.Code { + t.Fatalf("create replay %s status = %d, want stored status %d", key, replay.Code, original.Code) + } + if original.Code == http.StatusCreated { + if replay.Body.String() != original.Body.String() { + t.Fatalf("created attempt replay %s body differs from its immutable response", key) + } + return + } + type stableProblem struct { + Type string `json:"type"` + Title string `json:"title"` + Status int `json:"status"` + Code string `json:"code"` + Detail string `json:"detail"` + } + var originalProblem, replayProblem stableProblem + if err := json.Unmarshal(original.Body.Bytes(), &originalProblem); err != nil { + t.Fatalf("decode original conflict response: %v", err) + } + if err := json.Unmarshal(replay.Body.Bytes(), &replayProblem); err != nil { + t.Fatalf("decode replay conflict response: %v", err) + } + if originalProblem != replayProblem || replayProblem.Code != "state_conflict" { + t.Fatalf("create replay %s stable problem = %+v, want %+v", key, replayProblem, originalProblem) + } +} + +type assessmentAttemptStoredState struct { + Version int64 + Sessions int32 + State string +} + +func readAttemptStoredState(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) assessmentAttemptStoredState { + t.Helper() + var state assessmentAttemptStoredState + err := pool.QueryRow(ctx, ` + SELECT version, sessions_used, state + FROM assessment_attempts WHERE id = $1`, attemptID).Scan(&state.Version, &state.Sessions, &state.State) + if err != nil { + t.Fatalf("read stored assessment attempt state: %v", err) + } + return state +} + +func waitForAssessmentAttemptRowLock(t *testing.T, ctx context.Context, pool *pgxpool.Pool, blockingPID int32) { + t.Helper() + deadline := time.Now().Add(20 * time.Second) + for time.Now().Before(deadline) { + var waiting int64 + err := pool.QueryRow(ctx, ` + SELECT count(*) + FROM pg_stat_activity + WHERE wait_event_type='Lock' + AND $1 = ANY(pg_blocking_pids(pid)) + AND query ILIKE '%assessment_attempts%'`, blockingPID).Scan(&waiting) + if err != nil { + t.Fatalf("inspect blocked attempt session request: %v", err) + } + if waiting > 0 { + return + } + select { + case <-ctx.Done(): + t.Fatalf("wait for attempt row lock: %v", ctx.Err()) + case <-time.After(50 * time.Millisecond): + } + } + t.Fatal("session command never waited on the locked assessment_attempts row") +} + +func waitForAttemptIdleDeadline(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + deadline := time.Now().Add(90 * time.Second) + for time.Now().Before(deadline) { + var expired bool + err := pool.QueryRow(ctx, ` + SELECT last_activity_at + idle_timeout_seconds * interval '1 second' <= clock_timestamp() + FROM assessment_attempts WHERE id=$1`, attemptID).Scan(&expired) + if err != nil { + t.Fatalf("read attempt idle deadline: %v", err) + } + if expired { + return + } + select { + case <-ctx.Done(): + t.Fatalf("wait for attempt idle deadline: %v", ctx.Err()) + case <-time.After(100 * time.Millisecond): + } + } + t.Fatal("assessment attempt idle deadline did not pass during the row lock") +} + +// TestDemoExpressActiveAttemptOverHTTP covers an express run the candidate +// leaves unfinished. The availability read has no express field by contract, +// so the candidate keeps the identifier from the 201 response or replays the +// Idempotency-Key of that creation. A new start is refused while the run is +// active and succeeds once the run's own deadline has passed. +func TestDemoExpressActiveAttemptOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "express-resume@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.201:1234") + body := `{"kind":"demo_express"}` + + first := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-first", "192.0.2.202:1234") + if first.Code != http.StatusCreated { + t.Fatalf("create express = %d %s", first.Code, first.Body.String()) + } + firstID := assessmentAttemptIDOf(t, first) + + // Another key is refused while the first run is active, and creates nothing. + second := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-second", "192.0.2.203:1234") + requireSessionProblem(t, second, http.StatusConflict, "state_conflict") + assertAttemptCount(t, ctx, harness.pool, 1) + + // The creation key replays the stored 201, which returns the identifier of + // the active run. + replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-first", "192.0.2.204:1234") + assertAssessmentAttemptReplay(t, "express-first while active", first, replay) + + active := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+firstID.String(), "", + "", cookie.Value, "", "", "192.0.2.205:1234") + if state := assessmentAttemptStateOf(t, active); active.Code != http.StatusOK || state != "in_progress" { + t.Fatalf("read active express = %d state %q, want 200 in_progress", active.Code, state) + } + + // The run ends at its own deadline. The fixture moves the run's clock fields + // back instead of waiting for the policy duration, and the next start commits + // the due transition. + ageDemoExpressAttempt(t, ctx, harness.pool, firstID, 10*time.Minute) + third := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", body, + sessionHTTPTestOrigin, cookie.Value, csrf, "express-third", "192.0.2.206:1234") + if third.Code != http.StatusCreated { + t.Fatalf("create express after the deadline = %d %s", third.Code, third.Body.String()) + } + assertAttemptCount(t, ctx, harness.pool, 2) + + ended := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+firstID.String(), "", + "", cookie.Value, "", "", "192.0.2.207:1234") + if state := assessmentAttemptStateOf(t, ended); ended.Code != http.StatusOK || state != "expired" { + t.Fatalf("read the first express after its deadline = %d state %q, want 200 expired", ended.Code, state) + } + result := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+firstID.String()+"/result", "", + "", cookie.Value, "", "", "192.0.2.208:1234") + var summary struct { + Outcome string `json:"outcome"` + Summary string `json:"summary"` + } + if err := json.Unmarshal(result.Body.Bytes(), &summary); err != nil || result.Code != http.StatusOK || + summary.Outcome != "demonstration" || summary.Summary != "Тренировочный запуск завершился до окончания: он не оценивает и не подтверждает уровень." { + t.Fatalf("result of the expired express = %d %s, decode error %v", result.Code, result.Body.String(), err) + } +} + +// assessmentAttemptIDOf reads the identifier of an attempt response. +func assessmentAttemptIDOf(t *testing.T, response *httptest.ResponseRecorder) uuid.UUID { + t.Helper() + var snapshot struct { + ID uuid.UUID `json:"id"` + } + if err := json.Unmarshal(response.Body.Bytes(), &snapshot); err != nil || snapshot.ID == uuid.Nil { + t.Fatalf("attempt response %d %s has no identifier: %v", response.Code, response.Body.String(), err) + } + return snapshot.ID +} + +// assessmentAttemptStateOf reads the state of an attempt response. +func assessmentAttemptStateOf(t *testing.T, response *httptest.ResponseRecorder) string { + t.Helper() + var snapshot struct { + State string `json:"state"` + } + if err := json.Unmarshal(response.Body.Bytes(), &snapshot); err != nil { + t.Fatalf("decode attempt response %d %s: %v", response.Code, response.Body.String(), err) + } + return snapshot.State +} + +// ageDemoExpressAttempt moves an attempt and its clock fields back by by, with +// the triggers off for this one transaction, so that its deadline has passed. +// The shift keeps every ordering constraint because all fields move together. +func ageDemoExpressAttempt(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID, by time.Duration) { + t.Helper() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin express aging fixture: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `SET LOCAL session_replication_role = replica`); err != nil { + t.Fatalf("disable triggers for the express aging fixture: %v", err) + } + shift := fmt.Sprintf("%d seconds", int64(by.Seconds())) + command, err := tx.Exec(ctx, ` + UPDATE assessment_attempts + SET created_at = created_at - $2::interval, updated_at = updated_at - $2::interval, + expires_at = expires_at - $2::interval, session_started_at = session_started_at - $2::interval, + last_activity_at = last_activity_at - $2::interval + WHERE id = $1 AND kind = 'demo_express'`, attemptID, shift) + if err != nil || command.RowsAffected() != 1 { + t.Fatalf("age express attempt = %d rows, error %v", command.RowsAffected(), err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit express aging fixture: %v", err) + } +} diff --git a/backend/integration_test/assessment_availability_http_test.go b/backend/integration_test/assessment_availability_http_test.go new file mode 100644 index 0000000..80e198b --- /dev/null +++ b/backend/integration_test/assessment_availability_http_test.go @@ -0,0 +1,509 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + assessmentpolicy "lincodex/backend/internal/usecase/policy" +) + +type assessmentAvailabilityHTTPGrade struct { + Grade string `json:"grade"` + Status string `json:"status"` + Mode *string `json:"mode"` + TimeLimitSeconds *int32 `json:"time_limit_seconds"` + MaxSessions *int32 `json:"max_sessions"` + MaxItems *int32 `json:"max_items"` + PracticeRequired *bool `json:"practice_required"` +} + +type assessmentAvailabilityHTTPSpecialization struct { + Specialization string `json:"specialization"` + ActiveAttempt *uuid.UUID `json:"active_attempt_id"` + Grades []assessmentAvailabilityHTTPGrade `json:"grades"` +} + +type assessmentAvailabilityHTTPProjection struct { + Specializations []assessmentAvailabilityHTTPSpecialization `json:"specializations"` +} + +func TestAssessmentAvailabilityHTTPIsCandidateScopedAndReadOnly(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-http-candidate@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.50:1234") + + unauthenticated := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", "", "", "", "203.0.113.51:1234") + requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated") + employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "availability-http-employer@example.test", passwordHash) + employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "203.0.113.52:1234") + employerRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-availability", "", "", employerCookie.Value, "", "", "203.0.113.53:1234") + requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden") + + path := "/api/v1/me/assessment-availability" + emptyRead := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.54:1234") + var emptyProjection struct { + Specializations []json.RawMessage `json:"specializations"` + } + if emptyRead.Code != http.StatusOK || emptyRead.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(emptyRead.Body.Bytes(), &emptyProjection) != nil || emptyProjection.Specializations == nil || len(emptyProjection.Specializations) != 0 { + t.Fatalf("availability before questionnaire = %d %s, Cache-Control=%q, want empty candidate projection", + emptyRead.Code, emptyRead.Body.String(), emptyRead.Header().Get("Cache-Control")) + } + if response := assessmentAttemptQuestionnaireRequest(t, harness, candidateCookie.Value, candidateCSRF, "203.0.113.55:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, candidateCookie, candidateCSRF, "203.0.113.56:1234") + + available := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.57:1234") + var initial assessmentAvailabilityHTTPProjection + if available.Code != http.StatusOK || available.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(available.Body.Bytes(), &initial) != nil || len(initial.Specializations) != 2 { + t.Fatalf("availability after questionnaire = %d %s, Cache-Control=%q, want both saved specializations", + available.Code, available.Body.String(), available.Header().Get("Cache-Control")) + } + backend := findAssessmentAvailabilitySpecialization(t, initial, "backend") + for _, target := range []string{"intern", "junior"} { + grade := findAssessmentAvailabilityGrade(t, backend, target) + if grade.Status != "available" || grade.Mode == nil || *grade.Mode != "demo_basic" || + grade.TimeLimitSeconds == nil || *grade.TimeLimitSeconds != 72*60*60 || + grade.MaxSessions == nil || *grade.MaxSessions != 1 || grade.MaxItems == nil || *grade.MaxItems != 13 || + grade.PracticeRequired == nil || *grade.PracticeRequired { + t.Fatalf("backend %s availability = %+v, response=%s, want the published demo_basic start limits", + target, grade, available.Body.String()) + } + } + + // The questionnaire self-assesses junior, while this request selects the + // offered intern bank. The stored questionnaire grade is not a target gate. + created := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, "backend", "intern"), sessionHTTPTestOrigin, + candidateCookie.Value, candidateCSRF, "availability-create-different-grade", "203.0.113.58:1234") + var activeAttempt assessmentAnswerHTTPAttempt + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &activeAttempt) != nil || activeAttempt.ID == uuid.Nil { + t.Fatalf("create attempt at offered grade different from self-assessment = %d %s", created.Code, created.Body.String()) + } + + // Re-login immediately before the read-only measurement so the session + // activity coalescing window cannot obscure a write caused by the GET. + candidateCookie, candidateCSRF = loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.59:1234") + token, err := domain.ParseSecretToken(candidateCookie.Value) + if err != nil { + t.Fatalf("parse synthetic session token for state comparison: %v", err) + } + tokenHash := token.Hash() + type availabilityReadState struct { + attemptVersion int64 + sessionsUsed int32 + updatedAt time.Time + sessionSeenAt time.Time + attemptRows int64 + itemRows int64 + answeredItems int64 + idempotency int64 + } + readAvailabilityState := func() availabilityReadState { + t.Helper() + var state availabilityReadState + if err := harness.pool.QueryRow(ctx, "SELECT version, sessions_used, updated_at FROM assessment_attempts WHERE id=$1", activeAttempt.ID). + Scan(&state.attemptVersion, &state.sessionsUsed, &state.updatedAt); err != nil { + t.Fatalf("read attempt state before/after availability: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT last_seen_at FROM sessions WHERE token_hash=$1", tokenHash[:]).Scan(&state.sessionSeenAt); err != nil { + t.Fatalf("read session activity before/after availability: %v", err) + } + if err := harness.pool.QueryRow(ctx, ` + SELECT (SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'), + (SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2), + (SELECT count(*) FROM assessment_attempt_items WHERE attempt_id=$2 AND answered_at IS NOT NULL), + (SELECT count(*) FROM idempotency_records)`, candidate.ID, activeAttempt.ID). + Scan(&state.attemptRows, &state.itemRows, &state.answeredItems, &state.idempotency); err != nil { + t.Fatalf("read attempt/quota state before/after availability: %v", err) + } + return state + } + before := readAvailabilityState() + for index := 0; index < 2; index++ { + response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", candidateCookie.Value, "", "", "203.0.113.60:1234") + var current assessmentAvailabilityHTTPProjection + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(response.Body.Bytes(), ¤t) != nil { + t.Fatalf("repeated availability GET %d = %d %s, Cache-Control=%q", index+1, response.Code, + response.Body.String(), response.Header().Get("Cache-Control")) + } + backend = findAssessmentAvailabilitySpecialization(t, current, "backend") + if backend.ActiveAttempt == nil || *backend.ActiveAttempt != activeAttempt.ID { + t.Fatalf("repeated availability GET %d active attempt = %v, want %s", index+1, backend.ActiveAttempt, activeAttempt.ID) + } + for _, grade := range backend.Grades { + if grade.Status != "active_attempt" { + t.Fatalf("backend grade %s status = %q while an attempt is active", grade.Grade, grade.Status) + } + } + } + after := readAvailabilityState() + if before.attemptVersion != after.attemptVersion || before.sessionsUsed != after.sessionsUsed || + !before.updatedAt.Equal(after.updatedAt) || !before.sessionSeenAt.Equal(after.sessionSeenAt) || + before.attemptRows != after.attemptRows || before.itemRows != after.itemRows || + before.answeredItems != after.answeredItems || before.idempotency != after.idempotency { + t.Fatalf("availability GET wrote state: before=%+v after=%+v", before, after) + } + + adaptive := domain.DemoProductPolicyV2() + adaptive.Assessment.Calibration = domain.AssessmentCalibrationCalibrated + adaptive.Assessment.Attempt.RealMode = domain.AssessmentRealModeAdaptive + adaptive.Assessment.Attempt.BasicPassMark = 0 + publisher := assessmentpolicy.NewPublisher(postgres.NewPolicyStore(harness.pool).Policies(), time.Now) + adaptiveVersion, err := publisher.Publish(ctx, assessmentpolicy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: adaptive, + }) + if err != nil { + t.Fatalf("publish explicit adaptive policy for unavailable-mode check: %v", err) + } + adaptiveBank := assessment.NewBank(postgres.NewTransactor(harness.pool)) + adaptiveFixture := assessmentFixture{ + ctx: ctx, pool: harness.pool, store: postgres.NewAssessmentBankStore(harness.pool), + transactor: postgres.NewTransactor(harness.pool), bank: adaptiveBank, + demoBundle: loadDemoBundleFile(t), + } + adaptiveRequired, err := domain.RequiredPublishedAssessmentFamilies(adaptiveVersion.Policy()) + if err != nil { + t.Fatalf("read adaptive policy family requirement: %v", err) + } + var publishedBackendFamilies int32 + if err := harness.pool.QueryRow(ctx, ` + SELECT count(DISTINCT family_key)::integer + FROM assessment_families + WHERE category='backend' AND lifecycle='published' AND review_status='approved'`).Scan(&publishedBackendFamilies); err != nil { + t.Fatalf("count current backend families for adaptive opening: %v", err) + } + if publishedBackendFamilies < adaptiveRequired { + adaptiveBundle := adaptiveFixture.reviewedBundle(int(adaptiveRequired - publishedBackendFamilies)) + adaptiveBundle.Name = "availability-adaptive-backend" + adaptiveBundle.Category = "backend" + for index := range adaptiveBundle.Families { + adaptiveBundle.Families[index].Key = fmt.Sprintf("availability-adaptive-backend-%02d", index+1) + adaptiveBundle.Families[index].Specialization = string(domain.SpecializationBackend) + } + if _, err := adaptiveBank.ImportBundle(ctx, adaptiveBundle); err != nil { + t.Fatalf("import additional reviewed backend families for adaptive opening: %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, adaptiveBank, adaptiveBundle) + } + openAssessmentAttemptFixtureCategory( + ctx, t, adaptiveBank, adaptiveVersion.ID(), domain.AssessmentCategory("backend"), + domain.SpecializationBackend, domain.GradeJunior, + ) + adaptiveCandidate := createSessionHTTPUser( + ctx, t, harness.sessionHTTPHarness, "availability-adaptive-candidate@example.test", passwordHash, true, + ) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", adaptiveCandidate.ID); err != nil { + t.Fatalf("set adaptive candidate onboarding step: %v", err) + } + adaptiveCookie, adaptiveCSRF := loginConsentHTTP( + t, harness.sessionHTTPHarness, adaptiveCandidate.Email.Address(), "203.0.113.63:1234", + ) + if response := assessmentAvailabilityBackendQuestionnaireRequest(t, harness, adaptiveCookie.Value, adaptiveCSRF, "203.0.113.64:1234"); response.Code != http.StatusOK { + t.Fatalf("save adaptive candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, adaptiveCookie, adaptiveCSRF, "203.0.113.65:1234") + unsupported := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", adaptiveCookie.Value, "", "", "203.0.113.66:1234") + requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented") + var rootCountBefore, idempotencyBefore int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID). + Scan(&rootCountBefore); err != nil { + t.Fatalf("read adaptive candidate root attempt count before denied POST: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyBefore); err != nil { + t.Fatalf("read idempotency count before denied adaptive POST: %v", err) + } + adaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin, + adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.67:1234") + requireSessionProblem(t, adaptiveCreate, http.StatusConflict, "state_conflict") + var rootCountAfter int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id=$1 AND kind='root'", adaptiveCandidate.ID). + Scan(&rootCountAfter); err != nil { + t.Fatalf("read root attempts after unsupported adaptive create: %v", err) + } + var idempotencyAfter int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfter); err != nil { + t.Fatalf("read idempotency count after denied adaptive POST: %v", err) + } + if rootCountAfter != rootCountBefore { + t.Fatalf("unsupported adaptive create changed root attempt count from %d to %d", rootCountBefore, rootCountAfter) + } + if idempotencyAfter != idempotencyBefore+1 { + t.Fatalf("unsupported adaptive create idempotency row count = %d, want one immutable 409 outcome after %d", idempotencyAfter, idempotencyBefore) + } + replayedAdaptiveCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, "backend", "junior"), sessionHTTPTestOrigin, + adaptiveCookie.Value, adaptiveCSRF, "availability-create-adaptive-denied", "203.0.113.68:1234") + requireSessionProblem(t, replayedAdaptiveCreate, http.StatusConflict, "state_conflict") + var idempotencyAfterReplay int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records").Scan(&idempotencyAfterReplay); err != nil { + t.Fatalf("read idempotency count after adaptive 409 replay: %v", err) + } + if idempotencyAfterReplay != idempotencyAfter { + t.Fatalf("adaptive 409 replay added idempotency rows: before replay=%d after=%d", idempotencyAfter, idempotencyAfterReplay) + } +} + +func assessmentAvailabilityBackendQuestionnaireRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + cookie, csrf, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "specializations": []any{ + map[string]any{ + "specialization": "backend", "self_assessed_grade": "junior", "task_languages": []string{"go"}, + "stack": []string{}, "experience": nil, + }, + }, + "work_context": map[string]any{"work_formats": []string{"remote"}}, + }) + if err != nil { + t.Fatalf("marshal backend-only adaptive questionnaire: %v", err) + } + return assessmentAttemptHTTPRequest(t, harness, http.MethodPut, "/api/v1/me/questionnaire", string(body), + sessionHTTPTestOrigin, cookie, csrf, "", remoteAddr) +} + +func createAssessmentAvailabilityEmployer( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, + RegisteredAt: harness.clock.Now().Truncate(time.Microsecond), + }) + if err != nil { + t.Fatalf("NewUser(employer) error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create synthetic employer: %v", err) + } + verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, + harness.clock.Now().Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(employer) error = %v", err) + } + return verified +} + +func findAssessmentAvailabilitySpecialization( + t *testing.T, + availability assessmentAvailabilityHTTPProjection, + want string, +) assessmentAvailabilityHTTPSpecialization { + t.Helper() + for _, specialization := range availability.Specializations { + if specialization.Specialization == want { + return specialization + } + } + t.Fatalf("availability does not contain specialization %q", want) + return assessmentAvailabilityHTTPSpecialization{} +} + +func findAssessmentAvailabilityGrade( + t *testing.T, + specialization assessmentAvailabilityHTTPSpecialization, + want string, +) assessmentAvailabilityHTTPGrade { + t.Helper() + for _, grade := range specialization.Grades { + if grade.Grade == want { + return grade + } + } + t.Fatalf("availability for %q does not contain grade %q", specialization.Specialization, want) + return assessmentAvailabilityHTTPGrade{} +} + +func TestAssessmentDisclosedFamilyCutoffUsesItemDisclosureTime(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "availability-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.40:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.41:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.42:1234") + + create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, + "availability-disclosure-create", "203.0.113.43:1234") + var attempt assessmentAnswerHTTPAttempt + if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String()) + } + items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) + if len(items) < 3 { + t.Fatalf("frozen item count = %d, want at least three items", len(items)) + } + var createdAt time.Time + if err := harness.pool.QueryRow(ctx, "SELECT created_at FROM assessment_attempts WHERE id=$1", attempt.ID).Scan(&createdAt); err != nil { + t.Fatalf("read attempt creation time: %v", err) + } + since := createdAt.UTC().Add(time.Microsecond) + + firstAnswer := assessmentAnswerHTTPBodyWithCorrectness(t, attempt.Version, items[0], false) + accepted := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(firstAnswer), + sessionHTTPTestOrigin, cookie.Value, csrf, "availability-disclosure-answer", "203.0.113.44:1234") + if accepted.Code != http.StatusOK { + t.Fatalf("answer first item = %d %s", accepted.Code, accepted.Body.String()) + } + _, answeredAt := readAssessmentAnswerHTTPItem(t, ctx, harness, attempt.ID, items[0].ID) + if !answeredAt.After(since) { + t.Fatalf("first answer timestamp %s must be after cutoff %s to establish distinct disclosure times", answeredAt, since) + } + + familyKey := func(itemID uuid.UUID) domain.AssessmentFamilyKey { + t.Helper() + var stored string + if err := harness.pool.QueryRow(ctx, "SELECT family_key FROM assessment_attempt_items WHERE attempt_id=$1 AND id=$2", attempt.ID, itemID).Scan(&stored); err != nil { + t.Fatalf("read frozen item family key: %v", err) + } + key, err := domain.ParseAssessmentFamilyKey(stored) + if err != nil { + t.Fatalf("parse frozen item family key: %v", err) + } + return key + } + firstKey, secondKey, thirdKey := familyKey(items[0].ID), familyKey(items[1].ID), familyKey(items[2].ID) + var disclosed []domain.AssessmentFamilyKey + transactor := postgres.NewTransactor(harness.pool) + if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error { + var readErr error + disclosed, readErr = unit.AssessmentAttempts().ListDisclosedFamilyKeys(txctx, candidate.ID, since) + return readErr + }); err != nil { + t.Fatalf("read disclosed family keys after the rolling cutoff: %v", err) + } + contains := func(want domain.AssessmentFamilyKey) bool { + for _, key := range disclosed { + if key == want { + return true + } + } + return false + } + if contains(firstKey) || !contains(secondKey) || contains(thirdKey) { + t.Fatalf("disclosed families = %v; want first excluded, second included, and future third excluded", disclosed) + } + + var countBefore int32 + var latestBefore bool + if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error { + var readErr error + countBefore, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second)) + if readErr != nil { + return readErr + } + _, latestBefore, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization( + txctx, candidate.ID, domain.SpecializationBackend, nil, + ) + return readErr + }); err != nil { + t.Fatalf("read eligible root quota and retry history: %v", err) + } + if countBefore != 1 || !latestBefore { + t.Fatalf("eligible root before platform failure = count %d/latest %v, want 1/true", countBefore, latestBefore) + } + if _, err := harness.pool.Exec(ctx, ` + WITH failure_time AS (SELECT clock_timestamp() AS at) + UPDATE assessment_attempts + SET state='insufficient_bank', + updated_at=failure_time.at, + ended_at=failure_time.at, + version=version+1 + FROM failure_time + WHERE id=$1`, attempt.ID); err != nil { + t.Fatalf("mark isolated attempt as a system bank failure: %v", err) + } + var countAfter int32 + var latestAfter bool + var quotaAfter outbound.AssessmentRootQuotaSnapshot + if err := transactor.WithinTransaction(ctx, func(txctx context.Context, unit outbound.UnitOfWork) error { + var readErr error + countAfter, readErr = unit.AssessmentAttempts().CountRootAttemptsSince(txctx, candidate.ID, nil, createdAt.Add(-time.Second)) + if readErr != nil { + return readErr + } + _, latestAfter, readErr = unit.AssessmentAttempts().GetLatestRootForSpecialization( + txctx, candidate.ID, domain.SpecializationBackend, nil, + ) + if readErr != nil { + return readErr + } + asOf, timeErr := unit.AssessmentBank().DatabaseTime(txctx) + if timeErr != nil { + return timeErr + } + quotaAfter, readErr = unit.AssessmentAttempts().GetRootQuotaSnapshot( + txctx, candidate.ID, createdAt.Add(-time.Second), asOf, 24*time.Hour, 1, + ) + return readErr + }); err != nil { + t.Fatalf("read quota and retry history after platform failure: %v", err) + } + if countAfter != 0 || latestAfter || quotaAfter.Count != 0 || quotaAfter.AvailableAt != nil { + t.Fatalf("platform failure remains in availability history: count=%d latest=%v quota=%+v, want excluded", countAfter, latestAfter, quotaAfter) + } +} diff --git a/backend/integration_test/assessment_bank_test.go b/backend/integration_test/assessment_bank_test.go new file mode 100644 index 0000000..84572c7 --- /dev/null +++ b/backend/integration_test/assessment_bank_test.go @@ -0,0 +1,704 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/policy" +) + +const ( + assessmentTestTimeout = 3 * time.Minute + // demoBundleFile is the AI draft that the loader task ships. It has no + // human review, so nothing in it may become published. + demoBundleFile = "../testdata/assessment/backend_demo_bundle.json" + // assessmentCategory is the category of the demo bundle. + assessmentCategory = domain.AssessmentCategory("backend") + // Fixture identities of reviewed test bundles. They stand for people in + // tests only and are not content of the demo bank. + fixtureAuthor = "operator:fixture-author" + fixtureReviewer = "operator:fixture-reviewer" + fixtureOpener = domain.AssessmentOperator("operator:fixture-opener") + fixturePublisher = domain.AssessmentOperator("operator:fixture-publisher") + + assessmentIntegritySQLState = "23000" + assessmentCheckSQLState = "23514" +) + +type assessmentFixture struct { + ctx context.Context + pool *pgxpool.Pool + store *postgresadapter.AssessmentBankStore + transactor *postgresadapter.Transactor + bank *assessment.Bank + publisher *policy.Publisher + demoBundle assessment.Bundle +} + +func TestAssessmentBank(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentTestTimeout) + defer cancel() + newFixture := func(t *testing.T) assessmentFixture { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + return assessmentFixture{ + ctx: ctx, + pool: pool, + store: postgresadapter.NewAssessmentBankStore(pool), + transactor: postgresadapter.NewTransactor(pool), + bank: assessment.NewBank(postgresadapter.NewTransactor(pool)), + publisher: policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now), + demoBundle: loadDemoBundleFile(t), + } + } + + t.Run("two versions of a family are stored and the first keeps its original key", func(t *testing.T) { + fixture := newFixture(t) + first := fixture.singleFamilyBundle("backend-demo-v1", 1, "") + originalKey := first.Families[0].AnswerKey + if _, err := fixture.bank.ImportBundle(ctx, first); err != nil { + t.Fatalf("ImportBundle(version 1) error = %v", err) + } + second := fixture.singleFamilyBundle("backend-demo-v2", 2, "A different reference approach for version two.") + result, err := fixture.bank.ImportBundle(ctx, second) + if err != nil || len(result.Created) != 1 { + t.Fatalf("ImportBundle(version 2) = %+v, %v, want one created version", result, err) + } + + key := domain.AssessmentFamilyKey(first.Families[0].Key) + stored, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1) + if err != nil { + t.Fatalf("GetFamilyVersion(1) error = %v", err) + } + if stored.AnswerKey() != originalKey { + t.Fatalf("version 1 key = %+v, want the original %+v", stored.AnswerKey(), originalKey) + } + latest, err := fixture.store.AssessmentBank().GetLatestFamily(ctx, key) + if err != nil || latest.Version() != 2 || latest.AnswerKey() == originalKey { + t.Fatalf("GetLatestFamily() = version %d, %v, want version 2 with a different key", latest.Version(), err) + } + if stored.Lifecycle() != domain.AssessmentLifecycleDraft || stored.ReviewStatus() != domain.AssessmentReviewPending || stored.Reviewer() != "" { + t.Fatalf("imported demo version = %s/%s/%q, want draft, pending, no reviewer", stored.Lifecycle(), stored.ReviewStatus(), stored.Reviewer()) + } + + // Importing the same bundle again changes nothing; the same version + // with other content, and a gap in the numbering, are refused. + again, err := fixture.bank.ImportBundle(ctx, first) + if err != nil || len(again.Created) != 0 || len(again.Unchanged) != 1 { + t.Fatalf("ImportBundle(repeat) = %+v, %v, want one unchanged version", again, err) + } + changed := fixture.singleFamilyBundle("backend-demo-v1", 1, "Rewritten reference approach.") + fixture.assertRefusal(t, "ImportBundle(changed version 1)", domain.RefusalVersionConflict, importError(fixture, changed)) + fixture.assertRefusal(t, "ImportBundle(version 4)", domain.RefusalVersionGap, importError(fixture, fixture.singleFamilyBundle("backend-demo-v4", 4, "Skipped."))) + fixture.assertFamilyCount(t, 2) + }) + + t.Run("the database refuses to edit or remove a stored version", func(t *testing.T) { + fixture := newFixture(t) + if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil { + t.Fatalf("ImportBundle(demo) error = %v", err) + } + for name, statement := range map[string]string{ + "edit the key": `UPDATE assessment_families SET answer_key = '{"answer_format":"integer","reference_solution":"edited"}'`, + "edit the review": `UPDATE assessment_families SET reviewer = 'operator:someone', review_status = 'approved'`, + "edit the version": `UPDATE assessment_families SET version = version + 10`, + "edit the hash scheme": `UPDATE assessment_families SET hash_scheme = 2`, + "delete": `DELETE FROM assessment_families`, + "truncate": `TRUNCATE assessment_families, assessment_training_bank_binding_families, assessment_attempt_items, assessment_signal_events, assessment_answer_observations`, + } { + _, err := fixture.pool.Exec(ctx, statement) + assertPgError(t, name, err, assessmentIntegritySQLState, "assessment_families_immutable") + } + // Publishing a version without an approved review is refused by the + // table itself, not only by the domain. + _, err := fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'published', published_by = 'operator:raw-sql'`) + assertPgError(t, "publish without review", err, assessmentCheckSQLState, "assessment_families_published_requires_review") + // The lifecycle never moves backward or skips a step. + _, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'retired'`) + assertPgError(t, "retire a draft", err, assessmentIntegritySQLState, "assessment_families_lifecycle_transition") + // A new row cannot start published, whatever the caller sends. + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle <> 'draft'`, 0) + // The reviewer cannot be the author. + _, err = fixture.pool.Exec(ctx, ` + INSERT INTO assessment_families (id, family_key, version, category, specialization, title, bundle_name, author, reviewer, review_status, + seed_generator, answer_key, rubric, content_sha256, hash_scheme, lifecycle) + SELECT gen_random_uuid(), 'self-reviewed-family', 1, category, specialization, title, bundle_name, 'operator:same-person', 'operator:same-person', 'approved', + seed_generator, answer_key, rubric, content_sha256, hash_scheme, 'draft' + FROM assessment_families LIMIT 1`) + assertPgError(t, "reviewer is the author", err, assessmentCheckSQLState, "assessment_families_reviewer_independent") + fixture.assertFamilyCount(t, len(fixture.demoBundle.Families)) + }) + + t.Run("the same seed gives the same variant and a different seed keeps the rubric principle", func(t *testing.T) { + fixture := newFixture(t) + if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil { + t.Fatalf("ImportBundle(demo) error = %v", err) + } + for _, family := range fixture.demoBundle.Families { + key := domain.AssessmentFamilyKey(family.Key) + first, err := fixture.bank.GenerateVariant(ctx, key, 1, 42) + if err != nil { + t.Fatalf("GenerateVariant(%s, seed 42) error = %v", key, err) + } + second, err := fixture.bank.GenerateVariant(ctx, key, 1, 42) + if err != nil { + t.Fatalf("GenerateVariant(%s, seed 42) again error = %v", key, err) + } + if first.Statement != second.Statement || first.ReferenceAnswer != second.ReferenceAnswer { + t.Fatalf("%s: variants of seed 42 differ", key) + } + other := fixture.firstDifferentVariant(t, key, first) + if other.Rubric.Principle != first.Rubric.Principle || !slices.Equal(other.Rubric.Criteria, first.Rubric.Criteria) { + t.Fatalf("%s: the rubric changed with the seed", key) + } + if other.Rubric.Principle != family.Rubric.Principle { + t.Fatalf("%s: the variant rubric principle differs from the stored family rubric", key) + } + } + }) + + t.Run("a family without a reviewer cannot be published and the category stays closed", func(t *testing.T) { + fixture := newFixture(t) + if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil { + t.Fatalf("ImportBundle(demo) error = %v", err) + } + for _, family := range fixture.demoBundle.Families { + _, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher) + fixture.assertRefusal(t, "PublishFamily("+family.Key+")", domain.RefusalReviewerMissing, err) + } + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle = 'published'`, 0) + + policyVersion := fixture.publishGradingPolicy(t) + _, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, + }) + fixture.assertRefusal(t, "OpenCategory(no published families)", domain.RefusalCoverageInsufficient, err) + if _, err := fixture.bank.CategoryAvailability(ctx, assessmentCategory); !errors.Is(err, outbound.ErrAssessmentCategoryNotOpen) { + t.Fatalf("CategoryAvailability() error = %v, want ErrAssessmentCategoryNotOpen", err) + } + fixture.assertCount(t, `SELECT count(*) FROM assessment_category_openings`, 0) + }) + + t.Run("a category opens only under a referenced stored grading policy", func(t *testing.T) { + fixture := newFixture(t) + _, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, OpenedBy: fixtureOpener}) + fixture.assertRefusal(t, "OpenCategory(no policy reference)", domain.RefusalGradingPolicyMissing, err) + + unknown, err := domain.NewPolicyVersionID() + if err != nil { + t.Fatalf("NewPolicyVersionID() error = %v", err) + } + _, err = fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: unknown, OpenedBy: fixtureOpener}) + fixture.assertRefusal(t, "OpenCategory(unknown policy)", domain.RefusalGradingPolicyMissing, err) + fixture.assertCount(t, `SELECT count(*) FROM assessment_category_openings`, 0) + }) + + t.Run("a reviewed bundle opens the category once coverage reaches the policy requirement", func(t *testing.T) { + fixture := newFixture(t) + policyVersion := fixture.publishGradingPolicy(t) + requiredFamilies, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + required := int(requiredFamilies) + bundle := fixture.reviewedBundle(required) + if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle(reviewed) error = %v", err) + } + input := assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener} + + for index, family := range bundle.Families { + published, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher) + if err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + if _, ok := published.PublishedAt(); !ok || published.Lifecycle() != domain.AssessmentLifecyclePublished { + t.Fatalf("PublishFamily(%s) = %s without a publication time", family.Key, published.Lifecycle()) + } + if index < required-1 { + _, err := fixture.bank.OpenCategory(ctx, input) + fixture.assertRefusal(t, fmt.Sprintf("OpenCategory(%d of %d published)", index+1, required), domain.RefusalCoverageInsufficient, err) + } + } + opening, err := fixture.bank.OpenCategory(ctx, input) + if err != nil { + t.Fatalf("OpenCategory(enough coverage) error = %v", err) + } + if int(opening.RequiredFamilies) != required || int(opening.PublishedFamilies) != required || opening.PolicyVersionID != policyVersion.ID() { + t.Fatalf("opening = %+v, want %d required and published families under policy %s", opening, required, policyVersion.ID()) + } + current, err := fixture.bank.CategoryAvailability(ctx, assessmentCategory) + if err != nil || current.ID != opening.ID { + t.Fatalf("CategoryAvailability() = %+v, %v, want the new opening", current, err) + } + // The database derived the requirement from the policy document; it + // must equal the number that the domain computes from the same paths. + fixture.assertCount(t, `SELECT required_families FROM assessment_category_openings`, required) + published, err := fixture.store.AssessmentBank().GetPublishedFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[1].Key)) + if err != nil || published.PublishedBy() != fixturePublisher { + t.Fatalf("GetPublishedFamily() = %v, %v, want a version published by %s", published.PublishedBy(), err, fixturePublisher) + } + // A new policy version takes force: the opening was made under the + // old one, so the category needs a new opening. + fixture.publishGradingPolicy(t) + _, err = fixture.bank.CategoryAvailability(ctx, assessmentCategory) + fixture.assertRefusal(t, "CategoryAvailability(policy superseded)", domain.RefusalGradingPolicyNotCurrent, err) + _, err = fixture.pool.Exec(ctx, `UPDATE assessment_category_openings SET opened_by = 'operator:other'`) + assertPgError(t, "edit an opening", err, assessmentIntegritySQLState, "assessment_category_openings_immutable") + + // A second publication of a published version, and the retirement of + // a draft, are refused with a reason. + _, err = fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[0].Key), 1, fixturePublisher) + fixture.assertRefusal(t, "PublishFamily(published)", domain.RefusalNotDraft, err) + retired, err := fixture.bank.RetireFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[0].Key), 1, fixturePublisher) + if err != nil || retired.Lifecycle() != domain.AssessmentLifecycleRetired || retired.RetiredBy() != fixturePublisher { + t.Fatalf("RetireFamily() = %v, %v, want retired by %s", retired.Lifecycle(), err, fixturePublisher) + } + // Availability is live: with one published family fewer than the + // opening required, the category is refused with the reason. + _, err = fixture.bank.CategoryAvailability(ctx, assessmentCategory) + fixture.assertRefusal(t, "CategoryAvailability(after a retirement below the requirement)", domain.RefusalCoverageInsufficient, err) + _, err = fixture.bank.RetireFamily(ctx, domain.AssessmentFamilyKey(bundle.Families[0].Key), 1, fixturePublisher) + fixture.assertRefusal(t, "RetireFamily(retired)", domain.RefusalNotPublished, err) + _, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'published' WHERE lifecycle = 'retired'`) + assertPgError(t, "publish a retired version", err, assessmentIntegritySQLState, "assessment_families_lifecycle_transition") + }) + + t.Run("publishing a version retires the older published one and refuses an older one", func(t *testing.T) { + fixture := newFixture(t) + versions := fixture.reviewedVersionsBundle(1, 3) + key := domain.AssessmentFamilyKey(versions[0].Families[0].Key) + if _, err := fixture.bank.ImportBundle(ctx, versions[0]); err != nil { + t.Fatalf("ImportBundle(version 1) error = %v", err) + } + if _, err := fixture.bank.ActiveFamily(ctx, key); !errors.Is(err, outbound.ErrAssessmentFamilyNotFound) { + t.Fatalf("ActiveFamily(nothing published) error = %v, want ErrAssessmentFamilyNotFound", err) + } + if _, err := fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(1) error = %v", err) + } + for _, version := range versions[1:] { + if _, err := fixture.bank.ImportBundle(ctx, version); err != nil { + t.Fatalf("ImportBundle(%s) error = %v", version.Name, err) + } + } + other := domain.AssessmentOperator("operator:second-publisher") + if _, err := fixture.bank.PublishFamily(ctx, key, 3, other); err != nil { + t.Fatalf("PublishFamily(3) error = %v", err) + } + first, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1) + if err != nil || first.Lifecycle() != domain.AssessmentLifecycleRetired || first.RetiredBy() != other || first.PublishedBy() != fixturePublisher { + t.Fatalf("version 1 = %s published by %q retired by %q, %v, want retired by %s and published by %s", + first.Lifecycle(), first.PublishedBy(), first.RetiredBy(), err, other, fixturePublisher) + } + active, err := fixture.bank.ActiveFamily(ctx, key) + if err != nil || active.Version() != 3 { + t.Fatalf("ActiveFamily() = version %d, %v, want version 3", active.Version(), err) + } + _, err = fixture.bank.PublishFamily(ctx, key, 2, fixturePublisher) + fixture.assertRefusal(t, "PublishFamily(older than the published version)", domain.RefusalNewerVersionPublished, err) + _, err = fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher) + fixture.assertRefusal(t, "PublishFamily(retired version)", domain.RefusalNotDraft, err) + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle = 'published'`, 1) + + // The table allows one published version per family, whoever writes. + _, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET lifecycle = 'published', published_by = 'operator:raw-sql' WHERE family_key = $1 AND version = 2`, string(key)) + assertPgError(t, "second published version", err, "23505", "assessment_families_one_published_key") + // The recorded operators change only with their step. + _, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET published_by = 'operator:raw-sql' WHERE lifecycle = 'published'`) + assertPgError(t, "rewrite the publisher", err, assessmentIntegritySQLState, "assessment_families_lifecycle_transition") + // An approved pending draft is a new version, never an edit: the + // demo drafts stay pending drafts. + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE review_status = 'pending' AND lifecycle <> 'draft'`, 0) + }) + + t.Run("an older approved draft is not published after a newer version exists", func(t *testing.T) { + fixture := newFixture(t) + versions := fixture.reviewedVersionsBundle(1, 2) + for _, version := range versions { + if _, err := fixture.bank.ImportBundle(ctx, version); err != nil { + t.Fatalf("ImportBundle(%s) error = %v", version.Name, err) + } + } + key := domain.AssessmentFamilyKey(versions[0].Families[0].Key) + if _, err := fixture.bank.PublishFamily(ctx, key, 2, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(2) error = %v", err) + } + _, err := fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher) + fixture.assertRefusal(t, "PublishFamily(1 while 2 is published)", domain.RefusalNewerVersionPublished, err) + if _, err := fixture.bank.RetireFamily(ctx, key, 2, fixturePublisher); err != nil { + t.Fatalf("RetireFamily(2) error = %v", err) + } + _, err = fixture.bank.PublishFamily(ctx, key, 1, fixturePublisher) + fixture.assertRefusal(t, "PublishFamily(1 while 2 is retired)", domain.RefusalNewerVersionPublished, err) + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE lifecycle = 'published'`, 0) + }) + + t.Run("opening, publishing, and retiring of one category run one after another", func(t *testing.T) { + fixture := newFixture(t) + policyVersion := fixture.publishGradingPolicy(t) + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + bundle := fixture.reviewedBundle(int(required)) + if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle() error = %v", err) + } + for _, family := range bundle.Families { + if _, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } + // A transaction that holds the category lock, as a publication does + // until it commits, makes an opening wait instead of counting. + held, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) + go func() { + done <- fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.AssessmentBank().LockCategory(ctx, assessmentCategory); err != nil { + return err + } + close(held) + <-release + return nil + }) + }() + <-held + waiting, cancelWait := context.WithTimeout(ctx, 500*time.Millisecond) + defer cancelWait() + _, err = fixture.bank.OpenCategory(waiting, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener}) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("OpenCategory(while another transaction holds the category lock) error = %v, want a wait that ends with the deadline", err) + } + close(release) + if err := <-done; err != nil { + t.Fatalf("lock holder error = %v", err) + } + if _, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener}); err != nil { + t.Fatalf("OpenCategory(after the lock is released) error = %v", err) + } + }) + + t.Run("a category opens only under the policy version in force", func(t *testing.T) { + fixture := newFixture(t) + superseded := fixture.publishGradingPolicy(t) + current := fixture.publishGradingPolicy(t) + _, err := fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: superseded.ID(), OpenedBy: fixtureOpener}) + fixture.assertRefusal(t, "OpenCategory(superseded policy)", domain.RefusalGradingPolicyNotCurrent, err) + // The policy in force passes that check and then fails on coverage. + _, err = fixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{Category: assessmentCategory, GradingPolicyID: current.ID(), OpenedBy: fixtureOpener}) + fixture.assertRefusal(t, "OpenCategory(policy in force, no coverage)", domain.RefusalCoverageInsufficient, err) + }) + + t.Run("the database derives the required coverage and refuses invisible characters", func(t *testing.T) { + fixture := newFixture(t) + policyVersion := fixture.publishGradingPolicy(t) + bundle := fixture.reviewedBundle(3) + if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle() error = %v", err) + } + for _, family := range bundle.Families { + if _, err := fixture.bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), 1, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } + // Three published families, and a caller that claims that one is + // enough: the trigger replaces the claim with the policy's number. + _, err := fixture.pool.Exec(ctx, ` + INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at) + VALUES (gen_random_uuid(), 'backend', $1, 'operator:fixture-opener', 1, 3, now())`, policyVersion.ID().UUID()) + assertPgError(t, "opening with a claimed requirement", err, assessmentCheckSQLState, "assessment_category_openings_coverage") + + _, err = fixture.pool.Exec(ctx, ` + INSERT INTO assessment_families (id, family_key, version, category, specialization, title, bundle_name, author, review_status, + seed_generator, answer_key, rubric, content_sha256, hash_scheme, lifecycle) + SELECT gen_random_uuid(), 'bidi-title-family', 1, category, specialization, E'Cache \u202Etest', bundle_name, author, 'pending', + seed_generator, answer_key, rubric, content_sha256, hash_scheme, 'draft' + FROM assessment_families LIMIT 1`) + assertPgError(t, "title with a bidi override", err, assessmentCheckSQLState, "assessment_families_title_format") + }) + + t.Run("a policy document with malformed scored item bounds is refused with the thresholds refusal", func(t *testing.T) { + fixture := newFixture(t) + for index, document := range []string{ + `{}`, + `{"assessment":{"stop_rule":{"max_scored_items":"many","seed_items":1}}}`, + `{"assessment":{"stop_rule":{"max_scored_items":99999999999,"seed_items":1}}}`, + `{"assessment":{"stop_rule":{"max_scored_items":2.5,"seed_items":1}}}`, + `{"assessment":{"stop_rule":{"max_scored_items":-3,"seed_items":1}}}`, + `{"assessment":{"stop_rule":{"max_scored_items":10}}}`, + } { + // The document is written around the domain, which would never + // store it; the policy table only checks that it is an object. + var policyID string + err := fixture.pool.QueryRow(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) + VALUES (gen_random_uuid(), 'product', $1, 'demo', NULL, 'operator:raw-sql', $2::jsonb, decode(repeat('00', 32), 'hex')) + RETURNING id::text`, index+1, document).Scan(&policyID) + if err != nil { + t.Fatalf("insert raw policy version %d: %v", index+1, err) + } + _, err = fixture.pool.Exec(ctx, ` + INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at) + VALUES (gen_random_uuid(), 'backend', $1::uuid, 'operator:fixture-opener', 1, 1, now())`, policyID) + assertPgError(t, "opening under document "+document, err, assessmentCheckSQLState, "assessment_category_openings_policy_thresholds") + } + }) + + t.Run("a stored hash scheme must be a known one", func(t *testing.T) { + fixture := newFixture(t) + if _, err := fixture.bank.ImportBundle(ctx, fixture.demoBundle); err != nil { + t.Fatalf("ImportBundle(demo) error = %v", err) + } + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 1`, len(fixture.demoBundle.Families)) + _, err := fixture.pool.Exec(ctx, ` + INSERT INTO assessment_families (id, family_key, version, category, specialization, title, bundle_name, author, review_status, + seed_generator, answer_key, rubric, content_sha256, hash_scheme, lifecycle) + SELECT gen_random_uuid(), 'other-scheme-family', 1, category, specialization, title, bundle_name, author, 'pending', + seed_generator, answer_key, rubric, content_sha256, 7, 'draft' + FROM assessment_families LIMIT 1`) + assertPgError(t, "unknown hash scheme", err, assessmentCheckSQLState, "assessment_families_hash_scheme_known") + }) + + t.Run("a table family is stored with hash scheme 2 and imports again unchanged", func(t *testing.T) { + fixture := newFixture(t) + bundle := fixture.demoBundle + bundle.Name = "table-family-bundle" + bundle.Families = choiceTableBankFamilies(t, bundle.Families[0]) + first, err := fixture.bank.ImportBundle(ctx, bundle) + if err != nil || len(first.Created) != 3 || len(first.Unchanged) != 0 { + t.Fatalf("ImportBundle(table bundle) = %+v, %v, want three created versions", first, err) + } + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 2`, 2) + fixture.assertCount(t, `SELECT count(*) FROM assessment_families WHERE hash_scheme = 1`, 1) + again, err := fixture.bank.ImportBundle(ctx, bundle) + if err != nil || len(again.Created) != 0 || len(again.Unchanged) != 3 { + t.Fatalf("ImportBundle(table bundle again) = %+v, %v, want three unchanged versions", again, err) + } + // The stored row is verified with its own scheme when it is read, and + // the same seed gives the same variant from it. + for _, family := range bundle.Families { + key := domain.AssessmentFamilyKey(family.Key) + stored, err := fixture.store.AssessmentBank().GetFamilyVersion(ctx, key, 1) + if err != nil { + t.Fatalf("GetFamilyVersion(%s) error = %v", key, err) + } + wantScheme := int16(2) + if family.SeedGenerator.Table == nil { + wantScheme = 1 + } + if stored.HashScheme() != wantScheme { + t.Fatalf("family %s scheme = %d, want %d", key, stored.HashScheme(), wantScheme) + } + one, err := fixture.bank.GenerateVariant(ctx, key, 1, 77) + if err != nil { + t.Fatalf("GenerateVariant(%s) error = %v", key, err) + } + two, err := fixture.bank.GenerateVariant(ctx, key, 1, 77) + if err != nil || one.Statement != two.Statement || one.ReferenceAnswer != two.ReferenceAnswer || !slices.Equal(one.Options, two.Options) { + t.Fatalf("GenerateVariant(%s) twice = %+v and %+v (%v), want one variant", key, one, two, err) + } + } + // A table row edited in the database fails the hash, whatever the edit + // path: the trigger refuses the edit, and the row stays as imported. + _, err = fixture.pool.Exec(ctx, `UPDATE assessment_families SET seed_generator = replace(seed_generator::text, '"404"', '"405"')::jsonb WHERE hash_scheme = 2`) + assertPgError(t, "edit a table", err, assessmentIntegritySQLState, "assessment_families_immutable") + }) + + t.Run("families are listed in pages after a cursor", func(t *testing.T) { + fixture := newFixture(t) + bundle := fixture.reviewedBundle(5) + if _, err := fixture.bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle() error = %v", err) + } + var seen []string + var cursor outbound.AssessmentFamilyCursor + for range 10 { + page, err := fixture.store.AssessmentBank().ListFamilies(ctx, assessmentCategory, cursor, 2) + if err != nil { + t.Fatalf("ListFamilies() error = %v", err) + } + if len(page) == 0 { + break + } + if len(page) > 2 { + t.Fatalf("ListFamilies(limit 2) returned %d rows", len(page)) + } + for _, family := range page { + seen = append(seen, string(family.Key())) + } + last := page[len(page)-1] + cursor = outbound.AssessmentFamilyCursor{Key: last.Key(), Version: last.Version()} + } + if len(seen) != 5 || !slices.IsSorted(seen) { + t.Fatalf("pages returned %v, want the five keys once and in order", seen) + } + }) + + t.Run("the database refuses an opening below the required coverage", func(t *testing.T) { + fixture := newFixture(t) + policyVersion := fixture.publishGradingPolicy(t) + // Written around the usecase: the opening trigger counts the + // published families itself and the coverage CHECK refuses the row. + _, err := fixture.pool.Exec(ctx, ` + INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at) + VALUES (gen_random_uuid(), 'backend', $1, 'operator:fixture-opener', 1, 999, now())`, policyVersion.ID().UUID()) + assertPgError(t, "opening without published families", err, assessmentCheckSQLState, "assessment_category_openings_coverage") + _, err = fixture.pool.Exec(ctx, ` + INSERT INTO assessment_category_openings (id, category, policy_version_id, opened_by, required_families, published_families, opened_at) + VALUES (gen_random_uuid(), 'backend', gen_random_uuid(), 'operator:fixture-opener', 1, 1, now())`) + assertPgError(t, "opening under an unknown policy version", err, "23503", "assessment_category_openings_policy_version_id_fkey") + }) +} + +func importError(fixture assessmentFixture, bundle assessment.Bundle) error { + _, err := fixture.bank.ImportBundle(fixture.ctx, bundle) + return err +} + +func loadDemoBundleFile(t *testing.T) assessment.Bundle { + t.Helper() + file, err := os.Open(filepath.FromSlash(demoBundleFile)) + if err != nil { + t.Fatalf("open demo bundle: %v", err) + } + defer file.Close() + bundle, err := assessment.ParseBundle(file) + if err != nil { + t.Fatalf("ParseBundle(demo) error = %v", err) + } + return bundle +} + +// singleFamilyBundle takes the first family of the demo bundle as the given +// version. A non-empty solution replaces the reference solution, which makes +// the version's key differ from version 1. +func (fixture assessmentFixture) singleFamilyBundle(name string, version int32, solution string) assessment.Bundle { + bundle := fixture.demoBundle + bundle.Name = name + family := bundle.Families[0] + family.Version = version + if solution != "" { + family.AnswerKey.ReferenceSolution = solution + } + bundle.Families = []assessment.BundleFamily{family} + return bundle +} + +// reviewedBundle builds a bundle of count families that carries an approved +// review by a person who is not the author. It is a test fixture for the +// loader rules and not content of the demo bank: it reuses the generator +// definitions of the demo families under other keys. +func (fixture assessmentFixture) reviewedBundle(count int) assessment.Bundle { + bundle := fixture.demoBundle + bundle.Name = "fixture-reviewed-bundle" + bundle.Author = fixtureAuthor + bundle.Review = assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer} + bundle.Families = make([]assessment.BundleFamily, 0, count) + for index := range count { + family := fixture.demoBundle.Families[index%len(fixture.demoBundle.Families)] + family.Key = fmt.Sprintf("fixture-family-%02d", index+1) + bundle.Families = append(bundle.Families, family) + } + return bundle +} + +// reviewedVersionsBundle returns one bundle per version from first to last, +// each holding the first demo family as that version with an approved review +// by a person who is not the author. Later versions change the reference +// solution, so their keys differ. +func (fixture assessmentFixture) reviewedVersionsBundle(first, last int32) []assessment.Bundle { + var bundles []assessment.Bundle + for version := first; version <= last; version++ { + bundle := fixture.singleFamilyBundle(fmt.Sprintf("fixture-version-%d", version), version, "") + bundle.Families = []assessment.BundleFamily{bundle.Families[0]} + bundle.Families[0].AnswerKey.ReferenceSolution = fmt.Sprintf("Reference approach of version %d.", version) + bundle.Author = fixtureAuthor + bundle.Review = assessment.BundleReview{Status: string(domain.AssessmentReviewApproved), Reviewer: fixtureReviewer} + bundles = append(bundles, bundle) + } + return bundles +} + +// publishGradingPolicy stores a test policy as the grading policy that +// categories open under. +func (fixture assessmentFixture) publishGradingPolicy(t *testing.T) domain.PolicyVersion { + t.Helper() + version, err := fixture.publisher.Publish(fixture.ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: integrationPolicy(11), + }) + if err != nil { + t.Fatalf("Publish(grading policy) error = %v", err) + } + return version +} + +// firstDifferentVariant generates variants of other seeds until the +// statement differs from the given variant. +func (fixture assessmentFixture) firstDifferentVariant(t *testing.T, key domain.AssessmentFamilyKey, variant domain.AssessmentVariant) domain.AssessmentVariant { + t.Helper() + for seed := variant.Seed + 1; seed < variant.Seed+50; seed++ { + other, err := fixture.bank.GenerateVariant(fixture.ctx, key, variant.FamilyVersion, seed) + if err != nil { + t.Fatalf("GenerateVariant(%s, seed %d) error = %v", key, seed, err) + } + if other.Statement != variant.Statement { + return other + } + } + t.Fatalf("no seed near %d changed the statement of %s", variant.Seed, key) + return domain.AssessmentVariant{} +} + +func (fixture assessmentFixture) assertRefusal(t *testing.T, operation string, want domain.AssessmentRefusalReason, err error) { + t.Helper() + var refusal *domain.AssessmentRefusalError + if !errors.Is(err, domain.ErrAssessmentRefused) || !errors.As(err, &refusal) || refusal.Reason != want { + t.Fatalf("%s error = %v, want a refusal with reason %s", operation, err, want) + } + if refusal.Detail == "" { + t.Fatalf("%s refusal has no detail", operation) + } +} + +func (fixture assessmentFixture) assertFamilyCount(t *testing.T, want int) { + t.Helper() + fixture.assertCount(t, `SELECT count(*) FROM assessment_families`, want) +} + +func (fixture assessmentFixture) assertCount(t *testing.T, query string, want int) { + t.Helper() + var got int + if err := fixture.pool.QueryRow(fixture.ctx, query).Scan(&got); err != nil { + t.Fatalf("count rows with %q: %v", query, err) + } + if got != want { + t.Fatalf("%q = %d, want %d", query, got, want) + } +} + +func assertPgError(t *testing.T, operation string, err error, sqlState, constraint string) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != sqlState || pgError.ConstraintName != constraint { + t.Fatalf("%s error = %v, want SQLSTATE %s on %s", operation, err, sqlState, constraint) + } +} diff --git a/backend/integration_test/assessment_category_http_test.go b/backend/integration_test/assessment_category_http_test.go new file mode 100644 index 0000000..cc97c41 --- /dev/null +++ b/backend/integration_test/assessment_category_http_test.go @@ -0,0 +1,1025 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/primary/cli/categoryattest" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/policy" +) + +const categoryHTTPPromotionGap = 91 * 24 * time.Hour // longer than the 90-day promotion interval of the demo policy + +// categoryHTTPBank is the bank of the category scenarios. The product policy is +// the explicit demo policy, so that its pass mark is the one a demonstration +// category may rely on. +type categoryHTTPBank struct { + policy domain.PolicyVersion + // reviewed lists the categories that carry an operator attestation for the + // exact opening, manifest and policy; unreviewedCategory carries none. + reviewed []domain.AssessmentCategory +} + +const ( + categoryHTTPInternCategory = domain.AssessmentCategory("backend-intern") + categoryHTTPJuniorCategory = domain.AssessmentCategory("backend") + categoryHTTPUnreviewedCategory = domain.AssessmentCategory("frontend-intern") +) + +// seedAssessmentCategoryHTTPBank publishes the given demo policy and three opened +// categories of 25 published families each (the policy's maximum scored items +// plus its seed items): when attest is set, backend junior and backend intern +// are attested for synthetic demonstration use; frontend intern never is. It also binds the +// express training bank. +func seedAssessmentCategoryHTTPBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool, productPolicy domain.ProductPolicy, attest bool) categoryHTTPBank { + t.Helper() + transactor := postgresadapter.NewTransactor(pool) + bank := assessment.NewBank(transactor) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now) + fixture := assessmentFixture{ + ctx: ctx, pool: pool, store: postgresadapter.NewAssessmentBankStore(pool), transactor: transactor, + bank: bank, publisher: publisher, demoBundle: loadDemoBundleFile(t), + } + policyVersion, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: policyTestAuthor, Policy: productPolicy, + }) + if err != nil { + t.Fatalf("Publish(demo category policy) error = %v", err) + } + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + for _, category := range []struct { + name domain.AssessmentCategory + specialization domain.SpecializationCode + grade domain.GradeCode + prefix string + }{ + {categoryHTTPJuniorCategory, domain.SpecializationBackend, domain.GradeJunior, "category-backend"}, + {categoryHTTPInternCategory, domain.SpecializationBackend, domain.GradeIntern, "category-backend-intern"}, + {categoryHTTPUnreviewedCategory, domain.SpecializationFrontend, domain.GradeIntern, "category-frontend-intern"}, + } { + bundle := fixture.reviewedBundle(int(required)) + bundle.Name = "assessment-" + string(category.name) + "-fixture" + bundle.Category = string(category.name) + for index := range bundle.Families { + bundle.Families[index].Key = fmt.Sprintf("%s-%02d", category.prefix, index+1) + bundle.Families[index].Specialization = string(category.specialization) + } + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle(%s) error = %v", category.name, err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, bundle) + openAssessmentAttemptFixtureCategory(ctx, t, bank, policyVersion.ID(), category.name, category.specialization, category.grade) + } + training := fixture.reviewedBundle(int(policyVersion.Policy().Assessment.Training.DemoExpressItemCount)) + training.Name = "assessment-category-training-fixture" + training.Category = "training-category" + for index := range training.Families { + training.Families[index].Key = fmt.Sprintf("category-training-%02d", index+1) + } + if _, err := bank.ImportBundle(ctx, training); err != nil { + t.Fatalf("ImportBundle(category training) error = %v", err) + } + publishAssessmentAttemptFixtureFamilies(ctx, t, bank, training) + seedAssessmentAttemptTrainingBinding(ctx, t, pool, policyVersion.ID().UUID(), training.Category, len(training.Families)) + + seeded := categoryHTTPBank{policy: policyVersion} + if !attest { + return seeded + } + for _, category := range []domain.AssessmentCategory{categoryHTTPJuniorCategory, categoryHTTPInternCategory} { + attestSyntheticCategory(ctx, t, pool, category, policyVersion) + seeded.reviewed = append(seeded.reviewed, category) + } + return seeded +} + +// attestSyntheticCategory stores the operator attestation for the current +// opening of the category, its published manifest and the given policy. +func attestSyntheticCategory(ctx context.Context, t *testing.T, pool *pgxpool.Pool, category domain.AssessmentCategory, policyVersion domain.PolicyVersion) { + t.Helper() + var openingID uuid.UUID + var manifest []byte + if err := pool.QueryRow(ctx, ` + SELECT opening.id, binding.published_manifest_sha256 + FROM assessment_category_openings AS opening + JOIN assessment_category_catalog_bindings AS binding ON binding.opening_id = opening.id + WHERE opening.category = $1 + ORDER BY opening.opened_at DESC LIMIT 1`, string(category)).Scan(&openingID, &manifest); err != nil || len(manifest) != 32 { + t.Fatalf("read opening of %s: %v (manifest %d bytes)", category, err, len(manifest)) + } + var manifestHash [32]byte + copy(manifestHash[:], manifest) + review, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: openingID, Category: category, Source: domain.AssessmentCategorySourceSyntheticDemo, + OpeningManifestHash: manifestHash, ProductPolicyVersionID: policyVersion.ID(), + ProductPolicyVersion: policyVersion.Version(), ReviewedBy: domain.AssessmentOperator("operator:category-reviewer"), + ReviewedAt: time.Now().UTC(), + }) + if err != nil { + t.Fatalf("NewAssessmentSyntheticCategoryReview(%s) error = %v", category, err) + } + err = postgresadapter.NewTransactor(pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.AssessmentAttempts().CreateSyntheticCategoryReview(ctx, review) + return err + }) + if err != nil { + t.Fatalf("CreateSyntheticCategoryReview(%s) error = %v", category, err) + } +} + +type categoryHTTPCandidate struct { + id uuid.UUID + email string + cookie string + csrf string +} + +type categoryHTTPClient struct { + harness *assessmentAttemptHTTPHarness + ctx context.Context + calls int +} + +// remote spreads requests over documentation addresses so that the per-client +// rate limits of the router do not apply to the scenario. +func (client *categoryHTTPClient) remote() string { + client.calls++ + return fmt.Sprintf("198.51.%d.%d:1234", client.calls/250%250, client.calls%250+1) +} + +// call returns the status and the JSON body of one request. +func (client *categoryHTTPClient) call(t *testing.T, who categoryHTTPCandidate, method, path, body, key string) (int, []byte) { + t.Helper() + recorder := assessmentAttemptHTTPRequest(t, client.harness, method, path, body, sessionHTTPTestOrigin, + who.cookie, who.csrf, key, client.remote()) + return recorder.Code, recorder.Body.Bytes() +} + +func (client *categoryHTTPClient) candidate(t *testing.T, email string) categoryHTTPCandidate { + t.Helper() + harness := client.harness + passwordHash, err := harness.credentials.HashNewPassword(client.ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + user := createSessionHTTPUser(client.ctx, t, harness.sessionHTTPHarness, email, passwordHash, true) + if _, err := harness.pool.Exec(client.ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", user.ID); err != nil { + t.Fatalf("set onboarding step of %s: %v", email, err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, email, client.remote()) + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, client.remote()); response.Code != http.StatusOK { + t.Fatalf("save questionnaire of %s = %d %s", email, response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, client.remote()) + return categoryHTTPCandidate{id: user.ID, email: email, cookie: cookie.Value, csrf: csrf} +} + +// employer registers a verified employer account and signs it in. +func (client *categoryHTTPClient) employer(t *testing.T, email string) categoryHTTPCandidate { + t.Helper() + harness := client.harness + passwordHash, err := harness.credentials.HashNewPassword(client.ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + now := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser(employer) error = %v", err) + } + if err := harness.store.Users().Create(client.ctx, user); err != nil { + t.Fatalf("Create(employer) error = %v", err) + } + if _, err := harness.store.Users().MarkEmailVerified(client.ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)); err != nil { + t.Fatalf("MarkEmailVerified(employer) error = %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, email, client.remote()) + return categoryHTTPCandidate{id: user.ID, email: email, cookie: cookie.Value, csrf: csrf} +} + +// attemptRun is one finished attempt: its identifier, the frozen item count and +// the result as the owner read it right after finalization. +type attemptRun struct { + id uuid.UUID + items int + result map[string]any + body []byte +} + +// run creates a root attempt, answers the first correct frozen items right and +// every other item wrong, finalizes and reads the result. +func (client *categoryHTTPClient) run(t *testing.T, who categoryHTTPCandidate, specialization, grade string, correct func(items int) int) attemptRun { + t.Helper() + key := uuid.NewString() + status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBodyWithGrade(t, specialization, grade), key+"-create") + var attempt assessmentAnswerHTTPAttempt + if status != http.StatusCreated || json.Unmarshal(body, &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create %s/%s attempt = %d %s", specialization, grade, status, body) + } + items := readAssessmentAnswerHTTPItems(t, client.ctx, client.harness, attempt.ID) + wantCorrect := correct(len(items)) + version := attempt.Version + for index, item := range items { + answer := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, index < wantCorrect) + status, body = client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", + string(answer), fmt.Sprintf("%s-answer-%d", key, item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if status != http.StatusOK || json.Unmarshal(body, &next) != nil || next.Version != version+1 { + t.Fatalf("answer item %d = %d %s", item.Ordinal, status, body) + } + version = next.Version + } + finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version}) + if err != nil { + t.Fatalf("marshal finalize body: %v", err) + } + status, body = client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", + string(finalizeBody), key+"-finalize") + if status != http.StatusOK { + t.Fatalf("finalize %s/%s attempt = %d %s", specialization, grade, status, body) + } + return attemptRun{id: attempt.ID, items: len(items), result: client.result(t, who, attempt.ID), body: client.resultBody(t, who, attempt.ID)} +} + +func (client *categoryHTTPClient) resultBody(t *testing.T, who categoryHTTPCandidate, attemptID uuid.UUID) []byte { + t.Helper() + status, body := client.call(t, who, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String()+"/result", "", "") + if status != http.StatusOK { + t.Fatalf("read result of %s = %d %s", attemptID, status, body) + } + return body +} + +func (client *categoryHTTPClient) result(t *testing.T, who categoryHTTPCandidate, attemptID uuid.UUID) map[string]any { + t.Helper() + var result map[string]any + if err := json.Unmarshal(client.resultBody(t, who, attemptID), &result); err != nil { + t.Fatalf("decode result of %s: %v", attemptID, err) + } + return result +} + +// passPoints is the number of correct answers that the pinned pass mark needs +// for n scored items: the smallest integer not below n times the mark. +func passPoints(items int, passMarkBasisPoints int) int { + return (items*passMarkBasisPoints + 9999) / 10000 +} + +type categoryStored struct { + grade, source, calibration string + sourceAttempt uuid.UUID + productPolicy, grading uuid.UUID + assignedAt time.Time +} + +func readStoredCategory(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID uuid.UUID, specialization string) (categoryStored, bool) { + t.Helper() + var stored categoryStored + rows, err := pool.Query(ctx, ` + SELECT grade, source, calibration_status, source_attempt_id, product_policy_version_id, + grading_policy_version_id, assigned_at + FROM candidate_assessment_categories WHERE candidate_id = $1 AND specialization = $2`, candidateID, specialization) + if err != nil { + t.Fatalf("read current category: %v", err) + } + defer rows.Close() + if !rows.Next() { + return categoryStored{}, false + } + if err := rows.Scan(&stored.grade, &stored.source, &stored.calibration, &stored.sourceAttempt, + &stored.productPolicy, &stored.grading, &stored.assignedAt); err != nil { + t.Fatalf("scan current category: %v", err) + } + return stored, true +} + +func countStoredCategories(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID uuid.UUID) int { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id = $1`, candidateID).Scan(&count); err != nil { + t.Fatalf("count current categories: %v", err) + } + return count +} + +func decisionOf(t *testing.T, result map[string]any) map[string]any { + t.Helper() + decision, ok := result["category_decision"].(map[string]any) + if !ok { + t.Fatalf("result %v has no category_decision", result["attempt_id"]) + } + return decision +} + +func TestAssessmentCategoryAssignmentOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 2*assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, &isolatedEnv, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true) + // The threshold and the number of scored items are the stored policy's own + // values; the scenario computes the exact boundary from them. + passMark := int(bank.policy.Policy().Assessment.Attempt.BasicPassMark) + scoredItems := int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems) + threshold := passPoints(scoredItems, passMark) + + client := &categoryHTTPClient{harness: harness, ctx: ctx} + + low := client.candidate(t, "category-low@example.test") + high := client.candidate(t, "category-high@example.test") + other := client.candidate(t, "category-other@example.test") + + var highInternAttempt attemptRun + var highJuniorAttempt attemptRun + var lowAttempt attemptRun + + t.Run("confirmation follows the threshold of the pinned policy at k-1 and k", func(t *testing.T) { + lowAttempt = client.run(t, low, "backend", "intern", func(int) int { return threshold - 1 }) + highInternAttempt = client.run(t, high, "backend", "intern", func(int) int { return threshold }) + k := threshold + if highInternAttempt.items != scoredItems+int(bank.policy.Policy().Assessment.StopRule.SeedItems) { + t.Fatalf("frozen items = %d, want scored plus seed items", highInternAttempt.items) + } + + score := lowAttempt.result["basic_score"].(map[string]any) + if lowAttempt.result["outcome"] != "not_confirmed" || int(score["points"].(float64)) != k-1 || int(score["pass_points"].(float64)) != k { + t.Fatalf("attempt at k-1 = %v with score %v, want not_confirmed at %d of %d", lowAttempt.result["outcome"], score, k-1, k) + } + decision := decisionOf(t, lowAttempt.result) + if decision["status"] != "not_confirmed" || decision["current_confirmed_grade"] != nil || decision["previous_confirmed_grade"] != nil || + decision["method"] != "demo_basic_pass_mark" || decision["source"] != "synthetic_demo" || decision["calibration_status"] != "uncalibrated" { + t.Fatalf("decision at k-1 = %v, want not_confirmed by the demonstration method without a grade", decision) + } + if lowAttempt.result["confirmed_grade"] != nil || countStoredCategories(t, ctx, harness.pool, low.id) != 0 { + t.Fatalf("attempt at k-1 produced grade %v and %d categories, want none", lowAttempt.result["confirmed_grade"], countStoredCategories(t, ctx, harness.pool, low.id)) + } + + score = highInternAttempt.result["basic_score"].(map[string]any) + if highInternAttempt.result["outcome"] != "confirmed" || int(score["points"].(float64)) != k || int(score["pass_points"].(float64)) != k { + t.Fatalf("attempt at k = %v with score %v, want confirmed exactly at the threshold %d", highInternAttempt.result["outcome"], score, k) + } + decision = decisionOf(t, highInternAttempt.result) + if decision["status"] != "assigned" || decision["current_confirmed_grade"] != "intern" || decision["previous_confirmed_grade"] != nil || + decision["method"] != "demo_basic_pass_mark" || decision["source"] != "synthetic_demo" || decision["calibration_status"] != "uncalibrated" || + highInternAttempt.result["confirmed_grade"] != "intern" || highInternAttempt.result["calibration_status"] != "uncalibrated" { + t.Fatalf("decision at k = %v, grade %v, want assigned intern by the uncalibrated demonstration method", decision, highInternAttempt.result["confirmed_grade"]) + } + for _, field := range []string{"decided_at", "versions", "limitations"} { + if highInternAttempt.result[field] == nil { + t.Fatalf("result lacks %s: %v", field, highInternAttempt.result) + } + } + stored, found := readStoredCategory(t, ctx, harness.pool, high.id, "backend") + if !found || stored.grade != "intern" || stored.source != "synthetic_demo" || stored.calibration != "uncalibrated" || + stored.sourceAttempt != highInternAttempt.id || stored.productPolicy != bank.policy.ID().UUID() || stored.grading != bank.policy.ID().UUID() { + t.Fatalf("stored category = %+v (found %v), want intern from attempt %s under policy %s", stored, found, highInternAttempt.id, bank.policy.ID()) + } + var passMarkStored int32 + var schemaVersion int16 + if err := harness.pool.QueryRow(ctx, `SELECT pass_mark_basis_points, schema_version FROM assessment_attempt_results WHERE attempt_id = $1`, + highInternAttempt.id).Scan(&passMarkStored, &schemaVersion); err != nil || int(passMarkStored) != passMark || schemaVersion != 2 { + t.Fatalf("stored pass mark/schema = %d/%d (error %v), want the policy's %d on a v2 result", passMarkStored, schemaVersion, err, passMark) + } + }) + + t.Run("the category cannot be rewritten or removed outside a qualified result", func(t *testing.T) { + for _, test := range []struct { + name, sql, constraint string + code string + }{ + {"downgrade", `UPDATE candidate_assessment_categories SET grade = 'intern' WHERE candidate_id = $1`, "candidate_assessment_categories_monotonic", "23514"}, + {"other source", `UPDATE candidate_assessment_categories SET source_attempt_id = $2 WHERE candidate_id = $1`, "candidate_assessment_categories_result_match", "23514"}, + {"delete", `DELETE FROM candidate_assessment_categories WHERE candidate_id = $1`, "candidate_assessment_categories_delete", "23000"}, + } { + args := []any{high.id} + if test.name == "other source" { + args = append(args, lowAttempt.id) + } + _, err := harness.pool.Exec(ctx, test.sql, args...) + assertPgError(t, test.name, err, test.code, test.constraint) + } + _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempt_results SET current_confirmed_grade = 'senior' WHERE attempt_id = $1`, highInternAttempt.id) + assertPgError(t, "rewrite of a stored result", err, "23000", "assessment_attempt_result_immutable") + }) + + t.Run("a failed attempt for a higher grade keeps the category and both attempts stay in the history", func(t *testing.T) { + // The promotion interval counts on database time, so the finished intern + // attempt is moved past it instead of waiting for days. + moveFinishedAttemptBack(t, ctx, harness.pool, highInternAttempt.id, categoryHTTPPromotionGap) + before, found := readStoredCategory(t, ctx, harness.pool, high.id, "backend") + if !found { + t.Fatal("the candidate has no category before the higher attempt") + } + highInternAttempt.body = client.resultBody(t, high, highInternAttempt.id) + if err := json.Unmarshal(highInternAttempt.body, &highInternAttempt.result); err != nil { + t.Fatalf("decode moved result: %v", err) + } + highJuniorAttempt = client.run(t, high, "backend", "junior", func(int) int { return threshold - 1 }) + if highJuniorAttempt.result["outcome"] != "not_confirmed" || highJuniorAttempt.result["confirmed_grade"] != nil || + highJuniorAttempt.result["previous_confirmed_grade"] != "intern" { + t.Fatalf("failed higher attempt = %v, confirmed %v, previous %v; want not_confirmed with the intern grade staying in force", + highJuniorAttempt.result["outcome"], highJuniorAttempt.result["confirmed_grade"], highJuniorAttempt.result["previous_confirmed_grade"]) + } + decision := decisionOf(t, highJuniorAttempt.result) + if decision["status"] != "not_confirmed" || decision["previous_confirmed_grade"] != "intern" || decision["current_confirmed_grade"] != "intern" { + t.Fatalf("decision of the failed higher attempt = %v, want intern kept", decision) + } + after, found := readStoredCategory(t, ctx, harness.pool, high.id, "backend") + if !found || after != before { + t.Fatalf("category after the failed attempt = %+v (found %v), want unchanged %+v", after, found, before) + } + + firstStatus, firstBody := client.call(t, high, http.MethodGet, "/api/v1/me/assessment-results?limit=1", "", "") + var firstPage struct { + Items []map[string]any `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` + } + if firstStatus != http.StatusOK || json.Unmarshal(firstBody, &firstPage) != nil || len(firstPage.Items) != 1 || + !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil { + t.Fatalf("first history page = %d %s, want one newest result and a next cursor", firstStatus, firstBody) + } + if firstPage.Items[0]["attempt_id"] != highJuniorAttempt.id.String() { + t.Fatalf("newest history item = %v, want the failed higher attempt %s", firstPage.Items[0]["attempt_id"], highJuniorAttempt.id) + } + secondStatus, secondBody := client.call(t, high, http.MethodGet, + "/api/v1/me/assessment-results?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", "") + var secondPage struct { + Items []map[string]any `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` + } + if secondStatus != http.StatusOK || json.Unmarshal(secondBody, &secondPage) != nil || len(secondPage.Items) != 1 || + secondPage.Page.HasMore || secondPage.Page.NextCursor != nil || secondPage.Items[0]["attempt_id"] != highInternAttempt.id.String() { + t.Fatalf("second history page = %d %s, want the confirmed intern attempt and no more pages", secondStatus, secondBody) + } + if !jsonEqual(t, secondPage.Items[0], highInternAttempt.result) || !jsonEqual(t, firstPage.Items[0], highJuniorAttempt.result) { + t.Fatalf("history items differ from the single result reads:\n%v\n%v", secondPage.Items[0], firstPage.Items[0]) + } + + // The cursor belongs to the candidate that received it. + status, _ := client.call(t, other, http.MethodGet, "/api/v1/me/assessment-results?cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", "") + if status != http.StatusBadRequest { + t.Fatalf("foreign history cursor = %d, want 400", status) + } + for _, invalid := range []string{"limit=0", "limit=51", "cursor=not-a-cursor"} { + if status, body := client.call(t, high, http.MethodGet, "/api/v1/me/assessment-results?"+invalid, "", ""); status != http.StatusBadRequest { + t.Fatalf("history query %q = %d %s, want 400", invalid, status, body) + } + } + if status, _ := client.call(t, categoryHTTPCandidate{}, http.MethodGet, "/api/v1/me/assessment-results", "", ""); status != http.StatusUnauthorized { + t.Fatalf("history without a session = %d, want 401", status) + } + // Another candidate's history holds none of these attempts. + _, otherBody := client.call(t, other, http.MethodGet, "/api/v1/me/assessment-results", "", "") + if strings.Contains(string(otherBody), highInternAttempt.id.String()) || strings.Contains(string(otherBody), highJuniorAttempt.id.String()) { + t.Fatalf("history of another candidate lists foreign attempts: %s", otherBody) + } + if status, _ := client.call(t, other, http.MethodGet, "/api/v1/me/assessment-attempts/"+highInternAttempt.id.String()+"/result", "", ""); status != http.StatusNotFound { + t.Fatalf("foreign result read = %d, want 404", status) + } + }) + + t.Run("express with perfect answers creates no category and keeps the previous one", func(t *testing.T) { + before, found := readStoredCategory(t, ctx, harness.pool, high.id, "backend") + if !found { + t.Fatal("the candidate has no category before express") + } + create := func(who categoryHTTPCandidate, key string) assessmentAnswerHTTPAttempt { + status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, key) + var attempt assessmentAnswerHTTPAttempt + if status != http.StatusCreated || json.Unmarshal(body, &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create express attempt = %d %s", status, body) + } + return attempt + } + for _, who := range []categoryHTTPCandidate{high, other} { + expressKey := uuid.NewString() + attempt := create(who, expressKey+"-create") + version := attempt.Version + for _, item := range readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) { + status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", + string(assessmentAnswerHTTPBody(t, version, item)), fmt.Sprintf("%s-answer-%d", expressKey, item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if status != http.StatusOK || json.Unmarshal(body, &next) != nil { + t.Fatalf("answer express item %d = %d %s", item.Ordinal, status, body) + } + version = next.Version + } + finalizeBody, _ := json.Marshal(map[string]int64{"expected_version": version}) + if status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", + string(finalizeBody), expressKey+"-finalize"); status != http.StatusOK { + t.Fatalf("finalize express attempt = %d %s", status, body) + } + result := client.result(t, who, attempt.ID) + if result["outcome"] != "demonstration" || result["kind"] != "demo_express" || result["category_decision"] != nil || + result["confirmed_grade"] != nil || result["basic_score"] != nil { + t.Fatalf("express result = %v, want a demonstration without grade, score or category decision", result) + } + var schemaVersion int16 + var decisionStored, gradeStored bool + if err := harness.pool.QueryRow(ctx, ` + SELECT schema_version, category_decision IS NOT NULL, current_confirmed_grade IS NOT NULL + FROM assessment_attempt_results WHERE attempt_id = $1`, attempt.ID).Scan(&schemaVersion, &decisionStored, &gradeStored); err != nil || + schemaVersion != 1 || decisionStored || gradeStored { + t.Fatalf("express storage = schema %d decision %v grade %v (error %v), want the plain v1 record", schemaVersion, decisionStored, gradeStored, err) + } + // The database also refuses an express result as the source of a category. + _, err := harness.pool.Exec(ctx, ` + INSERT INTO candidate_assessment_categories ( + candidate_id, specialization, grade, source_attempt_id, source_review_id, product_policy_version_id, + product_policy_version, grading_policy_version_id, opening_id, opening_manifest_sha256, + source, calibration_status, assigned_at) + SELECT $1, 'backend', 'senior', $2, review.id, review.product_policy_version_id, review.product_policy_version, + review.product_policy_version_id, review.opening_id, review.opening_manifest_sha256, + 'synthetic_demo', 'uncalibrated', now() + FROM assessment_synthetic_category_reviews AS review LIMIT 1`, who.id, attempt.ID) + assertPgError(t, "category from an express result", err, "23514", "candidate_assessment_categories_result_match") + } + after, found := readStoredCategory(t, ctx, harness.pool, high.id, "backend") + if !found || after != before { + t.Fatalf("category after express = %+v (found %v), want unchanged %+v", after, found, before) + } + if countStoredCategories(t, ctx, harness.pool, other.id) != 0 { + t.Fatal("express created a category for a candidate that had none") + } + _, historyBody := client.call(t, high, http.MethodGet, "/api/v1/me/assessment-results", "", "") + var history struct { + Items []map[string]any `json:"items"` + } + if err := json.Unmarshal(historyBody, &history); err != nil || len(history.Items) != 2 { + t.Fatalf("history after express = %s (error %v), want the two real attempts only", historyBody, err) + } + for _, item := range history.Items { + if item["kind"] == "demo_express" { + t.Fatalf("history lists a training result: %v", item) + } + } + }) + + t.Run("the category is derived only from a reviewed source inside the enabled synthetic environment", func(t *testing.T) { + unreviewed := client.run(t, other, "frontend", "intern", func(items int) int { return items }) + decision := decisionOf(t, unreviewed.result) + if unreviewed.result["outcome"] != "confirmed" || decision["status"] != "not_eligible" || decision["method"] != nil || + decision["source"] != nil || unreviewed.result["confirmed_grade"] != nil || countStoredCategories(t, ctx, harness.pool, other.id) != 0 { + t.Fatalf("perfect attempt in an unreviewed category = %v / %v, want a confirmed score without any category", unreviewed.result["outcome"], decision) + } + + // The same bank under a service that does not enable demonstration categories. + disabled := newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, &isolatedEnv, assessment.AssessmentCategoryDecisionSettings{}) + disabledClient := &categoryHTTPClient{harness: disabled, ctx: ctx, calls: 1000} + candidate := disabledClient.candidate(t, "category-disabled@example.test") + disabledRun := disabledClient.run(t, candidate, "backend", "intern", func(items int) int { return items }) + decision = decisionOf(t, disabledRun.result) + if disabledRun.result["outcome"] != "confirmed" || decision["status"] != "not_eligible" || + disabledRun.result["confirmed_grade"] != nil || countStoredCategories(t, ctx, harness.pool, candidate.id) != 0 { + t.Fatalf("perfect attempt with assignment disabled = %v / %v, want a confirmed score without any category", disabledRun.result["outcome"], decision) + } + }) + + t.Run("a stored result keeps its version and outcome after the current policy changes, and an employer reads neither", func(t *testing.T) { + resultBefore := map[uuid.UUID][]byte{ + highInternAttempt.id: highInternAttempt.body, highJuniorAttempt.id: client.resultBody(t, high, highJuniorAttempt.id), + } + historyStatus, historyBefore := client.call(t, high, http.MethodGet, "/api/v1/me/assessment-results", "", "") + if historyStatus != http.StatusOK { + t.Fatalf("history before the policy change = %d %s", historyStatus, historyBefore) + } + categoryBefore, _ := readStoredCategory(t, ctx, harness.pool, high.id, "backend") + + changed := domain.DemoProductPolicyV2() + changed.Assessment.Attempt.BasicPassMark = 9000 + newPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: changed, + }) + if err != nil || newPolicy.Version() <= bank.policy.Version() { + t.Fatalf("Publish(changed policy) = version %d, error %v, want a newer version than %d", newPolicy.Version(), err, bank.policy.Version()) + } + for attemptID, want := range resultBefore { + got := client.resultBody(t, high, attemptID) + if !bytes.Equal(got, want) { + t.Fatalf("result %s changed after the policy change:\n%s\n%s", attemptID, want, got) + } + } + if _, historyAfter := client.call(t, high, http.MethodGet, "/api/v1/me/assessment-results", "", ""); !bytes.Equal(historyAfter, historyBefore) { + t.Fatalf("history changed after the policy change:\n%s\n%s", historyBefore, historyAfter) + } + var versions struct { + Versions struct { + PolicyVersion int32 `json:"policy_version"` + } `json:"versions"` + } + if err := json.Unmarshal(highInternAttempt.body, &versions); err != nil || versions.Versions.PolicyVersion != bank.policy.Version() { + t.Fatalf("result policy version = %d (error %v), want the pinned %d, not the current %d", + versions.Versions.PolicyVersion, err, bank.policy.Version(), newPolicy.Version()) + } + if categoryAfter, _ := readStoredCategory(t, ctx, harness.pool, high.id, "backend"); categoryAfter != categoryBefore { + t.Fatalf("category changed with the policy: %+v -> %+v", categoryBefore, categoryAfter) + } + + employer := client.employer(t, "category-employer@example.test") + for _, path := range []string{ + "/api/v1/me/assessment-results", + "/api/v1/me/assessment-attempts/" + highInternAttempt.id.String(), + "/api/v1/me/assessment-attempts/" + highInternAttempt.id.String() + "/result", + } { + status, body := client.call(t, employer, http.MethodGet, path, "", "") + if status != http.StatusForbidden && status != http.StatusNotFound { + t.Fatalf("employer read of %s = %d %s, want 403 or 404", path, status, body) + } + for _, leak := range []string{"reference_answer", "answer_key", highInternAttempt.id.String(), "category_decision"} { + if strings.Contains(string(body), leak) { + t.Fatalf("employer response for %s leaks %q: %s", path, leak, body) + } + } + } + + // The opened categories are bound to the policy they were opened under, so + // no attempt starts under the changed policy until an operator opens the + // categories again. A new pass mark therefore cannot reach a result, or a + // category, through a bank that was attested for another policy. + createBody := assessmentAttemptCreateBodyWithGrade(t, "backend", "intern") + if status, body := client.call(t, other, http.MethodPost, "/api/v1/me/assessment-attempts", createBody, uuid.NewString()); status != http.StatusConflict { + t.Fatalf("attempt under the changed policy = %d %s, want 409 until the categories are reopened", status, body) + } + }) + + t.Run("an organization reads only the current category and nothing about the attempts", func(t *testing.T) { + queries := sqlc.New(harness.pool) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: queries, identity: identity, + organizations: organizationFixture{ + ctx: ctx, pool: harness.pool, identity: identity, + transactor: postgresadapter.NewTransactor(harness.pool), now: now, + }, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + owner := fixture.organizations.employer(t, "category-projection-owner@example.test") + organization := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Category projection organization"), now) + for _, candidate := range []categoryHTTPCandidate{high, low} { + consent := fixture.grant(t, candidate.id, domain.ConsentPurposePublication, privacyC2Version, now) + fixture.publish(t, candidate.id, consent.ID(), 0, domain.CardFieldCategories) + } + sources, err := postgresadapter.NewPrivacyCohortStore(harness.pool).ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources() error = %v", err) + } + categories := map[uuid.UUID][]domain.CandidateViewConfirmedCategoryInput{} + for _, source := range sources { + categories[source.CandidateID()] = source.Input("cv1_"+strings.Repeat("A", 43), now).ConfirmedCategories + } + wantHigh := []domain.CandidateViewConfirmedCategoryInput{{ + Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard, + Basis: domain.AssessmentCategorySourceSyntheticDemo, + }} + if len(sources) != 2 || fmt.Sprint(categories[high.id]) != fmt.Sprint(wantHigh) || len(categories[low.id]) != 0 { + t.Fatalf("organization projection = %v, want only the current intern category of the confirmed candidate", categories) + } + view, err := domain.NewAnonymousCandidateView(domain.CandidateViewInput{ + Pseudonym: "cv1_" + strings.Repeat("A", 43), PublishedFields: mustCardFieldSet(t, domain.CardFieldCategories), + ConfirmedCategories: categories[high.id], AsOf: now, + }) + if err != nil { + t.Fatalf("NewAnonymousCandidateView() error = %v", err) + } + encoded, err := json.Marshal(view.DTO()) + if err != nil { + t.Fatalf("marshal anonymous view: %v", err) + } + for _, leak := range []string{highInternAttempt.id.String(), highJuniorAttempt.id.String(), "score", "points", "policy", "review", "outcome", "decided_at", "not_confirmed"} { + if strings.Contains(string(encoded), leak) { + t.Fatalf("organization-facing view leaks %q: %s", leak, encoded) + } + } + + // The category is exactly as visible as the card: an organization that the + // candidate hid, and every organization after a C2 revocation, get nothing. + otherOrganization := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Category projection organization B"), now) + fixture.hide(t, high.id, organization.ID(), now.Add(time.Second)) + reader := postgresadapter.NewPrivacyCohortStore(harness.pool) + hiddenFrom, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(hidden) error = %v", err) + } + visibleElsewhere, err := reader.ListVisibleCandidateViewSources(ctx, otherOrganization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(other) error = %v", err) + } + if privacyCohortHasSource(hiddenFrom, high.id) || !privacyCohortHasSource(visibleElsewhere, high.id) { + t.Fatalf("hidden organization sees the candidate = %v, other organization sees it = %v; want false and true", + privacyCohortHasSource(hiddenFrom, high.id), privacyCohortHasSource(visibleElsewhere, high.id)) + } + fixture.revokeC2(t, high.id, now.Add(2*time.Second)) + for _, id := range []uuid.UUID{organization.ID(), otherOrganization.ID()} { + revoked, err := reader.ListVisibleCandidateViewSources(ctx, id) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(revoked) error = %v", err) + } + if privacyCohortHasSource(revoked, high.id) { + t.Fatalf("organization %s still sees a candidate whose C2 was revoked", id) + } + } + }) +} + +func mustCardFieldSet(t *testing.T, fields ...domain.CardField) domain.CardFieldSet { + t.Helper() + set, err := domain.NewCardFieldSet(fields) + if err != nil { + t.Fatalf("NewCardFieldSet() error = %v", err) + } + return set +} + +// jsonEqual compares two decoded JSON values by their canonical encoding. +func jsonEqual(t *testing.T, left, right any) bool { + t.Helper() + leftEncoded, err := json.Marshal(left) + if err != nil { + t.Fatalf("marshal left JSON value: %v", err) + } + rightEncoded, err := json.Marshal(right) + if err != nil { + t.Fatalf("marshal right JSON value: %v", err) + } + return bytes.Equal(leftEncoded, rightEncoded) +} + +// moveFinishedAttemptBack moves a finished attempt, its stored result and the +// category taken from it back in time as one consistent record. The next grade +// is offered only after the promotion interval, which counts on database time; +// this fixture replaces days of waiting. Triggers are off for this one +// transaction because they exist to refuse exactly such rewrites. +func moveFinishedAttemptBack(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID, by time.Duration) { + t.Helper() + shift := fmt.Sprintf("%d seconds", int64(by.Seconds())) + snapshot := "result_snapshot" + for _, path := range []string{"attempt,started_at", "attempt,expires_at", "attempt,finished_at", "decided_at"} { + snapshot = fmt.Sprintf(`jsonb_set(%[1]s, '{%[2]s}', to_jsonb(to_char(((result_snapshot #>> '{%[2]s}')::timestamptz - $2::interval), + 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')))`, snapshot, path) + } + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin attempt time fixture: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + for _, statement := range []struct { + name, sql string + }{ + {"session settings", `SET LOCAL session_replication_role = replica`}, + {"time zone", `SET LOCAL TIME ZONE 'UTC'`}, + } { + if _, err := tx.Exec(ctx, statement.sql); err != nil { + t.Fatalf("set %s for the attempt time fixture: %v", statement.name, err) + } + } + for _, statement := range []struct { + name, sql string + rows int64 + }{ + {"attempt", `UPDATE assessment_attempts SET created_at = created_at - $2::interval, updated_at = updated_at - $2::interval, + expires_at = expires_at - $2::interval, chain_deadline = chain_deadline - $2::interval, + session_started_at = session_started_at - $2::interval, last_activity_at = last_activity_at - $2::interval, + ended_at = ended_at - $2::interval WHERE id = $1`, 1}, + {"items", `UPDATE assessment_attempt_items SET answered_at = answered_at - $2::interval WHERE attempt_id = $1`, -1}, + {"result", `UPDATE assessment_attempt_results SET decided_at = decided_at - $2::interval, + category_decision = CASE WHEN category_decision IS NULL THEN NULL ELSE jsonb_set(category_decision, '{decided_at}', + to_jsonb(to_char(((category_decision ->> 'decided_at')::timestamptz - $2::interval), 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'))) END, + result_snapshot = ` + snapshot + ` WHERE attempt_id = $1`, 1}, + {"category", `UPDATE candidate_assessment_categories SET assigned_at = assigned_at - $2::interval WHERE source_attempt_id = $1`, -1}, + } { + tag, err := tx.Exec(ctx, statement.sql, attemptID, shift) + if err != nil || statement.rows >= 0 && tag.RowsAffected() != statement.rows { + t.Fatalf("move %s back = %d rows, error %v", statement.name, tag.RowsAffected(), err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit attempt time fixture: %v", err) + } +} + +func TestAssessmentCategoryAttestCommandEnablesAssignment(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 2*assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, &isolatedEnv, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), false) + scored := int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems) + perfect := func(int) int { return scored } + client := &categoryHTTPClient{harness: harness, ctx: ctx} + lookup := func(key string) (string, bool) { return databaseURL, key == "DATABASE_URL" } + attest := func(args ...string) (string, error) { + var output bytes.Buffer + err := categoryattest.Run(ctx, args, lookup, &output) + return output.String(), err + } + + before := client.candidate(t, "attest-before@example.test") + beforeRun := client.run(t, before, "backend", "intern", perfect) + if decision := decisionOf(t, beforeRun.result); beforeRun.result["outcome"] != "confirmed" || decision["status"] != "not_eligible" || + countStoredCategories(t, ctx, harness.pool, before.id) != 0 { + t.Fatalf("attempt before the attestation = %v / %v, want a confirmed score without any category", beforeRun.result["outcome"], decision) + } + + output, err := attest("attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:stand-admin") + if err != nil || !strings.Contains(output, "\nattested: category backend-intern") || !strings.Contains(output, "synthetic demonstration only") { + t.Fatalf("attest = %q, %v, want a stored attestation and the synthetic-only note", output, err) + } + var reviews int + var reviewedBy string + if err := harness.pool.QueryRow(ctx, `SELECT count(*), min(reviewed_by) FROM assessment_synthetic_category_reviews WHERE category = 'backend-intern' + AND product_policy_version_id = $1`, bank.policy.ID().UUID()).Scan(&reviews, &reviewedBy); err != nil || reviews != 1 || reviewedBy != "operator:stand-admin" { + t.Fatalf("stored attestations = %d by %q (error %v), want one by the actor handle", reviews, reviewedBy, err) + } + if again, err := attest("attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:other"); err != nil || + !strings.Contains(again, "\nalready attested") { + t.Fatalf("repeated attest = %q, %v, want already attested", again, err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_synthetic_category_reviews`).Scan(&reviews); err != nil || reviews != 1 { + t.Fatalf("attestations after the repeat = %d (error %v), want still one", reviews, err) + } + + // Operators who attest the same source at the same time store one row; the + // others are told that it already exists. + if _, err := harness.pool.Exec(ctx, `ALTER TABLE assessment_synthetic_category_reviews DISABLE TRIGGER assessment_synthetic_category_review_refuse_mutation`); err != nil { + t.Fatalf("prepare the concurrent attestation case: %v", err) + } + if _, err := harness.pool.Exec(ctx, `DELETE FROM assessment_synthetic_category_reviews`); err != nil { + t.Fatalf("clear the attestation for the concurrent case: %v", err) + } + if _, err := harness.pool.Exec(ctx, `ALTER TABLE assessment_synthetic_category_reviews ENABLE TRIGGER assessment_synthetic_category_review_refuse_mutation`); err != nil { + t.Fatalf("restore the attestation guard: %v", err) + } + const operators = 6 + outputs := make([]string, operators) + failures := make([]error, operators) + var group sync.WaitGroup + for index := range operators { + group.Add(1) + go func() { + defer group.Done() + outputs[index], failures[index] = attest("attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", + "--actor", fmt.Sprintf("operator:stand-admin-%d", index)) + }() + } + group.Wait() + created := 0 + for index := range operators { + if failures[index] != nil { + t.Fatalf("concurrent attest %d failed: %v", index, failures[index]) + } + if strings.Contains(outputs[index], "\nattested: category") { + created++ + } else if !strings.Contains(outputs[index], "\nalready attested") { + t.Fatalf("concurrent attest %d output = %q", index, outputs[index]) + } + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_synthetic_category_reviews`).Scan(&reviews); err != nil || created != 1 || reviews != 1 { + t.Fatalf("concurrent attestations created %d outputs and %d rows (error %v), want exactly one", created, reviews, err) + } + // The repository itself reports a duplicate instead of failing. + var row struct { + opening uuid.UUID + manifest []byte + category string + } + if err := harness.pool.QueryRow(ctx, `SELECT opening_id, opening_manifest_sha256, category FROM assessment_synthetic_category_reviews`). + Scan(&row.opening, &row.manifest, &row.category); err != nil { + t.Fatalf("read the stored attestation: %v", err) + } + var manifestHash [32]byte + copy(manifestHash[:], row.manifest) + duplicate, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{ + ID: uuid.New(), OpeningID: row.opening, Category: domain.AssessmentCategory(row.category), + Source: domain.AssessmentCategorySourceSyntheticDemo, OpeningManifestHash: manifestHash, + ProductPolicyVersionID: bank.policy.ID(), ProductPolicyVersion: bank.policy.Version(), + ReviewedBy: domain.AssessmentOperator("operator:late"), ReviewedAt: time.Now().UTC(), + }) + if err != nil { + t.Fatalf("build duplicate attestation: %v", err) + } + err = postgresadapter.NewTransactor(harness.pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + stored, err := unit.AssessmentAttempts().CreateSyntheticCategoryReview(ctx, duplicate) + if err != nil || stored { + return fmt.Errorf("duplicate attestation stored=%v error=%v, want false and no error", stored, err) + } + return nil + }) + if err != nil { + t.Fatal(err) + } + + after := client.candidate(t, "attest-after@example.test") + afterRun := client.run(t, after, "backend", "intern", perfect) + stored, found := readStoredCategory(t, ctx, harness.pool, after.id, "backend") + if decision := decisionOf(t, afterRun.result); decision["status"] != "assigned" || afterRun.result["confirmed_grade"] != "intern" || + !found || stored.grade != "intern" || stored.source != "synthetic_demo" { + t.Fatalf("attempt after the attestation = %v / %v / %+v, want an assigned synthetic intern category", afterRun.result["outcome"], decisionOf(t, afterRun.result), stored) + } + + // A category that is not open and malformed arguments are refused without + // storing anything. The policy check is covered by the domain tests. + if _, err := attest("attest", "--specialization", "mobile", "--grade", "senior", "--actor", "operator:stand-admin"); err == nil { + t.Fatal("attest accepted a category that is not open") + } + for _, args := range [][]string{ + {"attest", "--specialization", "backend", "--grade", "intern", "--actor", "stand-admin"}, + {"attest", "--specialization", "backend"}, + } { + if _, err := attest(args...); err == nil { + t.Fatalf("attest(%v) accepted invalid arguments", args) + } + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_synthetic_category_reviews`).Scan(&reviews); err != nil || reviews != 1 { + t.Fatalf("attestations after refusals = %d (error %v), want still one", reviews, err) + } +} + +// A demo_basic policy with another pass mark is as good as any other: the +// threshold belongs to the accepted policy version, not to the database or the +// domain. +func TestAssessmentCategoryUsesTheThresholdOfItsOwnPolicy(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 2*assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, &isolatedEnv, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + strict := domain.DemoProductPolicyV2() + strict.Assessment.Attempt.BasicPassMark = 9000 + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, strict, false) + lookup := func(key string) (string, bool) { return databaseURL, key == "DATABASE_URL" } + var output bytes.Buffer + if err := categoryattest.Run(ctx, []string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:stand-admin"}, lookup, &output); err != nil { + t.Fatalf("attest under the 9000 policy = %q, %v, want the policy accepted", output.String(), err) + } + scored := int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems) + threshold := passPoints(scored, 9000) + if threshold == passPoints(scored, 8000) { + t.Fatalf("scenario threshold %d equals the 8000 threshold; the case proves nothing", threshold) + } + client := &categoryHTTPClient{harness: harness, ctx: ctx} + + below := client.candidate(t, "strict-below@example.test") + belowRun := client.run(t, below, "backend", "intern", func(int) int { return threshold - 1 }) + if decision := decisionOf(t, belowRun.result); belowRun.result["outcome"] != "not_confirmed" || decision["status"] != "not_confirmed" || + countStoredCategories(t, ctx, harness.pool, below.id) != 0 { + t.Fatalf("attempt at k-1 of 9000 = %v / %v, want not_confirmed without a category", belowRun.result["outcome"], decision) + } + at := client.candidate(t, "strict-at@example.test") + atRun := client.run(t, at, "backend", "intern", func(int) int { return threshold }) + stored, found := readStoredCategory(t, ctx, harness.pool, at.id, "backend") + score := atRun.result["basic_score"].(map[string]any) + if decision := decisionOf(t, atRun.result); atRun.result["outcome"] != "confirmed" || decision["status"] != "assigned" || + int(score["pass_points"].(float64)) != threshold || !found || stored.grade != "intern" { + t.Fatalf("attempt at k of 9000 = %v / %v / %+v (found %v), want an assigned category by the policy's own threshold", atRun.result["outcome"], decisionOf(t, atRun.result), stored, found) + } +} diff --git a/backend/integration_test/assessment_category_read_http_test.go b/backend/integration_test/assessment_category_read_http_test.go new file mode 100644 index 0000000..45c17b0 --- /dev/null +++ b/backend/integration_test/assessment_category_read_http_test.go @@ -0,0 +1,166 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + profileusecase "lincodex/backend/internal/usecase/profile" +) + +// TestConfirmedCategoryReadsOverHTTP checks the two candidate reads that show +// the confirmed category, with its basis: the availability and the profile. A +// candidate without a category gets null and an empty list. A higher passing +// result replaces the category, and a lower passing result leaves it as it is. +func TestConfirmedCategoryReadsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 2*assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, &isolatedEnv, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, + func(parts assessmentHarnessParts) []v1.HandlerOption { + return []v1.HandlerOption{v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now)))} + }) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true) + threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) + client := &categoryHTTPClient{harness: harness, ctx: ctx} + + none := client.candidate(t, "category-read-none@example.test") + failed := client.candidate(t, "category-read-failed@example.test") + held := client.candidate(t, "category-read-held@example.test") + + t.Run("a candidate without any result sees no confirmed category in either read", func(t *testing.T) { + assertAvailabilityConfirmation(t, client, none, "backend", nil, nil) + assertProfileConfirmedCategoriesEmpty(t, client, none) + }) + + t.Run("a candidate whose attempt confirmed nothing still sees no category", func(t *testing.T) { + run := client.run(t, failed, "backend", "intern", func(int) int { return threshold - 1 }) + if run.result["outcome"] != "not_confirmed" { + t.Fatalf("failing run outcome = %v, want not_confirmed", run.result["outcome"]) + } + assertAvailabilityConfirmation(t, client, failed, "backend", nil, nil) + assertProfileConfirmedCategoriesEmpty(t, client, failed) + }) + + var intern, junior attemptRun + t.Run("an assigned category is shown with its basis and attempt in both reads", func(t *testing.T) { + intern = client.run(t, held, "backend", "intern", func(int) int { return threshold }) + assertAvailabilityConfirmation(t, client, held, "backend", "intern", "synthetic_demo") + assertAvailabilityConfirmation(t, client, held, "frontend", nil, nil) + assertProfileBackendCategory(t, client, held, "intern", "synthetic_demo", intern) + }) + + t.Run("a higher passing result replaces the category and a lower one never lowers it", func(t *testing.T) { + // The promotion interval counts on database time, so the finished intern + // attempt is moved past it instead of waiting for days. + moveFinishedAttemptBack(t, ctx, harness.pool, intern.id, categoryHTTPPromotionGap) + junior = client.run(t, held, "backend", "junior", func(int) int { return threshold }) + if decision := decisionOf(t, junior.result); decision["status"] != "assigned" { + t.Fatalf("junior decision = %v, want assigned", decision) + } + assertAvailabilityConfirmation(t, client, held, "backend", "junior", "synthetic_demo") + assertProfileBackendCategory(t, client, held, "junior", "synthetic_demo", junior) + + lower := client.run(t, held, "backend", "intern", func(int) int { return threshold }) + if decision := decisionOf(t, lower.result); decision["status"] != "unchanged" || decision["current_confirmed_grade"] != "junior" { + t.Fatalf("lower passing decision = %v, want unchanged at junior", decision) + } + assertAvailabilityConfirmation(t, client, held, "backend", "junior", "synthetic_demo") + assertProfileBackendCategory(t, client, held, "junior", "synthetic_demo", junior) + }) +} + +// assertAvailabilityConfirmation checks the confirmed grade and basis of one +// specialization in the availability read. A nil argument stands for JSON null. +func assertAvailabilityConfirmation(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate, specialization string, grade, basis any) { + t.Helper() + status, body := client.call(t, who, http.MethodGet, "/api/v1/me/assessment-availability", "", "") + if status != http.StatusOK { + t.Fatalf("read availability = %d %s", status, body) + } + var read struct { + Specializations []map[string]any `json:"specializations"` + } + if err := json.Unmarshal(body, &read); err != nil { + t.Fatalf("decode availability: %v", err) + } + for _, item := range read.Specializations { + if item["specialization"] != specialization { + continue + } + if item["confirmed_grade"] != grade || item["confirmed_basis"] != basis { + t.Fatalf("availability %s = grade %v basis %v, want grade %v basis %v", specialization, item["confirmed_grade"], item["confirmed_basis"], grade, basis) + } + return + } + t.Fatalf("availability lists no %s specialization: %s", specialization, body) +} + +func readProfileBody(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate) []byte { + t.Helper() + status, body := client.call(t, who, http.MethodGet, "/api/v1/me/profile", "", "") + if status != http.StatusOK { + t.Fatalf("read profile = %d %s", status, body) + } + return body +} + +func assertProfileConfirmedCategoriesEmpty(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate) { + t.Helper() + if body := readProfileBody(t, client, who); !strings.Contains(string(body), `"confirmed_categories":[]`) { + t.Fatalf("profile = %s, want an empty confirmed_categories list", body) + } +} + +// assertProfileBackendCategory checks that the profile holds exactly one +// confirmed category, the backend one, with its grade, basis, and the attempt +// whose result assigned it. The assignment time is the decision time of that +// result. +func assertProfileBackendCategory(t *testing.T, client *categoryHTTPClient, who categoryHTTPCandidate, grade, basis string, attempt attemptRun) { + t.Helper() + var profile struct { + ConfirmedCategories []map[string]any `json:"confirmed_categories"` + } + if err := json.Unmarshal(readProfileBody(t, client, who), &profile); err != nil { + t.Fatalf("decode profile: %v", err) + } + if len(profile.ConfirmedCategories) != 1 { + t.Fatalf("confirmed_categories = %v, want exactly the backend category", profile.ConfirmedCategories) + } + category := profile.ConfirmedCategories[0] + if len(category) != 5 { + t.Fatalf("confirmed category has %d properties, want exactly specialization, grade, basis, confirmed_at, attempt_id: %v", len(category), category) + } + if category["specialization"] != "backend" || category["grade"] != grade || category["basis"] != basis || + category["attempt_id"] != attempt.id.String() { + t.Fatalf("confirmed category = %v, want backend %s with basis %s from attempt %s", category, grade, basis, attempt.id) + } + confirmedAt, ok := category["confirmed_at"].(string) + if !ok { + t.Fatalf("confirmed_at = %v, want a timestamp", category["confirmed_at"]) + } + assignedAt, err := time.Parse(time.RFC3339Nano, confirmedAt) + if err != nil { + t.Fatalf("parse confirmed_at %q: %v", confirmedAt, err) + } + decidedAt, err := time.Parse(time.RFC3339Nano, attempt.result["decided_at"].(string)) + if err != nil { + t.Fatalf("parse decided_at: %v", err) + } + if !assignedAt.Equal(decidedAt) { + t.Fatalf("confirmed_at = %s, want the decision time %s of the attempt", assignedAt, decidedAt) + } +} diff --git a/backend/integration_test/assessment_choice_http_test.go b/backend/integration_test/assessment_choice_http_test.go new file mode 100644 index 0000000..4d6f207 --- /dev/null +++ b/backend/integration_test/assessment_choice_http_test.go @@ -0,0 +1,299 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "slices" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" +) + +// choiceTableBankFamilies returns the families of a bank that offers every new +// answer format: a choice family whose distractors come from error models, a +// table family with integer answers, and a table family with choice answers. +// They reuse the rubric and the identity of the first demo family. +func choiceTableBankFamilies(t *testing.T, base assessment.BundleFamily) []assessment.BundleFamily { + t.Helper() + choice := base + choice.Key = "choice-lru-hits" + choice.SeedGenerator = domain.AssessmentSeedGenerator{ + Algorithm: "lru_hits_choice.v1", + Parameters: map[string]domain.AssessmentParameterRange{ + "accesses": {Min: 12, Max: 30}, "keys": {Min: 4, Max: 8}, "capacity": {Min: 2, Max: 4}, + }, + StatementTemplate: "A cache of capacity {{.capacity}} drops its least recently used key when it is full. Keys are read in this order: {{.sequence}}. How many reads find their key in the cache?", + } + choice.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Simulate the cache."} + + integerTable := base + integerTable.Key = "table-integer-limits" + integerTable.SeedGenerator = domain.AssessmentSeedGenerator{ + StatementTemplate: "A pool opens {{.connections}} connections at most and each request holds one for {{.seconds}} seconds. How many requests per minute can it serve at most?", + Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{ + {Values: map[string]string{"connections": "10", "seconds": "2"}, Answer: "300"}, + {Values: map[string]string{"connections": "4", "seconds": "3"}, Answer: "80"}, + {Values: map[string]string{"connections": "6", "seconds": "5"}, Answer: "72"}, + {Values: map[string]string{"connections": "20", "seconds": "1"}, Answer: "1200"}, + }}, + } + integerTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatInteger, ReferenceSolution: "Multiply by sixty and divide by the hold time."} + + choiceTable := base + choiceTable.Key = "table-choice-status" + choiceTable.SeedGenerator = domain.AssessmentSeedGenerator{ + StatementTemplate: "Which status code does an API return for {{.situation}}?", + Table: &domain.AssessmentVariantTable{Rows: []domain.AssessmentVariantRow{ + {Values: map[string]string{"situation": "a resource that does not exist"}, Answer: "404", Distractors: []string{"400", "410", "500"}}, + {Values: map[string]string{"situation": "a call without credentials"}, Answer: "401", Distractors: []string{"403", "407", "511"}}, + {Values: map[string]string{"situation": "an update on a stale version"}, Answer: "412", Distractors: []string{"409", "422", "428"}}, + }}, + } + choiceTable.AnswerKey = domain.AssessmentAnswerKey{AnswerFormat: domain.AnswerFormatChoice, ReferenceSolution: "Match the situation to the status code."} + return []assessment.BundleFamily{choice, integerTable, choiceTable} +} + +// allowedItemKeys are the fields that a candidate item may carry per format. +var allowedItemContentKeys = map[string][]string{ + "number": {"format", "unit"}, + "choice": {"format", "multiple", "options"}, +} + +func TestAssessmentChoiceAndTableFamiliesAreServedAndGradedOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + + source := loadDemoBundleFile(t) + source.Families = choiceTableBankFamilies(t, source.Families[0]) + seedAssessmentAttemptHTTPBankFrom(ctx, t, harness.pool, nil, source) + + // The bank holds both kinds of generator: the table families are stored + // with hash scheme 2 and the algorithmic family with scheme 1. + for scheme, want := range map[int]bool{1: true, 2: true} { + var stored int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_families WHERE hash_scheme = $1`, scheme).Scan(&stored); err != nil || (stored > 0) != want { + t.Fatalf("families with hash scheme %d = %d, %v, want some", scheme, stored, err) + } + } + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "choice-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "203.0.113.140:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "203.0.113.141:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, cookie, csrf, "203.0.113.142:1234") + + create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, + "choice-flow-create", "203.0.113.143:1234") + if create.Code != http.StatusCreated { + t.Fatalf("create real attempt = %d %s; logs: %s", create.Code, create.Body.String(), harness.logs.String()) + } + var attempt assessmentAnswerHTTPAttempt + if err := json.Unmarshal(create.Body.Bytes(), &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil { + t.Fatalf("created attempt = %+v, decode error %v", attempt, err) + } + items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) + formats := make(map[string]int) + for _, item := range items { + formats[item.Variant.AnswerFormat]++ + } + if formats[domain.AnswerFormatChoice] < 2 || formats[domain.AnswerFormatInteger] < 1 { + t.Fatalf("frozen formats = %v, want at least two choice items and one integer item", formats) + } + + attemptsPath := "/api/v1/me/assessment-attempts/" + attempt.ID.String() + assertCandidateItem := func(label string, body []byte, item assessmentAnswerHTTPItem) { + t.Helper() + assertAssessmentChoiceItemDTO(t, label, body, item) + } + assertCandidateItem("create response", create.Body.Bytes(), items[0]) + + // Answers: a choice item alternates between a wrong and a correct option + // (starting wrong), and every other item is answered correctly. + version, choiceIndex := attempt.Version, 0 + var wantCorrect []bool + for _, item := range items { + correct := true + if item.Variant.AnswerFormat == domain.AnswerFormatChoice { + correct = choiceIndex%2 == 1 + choiceIndex++ + } + wantCorrect = append(wantCorrect, correct) + if item.Ordinal == 1 { + assertChoiceAnswerProblems(t, harness, attemptsPath, cookie.Value, csrf, version, item) + } + body := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct) + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("choice-flow-item-%d", item.Ordinal), + fmt.Sprintf("203.0.113.%d:1234", 150+item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil || next.Version != version+1 { + t.Fatalf("answer item %d = %d %s, want version %d", item.Ordinal, response.Code, response.Body.String(), version+1) + } + if int(item.Ordinal) < len(items) { + assertCandidateItem(fmt.Sprintf("response after item %d", item.Ordinal), response.Body.Bytes(), items[item.Ordinal]) + } + version = next.Version + } + + // The wrong-then-correct alternation of the choice items reached the + // result through the key: the server scored the first max_points items. + finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version}) + if err != nil { + t.Fatalf("marshal finalization: %v", err) + } + finalized := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/finalize", string(finalizeBody), + sessionHTTPTestOrigin, cookie.Value, csrf, "choice-flow-finalize", "203.0.113.190:1234") + if finalized.Code != http.StatusOK { + t.Fatalf("finalize = %d %s", finalized.Code, finalized.Body.String()) + } + result := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, attemptsPath+"/result", "", "", cookie.Value, "", "", "203.0.113.191:1234") + var document struct { + BasicScore struct { + Points int `json:"points"` + MaxPoints int `json:"max_points"` + } `json:"basic_score"` + } + if result.Code != http.StatusOK || json.Unmarshal(result.Body.Bytes(), &document) != nil || document.BasicScore.MaxPoints < 1 { + t.Fatalf("result = %d %s, want a basic score", result.Code, result.Body.String()) + } + wantPoints := 0 + for _, correct := range wantCorrect[:document.BasicScore.MaxPoints] { + if correct { + wantPoints++ + } + } + if document.BasicScore.Points != wantPoints || wantPoints == document.BasicScore.MaxPoints { + t.Fatalf("score = %d of %d, want %d: every wrong choice scores nothing and every correct one scores", document.BasicScore.Points, document.BasicScore.MaxPoints, wantPoints) + } + for _, private := range []string{"ReferenceAnswer", "answer_key", "option_ids", "distractor"} { + if strings.Contains(result.Body.String(), private) { + t.Fatalf("result exposes %q: %s", private, result.Body.String()) + } + } + + // Every accepted answer left a signal observation; a choice is observed as + // an answer of a small answer space, like an integer. + var observed, choiceObserved int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_answer_observations WHERE attempt_id=$1`, attempt.ID).Scan(&observed); err != nil || observed != len(items) { + t.Fatalf("answer observations = %d, %v, want %d", observed, err, len(items)) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_answer_observations WHERE attempt_id=$1 AND answer_format='integer'`, attempt.ID).Scan(&choiceObserved); err != nil || + choiceObserved != formats[domain.AnswerFormatChoice]+formats[domain.AnswerFormatInteger] { + t.Fatalf("observations of the integer class = %d, %v, want %d", choiceObserved, err, formats[domain.AnswerFormatChoice]+formats[domain.AnswerFormatInteger]) + } +} + +// assertAssessmentChoiceItemDTO checks that the candidate sees the item of +// the attempt in the allowlisted shape: for a choice item the opaque option +// IDs and texts in the stored order, and no key or service field anywhere. +func assertAssessmentChoiceItemDTO(t *testing.T, label string, body []byte, item assessmentAnswerHTTPItem) { + t.Helper() + var document struct { + CurrentItem map[string]json.RawMessage `json:"current_item"` + } + if err := json.Unmarshal(body, &document); err != nil || document.CurrentItem == nil { + t.Fatalf("%s: no current item in %s (%v)", label, body, err) + } + var itemKeys []string + for key := range document.CurrentItem { + itemKeys = append(itemKeys, key) + } + slices.Sort(itemKeys) + var id uuid.UUID + if !slices.Equal(itemKeys, []string{"content", "id", "prompt", "sequence"}) || + json.Unmarshal(document.CurrentItem["id"], &id) != nil || id != item.ID { + t.Fatalf("%s: item keys %v for item %s, want exactly content, id, prompt, and sequence of %s", label, itemKeys, id, item.ID) + } + var content map[string]json.RawMessage + if err := json.Unmarshal(document.CurrentItem["content"], &content); err != nil { + t.Fatalf("%s: decode content: %v", label, err) + } + var format string + if err := json.Unmarshal(content["format"], &format); err != nil { + t.Fatalf("%s: decode content format: %v", label, err) + } + var contentKeys []string + for key := range content { + contentKeys = append(contentKeys, key) + } + slices.Sort(contentKeys) + if want, known := allowedItemContentKeys[format]; !known || !slices.Equal(contentKeys, want) { + t.Fatalf("%s: content of format %q has keys %v, want %v", label, format, contentKeys, want) + } + if item.Variant.AnswerFormat == domain.AnswerFormatChoice { + var options []map[string]string + if err := json.Unmarshal(content["options"], &options); err != nil || len(options) != len(item.Variant.Options) { + t.Fatalf("%s: options = %v, %v, want %d", label, options, err, len(item.Variant.Options)) + } + for position, option := range options { + stored := item.Variant.Options[position] + if len(option) != 2 || option["id"] != stored.ID || option["text"] != stored.Text { + t.Fatalf("%s: option %d = %v, want only the ID and the text of the stored option", label, position, option) + } + } + if string(content["multiple"]) != "false" { + t.Fatalf("%s: multiple = %s, want false", label, content["multiple"]) + } + } + for _, private := range []string{"ReferenceAnswer", "reference", "answer_key", "distractor", "mistake", "correct", "\"seed\"", "variant", "\"row\""} { + if strings.Contains(string(body), private) { + t.Fatalf("%s: candidate response contains %q: %s", label, private, body) + } + } +} + +// assertChoiceAnswerProblems checks that an option the item does not have and +// a selection of two options are refused as invalid input, without an answer +// being stored. It is a no-op for an item that is not a choice. +func assertChoiceAnswerProblems( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attemptsPath, session, csrf string, + version int64, + item assessmentAnswerHTTPItem, +) { + t.Helper() + if item.Variant.AnswerFormat != domain.AnswerFormatChoice { + return + } + for name, selection := range map[string][]string{ + "an option of no item": {"onotanoption"}, + "two options at once": {item.Variant.Options[0].ID, item.Variant.Options[1].ID}, + } { + encoded, err := json.Marshal(map[string]any{ + "expected_version": version, "item_id": item.ID, + "answer": map[string]any{"format": "choice", "option_ids": selection}, + }) + if err != nil { + t.Fatalf("marshal %s: %v", name, err) + } + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, attemptsPath+"/answers", string(encoded), + sessionHTTPTestOrigin, session, csrf, "choice-flow-bad-"+strings.ReplaceAll(name, " ", "-"), "203.0.113.149:1234") + if response.Code != http.StatusBadRequest { + t.Fatalf("answer with %s = %d %s, want 400", name, response.Code, response.Body.String()) + } + } +} diff --git a/backend/integration_test/assessment_leak_trace_http_test.go b/backend/integration_test/assessment_leak_trace_http_test.go new file mode 100644 index 0000000..9a07332 --- /dev/null +++ b/backend/integration_test/assessment_leak_trace_http_test.go @@ -0,0 +1,215 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "fmt" + "net/http" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/cli/leaktrace" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" +) + +// TestAssessmentLeakTraceOverHTTP checks, with PostgreSQL, that the operator +// search finds the real attempt behind the text that the page presented: by the +// invisible mark, then by the statement and its wording once the mark is gone, +// then by the visible code of a screenshot's text. It checks that unrelated text +// is not found, that every search is audited without the text and the audit is +// immutable and outlives the attempt, that a search changes no attempt, review, +// or result, and that the command wiring reads the same secret as the server. +func TestAssessmentLeakTraceOverHTTP(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + env := bootstrap(t, postgresService, redisService) + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + t.Cleanup(harness.pool.Close) + signals := reviewTestSignalPolicy() + seedAssessmentAttemptHTTPBankWithSignals(ctx, t, harness.pool, &signals) + + first := newReviewCandidate(ctx, t, harness, "leak-first@example.test", "192.0.2", 1) + second := newReviewCandidate(ctx, t, harness, "leak-second@example.test", "192.0.3", 1) + firstAttempt := leakTraceCreate(t, harness, first, "leak-first-create", "192.0.2.30:1234") + secondAttempt := leakTraceCreate(t, harness, second, "leak-second-create", "192.0.3.30:1234") + if firstAttempt.code == secondAttempt.code || firstAttempt.prompt == secondAttempt.prompt { + t.Fatal("two attempts were presented the same code or the same marked prompt") + } + + tracer, err := assessment.NewLeakTracer(postgresadapter.NewTransactor(harness.pool), harness.keyring, harness.keyring) + if err != nil { + t.Fatalf("NewLeakTracer() error = %v", err) + } + trace := func(text, code string) assessment.LeakTraceResult { + t.Helper() + result, err := tracer.Trace(ctx, assessment.LeakTraceCommand{Actor: "operator:integration", Text: text, Code: code}) + if err != nil { + t.Fatalf("Trace() error = %v", err) + } + return result + } + before := leakTraceFacts(t, ctx, harness) + + // The text as presented, inside a message: the invisible mark names the attempt. + marked := trace("Look what I got at the test: "+firstAttempt.prompt+" any ideas?", "") + if marked.Status != domain.AssessmentLeakTraceFound || marked.Method != domain.AssessmentLeakTraceInvisibleMark || + marked.AttemptID != domain.AssessmentAttemptID(firstAttempt.id) || marked.EvidenceBits != 50 { + t.Fatalf("marked text result = %+v, want the first attempt by its invisible mark", marked) + } + + // The invisible characters stripped (a chat tool, retyping): the statement and + // its wording still point at the attempt that was served it, and not at the other. + stripped := trace(domain.VisibleAssessmentText(secondAttempt.prompt), "") + if stripped.Status != domain.AssessmentLeakTraceFound || stripped.AttemptID != domain.AssessmentAttemptID(secondAttempt.id) || + (stripped.Method != domain.AssessmentLeakTraceWording && stripped.Method != domain.AssessmentLeakTraceVariant) { + t.Fatalf("stripped text result = %+v, want the second attempt by its statement", stripped) + } + + // The text of a screenshot: the statement without the mark and the tile with the code and the time. + tile := fmt.Sprintf("%s\n%s %s", domain.VisibleAssessmentText(firstAttempt.prompt), firstAttempt.code, time.Now().UTC().Format("2006-01-02 15:04")+"Z") + screenshot := trace(tile, "") + if screenshot.Status != domain.AssessmentLeakTraceFound || screenshot.Method != domain.AssessmentLeakTraceVisibleCode || + screenshot.AttemptID != domain.AssessmentAttemptID(firstAttempt.id) { + t.Fatalf("screenshot text result = %+v, want the first attempt by its visible code", screenshot) + } + if !strings.Contains(strings.Join(screenshot.Notes, " "), "falls within the life of the attempt") { + t.Fatalf("screenshot notes = %v, want the tile time within the attempt", screenshot.Notes) + } + + // Insufficient data is reported as not found. + unrelated := trace("The committee will meet on Thursday to discuss the budget for the coming year and the new office.", "") + if unrelated.Status != domain.AssessmentLeakTraceNotFound || !unrelated.AttemptID.IsZero() { + t.Fatalf("unrelated text result = %+v, want not found", unrelated) + } + short := trace("How many requests?", "") + if short.Status != domain.AssessmentLeakTraceNotFound { + t.Fatalf("short text result = %+v, want not found", short) + } + + // A search changes no attempt, review, or result. + if after := leakTraceFacts(t, ctx, harness); after != before { + t.Fatalf("a search changed the attempts: %q before, %q after", before, after) + } + + // Every search was audited, without the text. + var rows int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_leak_traces`).Scan(&rows); err != nil || rows != 5 { + t.Fatalf("audit rows = %d, error %v, want one per search", rows, err) + } + var dump string + if err := harness.pool.QueryRow(ctx, `SELECT string_agg(t::text, ' ') FROM assessment_leak_traces AS t`).Scan(&dump); err != nil { + t.Fatalf("dump the audit: %v", err) + } + for _, leaked := range []string{"gateway", "limiter", "committee", "Thursday", firstAttempt.code} { + if strings.Contains(strings.ToLower(dump), strings.ToLower(leaked)) { + t.Fatalf("the audit holds %q, want a keyed digest of the text only", leaked) + } + } + if found := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE status = 'found' AND attempt_id IS NOT NULL AND actor = 'operator:integration'`); found != 3 { + t.Fatalf("found audit rows = %d, want 3", found) + } + if notFound := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE status = 'not_found' AND attempt_id IS NULL AND method IS NULL`); notFound != 2 { + t.Fatalf("not found audit rows = %d, want 2", notFound) + } + + // The audit is immutable and survives the attempt it names. + _, updateErr := harness.pool.Exec(ctx, `UPDATE assessment_leak_traces SET actor = 'operator:other'`) + assertSQLError(t, "update an audit record", updateErr, "23000", "assessment_leak_traces_immutable") + _, deleteErr := harness.pool.Exec(ctx, `DELETE FROM assessment_leak_traces`) + assertSQLError(t, "delete an audit record", deleteErr, "23000", "assessment_leak_traces_immutable") + _, truncateErr := harness.pool.Exec(ctx, `TRUNCATE assessment_leak_traces`) + assertSQLError(t, "truncate the audit", truncateErr, "23000", "assessment_leak_traces_immutable") + _, foundWithoutAttempt := harness.pool.Exec(ctx, `INSERT INTO assessment_leak_traces + (id, actor, searched_at, text_digest, key_version, text_runes, status, method, attempt_id, candidates, evidence_bits) + VALUES ($1, 'operator:integration', now(), $2, 1, 10, 'found', 'wording', NULL, 1, 1)`, uuid.New(), bytes.Repeat([]byte{1}, 32)) + assertSQLError(t, "found search without an attempt", foundWithoutAttempt, assessmentCheckSQLState, "assessment_leak_traces_found") + if _, err := harness.pool.Exec(ctx, `DELETE FROM assessment_attempts WHERE id = $1`, firstAttempt.id); err != nil { + t.Fatalf("delete the attempt: %v", err) + } + if rows := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE attempt_id = $1`, firstAttempt.id); rows != 2 { + t.Fatalf("audit rows of the deleted attempt = %d, want them kept", rows) + } + gone := trace(firstAttempt.prompt, "") + if gone.Status != domain.AssessmentLeakTraceNotFound { + t.Fatalf("search for a deleted attempt = %+v, want not found: the mark names no attempt any more", gone) + } + + // The command reads the secret of the server and the audit is written by it too. + var output bytes.Buffer + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return databaseURL, true + case "IDENTITY_KEY_SECRET": + return isolatedEnv.Config.IdentityKeySecret, true + default: + return "", false + } + } + err = leaktrace.Run(ctx, []string{"search", "--actor", "operator:command", "--stdin"}, lookup, + strings.NewReader("Question: "+secondAttempt.prompt), &output) + if err != nil || !strings.Contains(output.String(), "result: found") || !strings.Contains(output.String(), "method: invisible_mark") || + !strings.Contains(output.String(), "attempt: "+secondAttempt.id.String()) { + t.Fatalf("command output = %q, error %v, want the second attempt by its mark", output.String(), err) + } + if rows := countRows(t, ctx, harness, `SELECT count(*) FROM assessment_leak_traces WHERE actor = 'operator:command' AND status = 'found'`); rows != 1 { + t.Fatalf("command audit rows = %d, want 1", rows) + } + otherSecret := func(key string) (string, bool) { + if key == "IDENTITY_KEY_SECRET" { + return strings.Repeat("x", 48), true + } + return lookup(key) + } + output.Reset() + if err := leaktrace.Run(ctx, []string{"search", "--actor", "operator:command", "--stdin"}, otherSecret, + strings.NewReader("Question: "+secondAttempt.prompt), &output); err != nil || strings.Contains(output.String(), "method: invisible_mark") { + t.Fatalf("a command with another secret = %q, %v, want it not to read the mark of the server", output.String(), err) + } +} + +type leakTraceAttempt struct { + id uuid.UUID + code string + prompt string +} + +func leakTraceCreate(t *testing.T, harness *assessmentAttemptHTTPHarness, candidate reviewCandidate, key, remoteAddr string) leakTraceAttempt { + t.Helper() + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr) + if response.Code != http.StatusCreated { + t.Fatalf("create real attempt = %d %s", response.Code, response.Body.String()) + } + id, _ := assessmentSignalAttemptItem(t, response.Body.Bytes()) + code, prompt := decodeWatermarkedAttempt(t, response.Body.Bytes()) + if code == "" || !hasZeroWidth(prompt) { + t.Fatalf("the presented attempt has code %q and a prompt without a mark", code) + } + return leakTraceAttempt{id: id, code: code, prompt: prompt} +} + +// leakTraceFacts summarizes what a search must not change: the versions and +// states of the attempts and the number of reviews and results. +func leakTraceFacts(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness) string { + t.Helper() + var facts string + if err := harness.pool.QueryRow(ctx, `SELECT + coalesce((SELECT string_agg(id::text || ':' || version || ':' || state, ',' ORDER BY id) FROM assessment_attempts), '') || '|' || + (SELECT count(*) FROM assessment_attempt_reviews) || '|' || + (SELECT count(*) FROM assessment_attempt_results)`).Scan(&facts); err != nil { + t.Fatalf("read the attempt facts: %v", err) + } + return facts +} diff --git a/backend/integration_test/assessment_practice_http_test.go b/backend/integration_test/assessment_practice_http_test.go new file mode 100644 index 0000000..41869f6 --- /dev/null +++ b/backend/integration_test/assessment_practice_http_test.go @@ -0,0 +1,488 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + v1 "lincodex/backend/internal/adapter/primary/http/v1" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/practice" +) + +const ( + assessmentPracticeTimeout = 6 * time.Minute + // practiceHiddenMarker is part of every hidden test text, so a response + // that leaks hidden content is found by a substring search. + practiceHiddenMarker = "hidden-secret" + practiceSource = "print(sum(map(int, input().split())))\n" +) + +func TestAssessmentPracticeSubmissionStorage(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentPracticeTimeout) + defer cancel() + harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) { + return practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true) + }) + owner := newPracticeCandidate(ctx, t, harness, "practice-owner", 10) + other := newPracticeCandidate(ctx, t, harness, "practice-other", 20) + // firstRun is the debug run that the first case stores; it stays queued, + // as no worker runs here, until a later case gives it a result. + var firstRun uuid.UUID + + t.Run("debug run is stored with its job and shows no hidden content", func(t *testing.T) { + body := practiceRunBody(t, owner.practiceID, "python", practiceSource, []domain.PracticeTest{{Input: "4 5\n", ExpectedOutput: "9\n"}}) + created := practiceRunRequest(t, harness, owner, body, "run-first") + if created.Code != http.StatusAccepted { + t.Fatalf("create run = %d %s", created.Code, created.Body.String()) + } + if created.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("run Cache-Control = %q, want no-store", created.Header().Get("Cache-Control")) + } + run := decodePracticeRun(t, created) + if run.ItemID != owner.practiceID || run.State != "queued" || run.Result != nil || run.FailureReason != nil || run.FinishedAt != nil { + t.Fatalf("created run = %+v, want a queued run of the practice", run) + } + assertPracticeResponseIsPublic(t, created) + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + firstRun = run.ID + + replay := practiceRunRequest(t, harness, owner, body, "run-first") + if replay.Code != http.StatusAccepted || decodePracticeRun(t, replay).ID != run.ID { + t.Fatalf("same-key replay = %d %s, want the stored run %s", replay.Code, replay.Body.String(), run.ID) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + + changed := practiceRunBody(t, owner.practiceID, "python", practiceSource+"# changed\n", nil) + requireSessionProblem(t, practiceRunRequest(t, harness, owner, changed, "run-first"), http.StatusUnprocessableEntity, "idempotency_key_reused") + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + + read := practiceRunRead(t, harness, owner, owner.attemptID, run.ID) + if read.Code != http.StatusOK || decodePracticeRun(t, read).ID != run.ID { + t.Fatalf("read run = %d %s", read.Code, read.Body.String()) + } + requireSessionProblem(t, practiceRunRead(t, harness, other, owner.attemptID, run.ID), http.StatusNotFound, "not_found") + requireSessionProblem(t, practiceRunRead(t, harness, owner, owner.attemptID, uuid.New()), http.StatusNotFound, "not_found") + requireSessionProblem(t, practiceRunRead(t, harness, owner, other.attemptID, run.ID), http.StatusNotFound, "not_found") + }) + + t.Run("refusals store nothing", func(t *testing.T) { + foreign := practiceRunBody(t, owner.practiceID, "python", practiceSource, nil) + requireSessionProblem(t, practiceRunRequest(t, harness, other, foreign, "run-foreign"), http.StatusNotFound, "not_found") + closed := practiceRunBody(t, owner.additionalID, "python", practiceSource, nil) + requireSessionProblem(t, practiceRunRequest(t, harness, owner, closed, "run-closed"), http.StatusConflict, "state_conflict") + tooLong := practiceRunBody(t, owner.practiceID, "python", strings.Repeat("x", 1001), nil) + requireSessionProblem(t, practiceRunRequest(t, harness, owner, tooLong, "run-too-long"), http.StatusBadRequest, "validation_failed") + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "public", 1) + assertPracticeRows(t, ctx, harness.pool, owner.additionalID, "public", 0) + }) + + t.Run("a stored result is shown without hidden groups", func(t *testing.T) { + // A result that holds a hidden group, which a debug run never gets, + // proves that the presentation drops it. + storePracticeResult(t, ctx, harness.pool, firstRun, domain.PracticeRunResult{ + Outcome: domain.PracticeOutcomeWrongAnswer, DurationMs: 42, + Groups: []domain.PracticeGroupOutcome{ + {ID: practice.PublicGroupID, Outcome: domain.PracticeOutcomeWrongAnswer, PassedTests: 1, TotalTests: 2, Tests: []domain.PracticeTestOutcome{ + {ID: "1", Outcome: domain.PracticeOutcomeAccepted, TimeMs: 3, MemoryKB: 900}, + {ID: "2", Outcome: domain.PracticeOutcomeWrongAnswer, TimeMs: 4, MemoryKB: 901}, + }}, + {ID: "hidden-1", Hidden: true, Outcome: domain.PracticeOutcomeAccepted, PassedTests: 1, TotalTests: 1}, + }, + }) + read := practiceRunRead(t, harness, owner, owner.attemptID, firstRun) + finished := decodePracticeRun(t, read) + if read.Code != http.StatusOK || finished.State != "finished" || finished.Result == nil || len(finished.Result.Tests) != 2 { + t.Fatalf("finished run = %d %s", read.Code, read.Body.String()) + } + for _, test := range finished.Result.Tests { + if test.Source != "example" { + t.Fatalf("finished run lists a test from %q", test.Source) + } + } + assertPracticeResponseIsPublic(t, read) + }) + + t.Run("final source is stored once and never replaced", func(t *testing.T) { + service := harness.service + command := practice.FinalCommand{ + ActorID: owner.userID, AttemptID: domain.AssessmentAttemptID(owner.attemptID), PracticeID: owner.practiceID, + IdempotencyKey: "final-first", Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, + } + first, err := service.SubmitFinal(ctx, command) + if err != nil || first.Replayed || first.Unchanged || first.Practice.Status != domain.AssessmentPracticePending || + first.Practice.SubmittedAt == nil || first.Practice.ItemID != owner.practiceID { + t.Fatalf("first final submission = %+v, error %v", first, err) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 1) + + replay, err := service.SubmitFinal(ctx, command) + if err != nil || !replay.Replayed || replay.Practice.Status != domain.AssessmentPracticePending { + t.Fatalf("final replay = %+v, error %v", replay, err) + } + repeat := command + repeat.IdempotencyKey = "final-same-source" + same, err := service.SubmitFinal(ctx, repeat) + if err != nil || !same.Unchanged { + t.Fatalf("same final solution under a new key = %+v, error %v", same, err) + } + other := command + other.IdempotencyKey = "final-other-source" + other.Source = practiceSource + "# another solution\n" + if _, err := service.SubmitFinal(ctx, other); !errors.Is(err, practice.ErrStateConflict) { + t.Fatalf("another final solution error = %v, want state conflict", err) + } + reused := command + reused.Source = other.Source + if _, err := service.SubmitFinal(ctx, reused); !errors.Is(err, practice.ErrKeyReused) { + t.Fatalf("final key reused error = %v, want key reused", err) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 1) + assertFinalSourceIsImmutable(t, ctx, harness.pool, owner.practiceID) + + // A practice that failed in the sandbox accepts a solution again; the + // first one stays stored as it was. + if _, err := harness.pool.Exec(ctx, `UPDATE assessment_practices + SET status = 'failed', failure_reason = 'sandbox_error' WHERE id = $1`, owner.practiceID); err != nil { + t.Fatalf("mark practice failed: %v", err) + } + retry := other + retry.IdempotencyKey = "final-after-failure" + again, err := service.SubmitFinal(ctx, retry) + if err != nil || again.Practice.Status != domain.AssessmentPracticePending || again.Practice.FailureReason != "" { + t.Fatalf("final submission after a sandbox failure = %+v, error %v", again, err) + } + assertPracticeRows(t, ctx, harness.pool, owner.practiceID, "final", 2) + }) + + t.Run("disabled runner stores nothing", func(t *testing.T) { + disabled, err := practice.NewService(postgresadapter.NewTransactor(harness.pool), harness.keyring, time.Now, false) + if err != nil { + t.Fatalf("NewService() error = %v", err) + } + _, err = disabled.SubmitRun(ctx, practice.RunCommand{ + ActorID: other.userID, AttemptID: domain.AssessmentAttemptID(other.attemptID), PracticeID: other.practiceID, + IdempotencyKey: "disabled-run", Source: practiceSource, Language: languagePointer(domain.TaskLanguagePython), + }) + if !errors.Is(err, practice.ErrUnavailable) { + t.Fatalf("run with a disabled runner error = %v, want unavailable", err) + } + assertPracticeRows(t, ctx, harness.pool, other.practiceID, "public", 0) + }) + + assertEverySubmissionHasOneJob(t, ctx, harness.pool) +} + +// practiceHarness is the attempt router with the practice operations. +type practiceHarness struct { + *assessmentAttemptHTTPHarness + service *practice.Service + passwordHash domain.PasswordHash + // databaseURL names the isolated database of the harness. + databaseURL string +} + +// newPracticeHarness builds the router on an isolated, migrated database with +// the reviewed fixture bank, and the practice service that build returns. +func newPracticeHarness( + ctx context.Context, + t *testing.T, + env *testEnvironment, + build func(assessmentHarnessParts) (*practice.Service, error), +) *practiceHarness { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + var service *practice.Service + attemptHarness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, &isolatedEnv, assessment.AssessmentCategoryDecisionSettings{}, func(parts assessmentHarnessParts) []v1.HandlerOption { + built, err := build(parts) + if err != nil { + t.Fatalf("build practice service: %v", err) + } + service = built + return []v1.HandlerOption{v1.WithPractice(v1.NewPracticeHandler(built))} + }) + seedAssessmentAttemptHTTPBank(ctx, t, attemptHarness.pool) + passwordHash, err := attemptHarness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + return &practiceHarness{ + assessmentAttemptHTTPHarness: attemptHarness, service: service, passwordHash: passwordHash, databaseURL: databaseURL, + } +} + +// practiceCandidate is a candidate whose real attempt is at its main practice. +type practiceCandidate struct { + userID uuid.UUID + cookie string + csrf string + remoteAddr string + attemptID uuid.UUID + // practiceID is the main practice, the current item of the attempt. + practiceID uuid.UUID + // additionalID is the additional practice, which is not open while the + // attempt is at the main one. + additionalID uuid.UUID +} + +// newPracticeCandidate registers a candidate, starts a real attempt, moves it +// to practice_pending, and assigns its two practices. hostIndex keeps the +// client addresses of candidates apart. +func newPracticeCandidate(ctx context.Context, t *testing.T, harness *practiceHarness, name string, hostIndex int) practiceCandidate { + t.Helper() + address := func(port int) string { return fmt.Sprintf("192.0.2.%d:%d", hostIndex, port) } + user := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, name+"@example.test", harness.passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", user.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, user.Email.Address(), address(1)) + if response := assessmentAttemptQuestionnaireRequest(t, harness.assessmentAttemptHTTPHarness, cookie.Value, csrf, address(2)); response.Code != http.StatusOK { + t.Fatalf("save questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness.assessmentAttemptHTTPHarness, cookie, csrf, address(3)) + created := assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, name+"-attempt", address(4)) + if created.Code != http.StatusCreated { + t.Fatalf("create attempt = %d %s", created.Code, created.Body.String()) + } + attemptID := assessmentAttemptIDOf(t, created) + // No flow serves practice items yet, so the fixture moves the attempt to + // its main practice the way the item part will end. + if _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempts + SET state = 'practice_pending', version = version + 1, updated_at = greatest(updated_at, clock_timestamp()) + WHERE id = $1`, attemptID); err != nil { + t.Fatalf("move attempt to its practice: %v", err) + } + candidate := practiceCandidate{ + userID: user.ID, cookie: cookie.Value, csrf: csrf, remoteAddr: address(5), attemptID: attemptID, + practiceID: createPractice(ctx, t, harness.pool, user.ID, attemptID, domain.AssessmentPracticeMain), + } + candidate.additionalID = createPractice(ctx, t, harness.pool, user.ID, attemptID, domain.AssessmentPracticeAdditional) + return candidate +} + +func createPractice( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + userID, attemptID uuid.UUID, + kind domain.AssessmentPracticeKind, +) uuid.UUID { + t.Helper() + id, err := uuid.NewV7() + if err != nil { + t.Fatalf("generate practice ID: %v", err) + } + // A submission is stamped with the database time, so the practice is + // created with it too: a database clock slightly behind the test host + // would otherwise put the first submission before its practice. + var createdAt time.Time + if err := pool.QueryRow(ctx, `SELECT clock_timestamp()`).Scan(&createdAt); err != nil { + t.Fatalf("read database time: %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.AssessmentPractices().Create(ctx, domain.AssessmentPractice{ + ID: id, AttemptID: domain.AssessmentAttemptID(attemptID), UserID: userID, Kind: kind, Task: practiceTestTask(), + Status: domain.AssessmentPracticeNotStarted, CreatedAt: createdAt.UTC().Truncate(time.Microsecond), + }) + }) + if err != nil { + t.Fatalf("create %s practice: %v", kind, err) + } + return id +} + +// practiceTestTask is a synthetic task whose hidden texts carry +// practiceHiddenMarker. +func practiceTestTask() domain.PracticeTask { + hidden := make([]domain.PracticeTestGroup, 0, domain.PracticeHiddenGroups) + for group := 1; group <= domain.PracticeHiddenGroups; group++ { + hidden = append(hidden, domain.PracticeTestGroup{Tests: []domain.PracticeTest{{ + Input: fmt.Sprintf("%s-input-%d\n", practiceHiddenMarker, group), + ExpectedOutput: fmt.Sprintf("%s-output-%d\n", practiceHiddenMarker, group), + }}}) + } + return domain.PracticeTask{ + Languages: []domain.TaskLanguageCode{domain.TaskLanguagePython, domain.TaskLanguageGo}, + MaxSourceLength: 1000, TimeLimitMs: 1000, MemoryLimitMB: 64, OutputLimitKB: 64, + Checker: domain.PracticeChecker{Kind: domain.PracticeCheckerTokens}, + PublicTests: []domain.PracticeTest{{Input: "1 2\n", ExpectedOutput: "3\n"}, {Input: "2 2\n", ExpectedOutput: "4\n"}}, + HiddenGroups: hidden, + } +} + +func practiceRunBody(t *testing.T, itemID uuid.UUID, language, source string, tests []domain.PracticeTest) string { + t.Helper() + body := map[string]any{"item_id": itemID, "language": language, "source_code": source} + if tests != nil { + body["tests"] = tests + } + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal practice run body: %v", err) + } + return string(encoded) +} + +func practiceRunRequest(t *testing.T, harness *practiceHarness, candidate practiceCandidate, body, key string) *httptest.ResponseRecorder { + t.Helper() + return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+candidate.attemptID.String()+"/practice-runs", body, + sessionHTTPTestOrigin, candidate.cookie, candidate.csrf, key, candidate.remoteAddr) +} + +func practiceRunRead(t *testing.T, harness *practiceHarness, candidate practiceCandidate, attemptID, runID uuid.UUID) *httptest.ResponseRecorder { + t.Helper() + return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, http.MethodGet, + "/api/v1/me/assessment-attempts/"+attemptID.String()+"/practice-runs/"+runID.String(), "", + "", candidate.cookie, "", "", candidate.remoteAddr) +} + +type practiceRunResponse struct { + ID uuid.UUID `json:"id"` + ItemID uuid.UUID `json:"item_id"` + State string `json:"state"` + FinishedAt *time.Time `json:"finished_at"` + FailureReason *string `json:"failure_reason"` + Result *struct { + Outcome string `json:"outcome"` + Tests []struct { + Source string `json:"source"` + Index int `json:"index"` + Outcome string `json:"outcome"` + } `json:"tests"` + } `json:"result"` +} + +func decodePracticeRun(t *testing.T, response *httptest.ResponseRecorder) practiceRunResponse { + t.Helper() + var run practiceRunResponse + if err := json.Unmarshal(response.Body.Bytes(), &run); err != nil || run.ID == uuid.Nil { + t.Fatalf("practice run response %d %s: %v", response.Code, response.Body.String(), err) + } + return run +} + +// assertPracticeResponseIsPublic checks that a run response holds only the +// fields of the contract and nothing of the hidden groups or the source. +func assertPracticeResponseIsPublic(t *testing.T, response *httptest.ResponseRecorder) { + t.Helper() + text := response.Body.String() + for _, secret := range []string{practiceHiddenMarker, "hidden-1", "hidden", "print(sum", "expected_output", "input"} { + if strings.Contains(text, secret) { + t.Fatalf("practice run response exposes %q: %s", secret, text) + } + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(response.Body.Bytes(), &fields); err != nil { + t.Fatalf("decode practice run fields: %v", err) + } + allowed := map[string]bool{"id": true, "item_id": true, "state": true, "created_at": true, "finished_at": true, "failure_reason": true, "result": true} + for name := range fields { + if !allowed[name] { + t.Fatalf("practice run response has field %q", name) + } + } +} + +func assertPracticeRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string, want int) { + t.Helper() + var submissions, jobs int + if err := pool.QueryRow(ctx, `SELECT count(*), count(job.submission_id) + FROM assessment_practice_submissions AS submission + LEFT JOIN assessment_practice_jobs AS job ON job.submission_id = submission.id + WHERE submission.practice_id = $1 AND submission.mode = $2`, practiceID, mode).Scan(&submissions, &jobs); err != nil { + t.Fatalf("count practice rows: %v", err) + } + if submissions != want || jobs != want { + t.Fatalf("%s submissions = %d with %d jobs, want %d of each", mode, submissions, jobs, want) + } +} + +func assertEverySubmissionHasOneJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool) { + t.Helper() + var orphans int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions AS submission + WHERE NOT EXISTS (SELECT 1 FROM assessment_practice_jobs AS job WHERE job.submission_id = submission.id)`).Scan(&orphans); err != nil { + t.Fatalf("count submissions without a job: %v", err) + } + if orphans != 0 { + t.Fatalf("%d submissions have no execution job", orphans) + } +} + +// assertFinalSourceIsImmutable proves that the database refuses to replace or +// delete a stored final solution, and accepts its result only once. +func assertFinalSourceIsImmutable(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) { + t.Helper() + var submissionID uuid.UUID + if err := pool.QueryRow(ctx, `SELECT id FROM assessment_practice_submissions WHERE practice_id = $1 AND mode = 'final'`, + practiceID).Scan(&submissionID); err != nil { + t.Fatalf("read final submission: %v", err) + } + statements := map[string]string{ + `UPDATE assessment_practice_submissions SET source = 'print(42)' WHERE id = $1`: "assessment_practice_submission_immutable", + `UPDATE assessment_practice_submissions SET language = 'go' WHERE id = $1`: "assessment_practice_submission_immutable", + `DELETE FROM assessment_practice_submissions WHERE id = $1`: "assessment_practice_submission_delete_forbidden", + } + for statement, constraint := range statements { + _, err := pool.Exec(ctx, statement, submissionID) + requireConstraintViolation(t, err, constraint) + } + setResult := `UPDATE assessment_practice_submissions + SET result = '{"outcome":"accepted","groups":[],"duration_ms":1}', result_at = created_at WHERE id = $1` + if _, err := pool.Exec(ctx, setResult, submissionID); err != nil { + t.Fatalf("store the first result: %v", err) + } + _, err := pool.Exec(ctx, setResult, submissionID) + requireConstraintViolation(t, err, "assessment_practice_submission_immutable") +} + +func requireConstraintViolation(t *testing.T, err error, constraint string) { + t.Helper() + var databaseError *pgconn.PgError + if !errors.As(err, &databaseError) || databaseError.ConstraintName != constraint { + t.Fatalf("statement error = %v, want a violation of %s", err, constraint) + } +} + +func storePracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, submissionID uuid.UUID, result domain.PracticeRunResult) { + t.Helper() + encoded, err := json.Marshal(result) + if err != nil { + t.Fatalf("marshal practice result: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE assessment_practice_submissions SET result = $2, result_at = created_at WHERE id = $1`, + submissionID, encoded); err != nil { + t.Fatalf("store practice result: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE assessment_practice_jobs + SET state = 'finished', finished_at = greatest(created_at, clock_timestamp()), updated_at = greatest(updated_at, clock_timestamp()) + WHERE submission_id = $1`, submissionID); err != nil { + t.Fatalf("finish practice job: %v", err) + } +} + +func languagePointer(language domain.TaskLanguageCode) *domain.TaskLanguageCode { + return &language +} diff --git a/backend/integration_test/assessment_practice_queue_test.go b/backend/integration_test/assessment_practice_queue_test.go new file mode 100644 index 0000000..8c22482 --- /dev/null +++ b/backend/integration_test/assessment_practice_queue_test.go @@ -0,0 +1,686 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/practice" + "lincodex/backend/internal/worker/practicequeue" + "lincodex/backend/internal/worker/retry" +) + +const ( + practiceQueueTimeout = 8 * time.Minute + // practiceQueueLease is the lease of the queue tests, on their clock. + practiceQueueLease = 5 * time.Second + // practiceRunsPerMinute is the debug run limit of the tests. + practiceRunsPerMinute = 2 + // fakeRunnerBusyWait is the Retry-After of the fake runner when busy. + fakeRunnerBusyWait = 30 * time.Second +) + +func TestAssessmentPracticeQueue(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), practiceQueueTimeout) + defer cancel() + harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) { + service, err := practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true) + if err != nil { + return nil, err + } + return service.WithRunRateLimit(env.Redis, outbound.RateLimitRule{Window: time.Minute, Limit: practiceRunsPerMinute}), nil + }) + clock := &practiceQueueClock{} + runner := newFakePracticeRunner() + queue := newPracticeQueueRig(t, harness.pool, runner, clock) + + candidates := make([]practiceCandidate, practice.MaxRunningJobs+practice.MaxQueuedJobs+1) + for index := range candidates { + candidates[index] = newPracticeCandidate(ctx, t, harness, fmt.Sprintf("practice-queue-%02d", index), 30+index) + } + + t.Run("twelve runs at once fill one running and ten queued slots and the last is busy", func(t *testing.T) { + responses := make([]*httptest.ResponseRecorder, len(candidates)) + start := make(chan struct{}) + var wait sync.WaitGroup + for index, candidate := range candidates { + wait.Add(1) + go func() { + defer wait.Done() + <-start + body := practiceRunBody(t, candidate.practiceID, "python", practiceSource, nil) + responses[index] = practiceRunRequest(t, harness, candidate, body, "queue-run") + }() + } + close(start) + wait.Wait() + busy := -1 + for index, response := range responses { + switch response.Code { + case http.StatusAccepted: + case http.StatusServiceUnavailable: + if busy >= 0 { + t.Fatalf("a second run was refused as busy: %s", response.Body.String()) + } + busy = index + requireSessionProblem(t, response, http.StatusServiceUnavailable, "service_unavailable") + if response.Header().Get("Retry-After") != "10" { + t.Fatalf("busy Retry-After = %q, want 10", response.Header().Get("Retry-After")) + } + default: + t.Fatalf("run %d = %d %s", index, response.Code, response.Body.String()) + } + } + if busy < 0 { + t.Fatal("no run was refused as busy") + } + assertPracticeRows(t, ctx, harness.pool, candidates[busy].practiceID, "public", 0) + assertPracticeJobStates(t, ctx, harness.pool, map[string]int{"queued": 11}) + + // One worker holds the only running slot while the runner works; a + // second worker finds nothing it may run. + runner.hold(true) + workerCtx, stopWorker := context.WithCancel(ctx) + workerDone := make(chan struct{}) + go func() { + defer close(workerDone) + queue.worker.Run(workerCtx) + }() + waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"running": 1, "queued": 10}) + other := queue.newWorker(t) + if _, claimed, err := other.RunOnce(ctx); err != nil || claimed { + t.Fatalf("second worker claimed = %v, error %v; want nothing while one job runs", claimed, err) + } + runner.hold(false) + waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"finished": 11}) + stopWorker() + <-workerDone + runner.requireOneRunPerSubmission(t, 11) + assertPracticeResultsStored(t, ctx, harness.pool, 11) + }) + + t.Run("a full queue answers a final solution busy and consumes nothing", func(t *testing.T) { + latecomer := candidates[len(candidates)-1] + for _, candidate := range candidates[:len(candidates)-1] { + body := practiceRunBody(t, candidate.practiceID, "python", practiceSource+"# second run\n", nil) + if response := practiceRunRequest(t, harness, candidate, body, "queue-refill"); response.Code != http.StatusAccepted { + t.Fatalf("refill run = %d %s", response.Code, response.Body.String()) + } + } + versionBefore := practiceAttemptVersion(t, ctx, harness.pool, latecomer.attemptID) + command := practice.FinalCommand{ + ActorID: latecomer.userID, AttemptID: domain.AssessmentAttemptID(latecomer.attemptID), PracticeID: latecomer.practiceID, + IdempotencyKey: "final-while-full", Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, + } + busy, err := harness.service.SubmitFinal(ctx, command) + if err != nil || busy.RetryAfter <= 0 || busy.Practice.Status != domain.AssessmentPracticeFailed || + busy.Practice.FailureReason != domain.AssessmentPracticeSandboxBusy { + t.Fatalf("final solution with a full queue = %+v, error %v; want failed with sandbox_busy", busy, err) + } + assertPracticeRows(t, ctx, harness.pool, latecomer.practiceID, "final", 0) + if version := practiceAttemptVersion(t, ctx, harness.pool, latecomer.attemptID); version != versionBefore { + t.Fatalf("attempt version = %d after a busy refusal, want %d", version, versionBefore) + } + + queue.drain(t, ctx) + command.IdempotencyKey = "final-after-full" + accepted, err := harness.service.SubmitFinal(ctx, command) + if err != nil || accepted.Practice.Status != domain.AssessmentPracticePending { + t.Fatalf("final solution after the queue drained = %+v, error %v", accepted, err) + } + queue.drain(t, ctx) + assertPracticeStatus(t, ctx, harness.pool, latecomer.practiceID, "finished", "") + }) + + t.Run("a busy runner and an infrastructure failure never grade or consume", func(t *testing.T) { + candidate := candidates[0] + submitPracticeFinal(t, ctx, harness, candidate, "final-runner-busy") + runner.answerBusy(1) + if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeBusy { + t.Fatalf("try on a busy runner = %q claimed %v, error %v; want busy", outcome, claimed, err) + } + job := readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "queued" || job.attempts != 0 || job.generation != 0 { + t.Fatalf("job after a busy runner = %+v, want queued without a counted attempt", job) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "pending", "") + // The job waits for the time the runner asked for. + if _, claimed, err := queue.worker.RunOnce(ctx); err != nil || claimed { + t.Fatalf("claim before the runner's wait = %v, error %v", claimed, err) + } + clock.advance(fakeRunnerBusyWait + time.Second) + + runner.failInfrastructure(1) + if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeRetry { + t.Fatalf("try after an infrastructure failure = %q, error %v; want retry", outcome, err) + } + job = readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "queued" || job.attempts != 1 || job.generation != 1 || job.errorClass != "runner_infrastructure_failure" { + t.Fatalf("job after an infrastructure failure = %+v, want queued with a new generation", job) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "pending", "") + assertNoPracticeResult(t, ctx, harness.pool, candidate.practiceID) + + clock.advance(time.Minute) + if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished { + t.Fatalf("try after the backoff = %q, error %v; want finished", outcome, err) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "finished", "") + }) + + t.Run("a worker restarted mid-job recovers it with a single run and result", func(t *testing.T) { + candidate := candidates[1] + submitPracticeFinal(t, ctx, harness, candidate, "final-restart") + runner.hold(true) + defer runner.hold(false) + + crashedPool := newPoolFor(ctx, t, harness.databaseURL) + crashed := queue.workerOn(t, crashedPool) + crashCtx, crash := context.WithCancel(ctx) + crashedDone := make(chan struct{}) + go func() { + defer close(crashedDone) + _, _, _ = crashed.worker.RunOnce(crashCtx) + }() + waitForPracticeJobStates(t, ctx, harness.pool, map[string]int{"running": 1}) + submissionID := latestPracticeSubmission(t, ctx, harness.pool, candidate.practiceID, "final") + runner.waitForRuns(t, ctx, submissionID, 1) + // The process dies: its connections are gone, so it cannot give the + // job back, and the lease keeps the job running. + crashedPool.Close() + crash() + <-crashedDone + stale := crashed.lastClaim() + job := readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "running" || job.leaseOwner != stale.LeaseOwner { + t.Fatalf("job after the crash = %+v, want running under the crashed lease", job) + } + + restarted := queue.newWorker(t) + if _, claimed, err := restarted.RunOnce(ctx); err != nil || claimed { + t.Fatalf("claim during the crashed lease = %v, error %v; want none", claimed, err) + } + clock.advance(practiceQueueLease + time.Second) + runner.hold(false) + if outcome, claimed, err := restarted.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeFinished { + t.Fatalf("restarted worker = %q claimed %v, error %v; want the job finished", outcome, claimed, err) + } + job = readPracticeJob(t, ctx, harness.pool, candidate.practiceID) + if job.state != "finished" || job.attempts != 1 || job.generation != 0 { + t.Fatalf("recovered job = %+v, want finished on the same run key with one counted takeover", job) + } + if runs := runner.runsOf(submissionID); runs != 1 { + t.Fatalf("runner started %d runs for the recovered job, want 1", runs) + } + result := readPracticeResult(t, ctx, harness.pool, candidate.practiceID, "final") + + // The crashed worker coming back late cannot add a second result. + lateStore := postgresadapter.NewPracticeJobStore(newPoolFor(ctx, t, harness.databaseURL)) + held, err := lateStore.Complete(ctx, stale, uuid.New(), domain.PracticeRunResult{Outcome: domain.PracticeOutcomeWrongAnswer, Groups: []domain.PracticeGroupOutcome{}}) + if err != nil || held { + t.Fatalf("late completion held = %v, error %v; want refused", held, err) + } + if again := readPracticeResult(t, ctx, harness.pool, candidate.practiceID, "final"); again != result { + t.Fatalf("result changed after a late completion: %s, was %s", again, result) + } + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "finished", "") + }) + + t.Run("debug runs have a technical rate limit and consume nothing when refused", func(t *testing.T) { + candidate := newPracticeCandidate(ctx, t, harness, "practice-limits", 60) + run := func(key string) *httptest.ResponseRecorder { + body := practiceRunBody(t, candidate.practiceID, "go", "package main\nfunc main() {}\n// "+key+"\n", nil) + return practiceRunRequest(t, harness, candidate, body, key) + } + if response := run("limit-first"); response.Code != http.StatusAccepted { + t.Fatalf("first run = %d %s", response.Code, response.Body.String()) + } + unfinished := run("limit-while-unfinished") + requireSessionProblem(t, unfinished, http.StatusTooManyRequests, "rate_limited") + if unfinished.Header().Get("Retry-After") == "" { + t.Fatal("refused run has no Retry-After") + } + queue.drain(t, ctx) + if response := run("limit-second"); response.Code != http.StatusAccepted { + t.Fatalf("second run = %d %s", response.Code, response.Body.String()) + } + queue.drain(t, ctx) + limited := run("limit-third") + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("rate-limited run has no Retry-After") + } + assertPracticeRows(t, ctx, harness.pool, candidate.practiceID, "public", 2) + assertPracticeStatus(t, ctx, harness.pool, candidate.practiceID, "not_started", "") + }) + + assertEverySubmissionHasOneJob(t, ctx, harness.pool) +} + +// practiceQueueRig builds workers on the test clock and the fake runner. +type practiceQueueRig struct { + pool *pgxpool.Pool + runner outbound.CodeRunner + clock *practiceQueueClock + logger *slog.Logger + worker *practicequeue.Worker +} + +func newPracticeQueueRig(t *testing.T, pool *pgxpool.Pool, runner outbound.CodeRunner, clock *practiceQueueClock) *practiceQueueRig { + t.Helper() + rig := &practiceQueueRig{pool: pool, runner: runner, clock: clock, logger: slog.New(slog.DiscardHandler)} + rig.worker = rig.newWorker(t) + return rig +} + +func (rig *practiceQueueRig) newWorker(t *testing.T) *practicequeue.Worker { + t.Helper() + return rig.workerOn(t, rig.pool).worker +} + +// recordedWorker is a worker whose store remembers its last claim, so a test +// can act as that worker after it stopped. +type recordedWorker struct { + worker *practicequeue.Worker + store *recordingPracticeStore +} + +func (worker recordedWorker) lastClaim() outbound.ClaimedPracticeJob { + worker.store.mu.Lock() + defer worker.store.mu.Unlock() + return worker.store.claimed +} + +func (rig *practiceQueueRig) workerOn(t *testing.T, pool *pgxpool.Pool) recordedWorker { + t.Helper() + store := &recordingPracticeStore{PracticeJobStore: postgresadapter.NewPracticeJobStore(pool)} + executor, err := practice.NewExecutor(rig.runner, store, rig.clock.now, practice.ExecutionSettings{ + PollInterval: 20 * time.Millisecond, Lease: practiceQueueLease, RunTimeout: time.Hour, MaxAttempts: 3, + BackoffInitial: 10 * time.Second, BackoffMax: 40 * time.Second, StoreTimeout: 5 * time.Second, + }, rig.logger) + if err != nil { + t.Fatalf("NewExecutor() error = %v", err) + } + worker, err := practicequeue.New(store, executor, rig.logger, practicequeue.Settings{ + PollInterval: 20 * time.Millisecond, Lease: practiceQueueLease, StoreTimeout: 5 * time.Second, + Backoff: retry.Backoff{Initial: 20 * time.Millisecond, Max: 100 * time.Millisecond}, + }, rig.clock.now) + if err != nil { + t.Fatalf("practicequeue.New() error = %v", err) + } + return recordedWorker{worker: worker, store: store} +} + +// drain runs jobs until none is left unfinished, moving the clock past any +// wait. +func (rig *practiceQueueRig) drain(t *testing.T, ctx context.Context) { + t.Helper() + for range 100 { + if _, claimed, err := rig.worker.RunOnce(ctx); err != nil { + t.Fatalf("drain the practice queue: %v", err) + } else if claimed { + continue + } + var active int + if err := rig.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_jobs WHERE state IN ('queued', 'running')`).Scan(&active); err != nil { + t.Fatalf("count unfinished practice jobs: %v", err) + } + if active == 0 { + return + } + rig.clock.advance(time.Minute) + } + t.Fatal("the practice queue did not drain") +} + +type recordingPracticeStore struct { + outbound.PracticeJobStore + mu sync.Mutex + claimed outbound.ClaimedPracticeJob +} + +func (store *recordingPracticeStore) Claim(ctx context.Context, claim outbound.PracticeJobClaim) (outbound.ClaimedPracticeJob, bool, error) { + job, claimed, err := store.PracticeJobStore.Claim(ctx, claim) + if claimed { + store.mu.Lock() + store.claimed = job + store.mu.Unlock() + } + return job, claimed, err +} + +// practiceQueueClock is the application clock of the queue tests: the real +// time moved forward by the test, so jobs stored with the database time are +// due at once. +type practiceQueueClock struct { + mu sync.Mutex + offset time.Duration +} + +func (clock *practiceQueueClock) now() time.Time { + clock.mu.Lock() + defer clock.mu.Unlock() + return time.Now().UTC().Add(clock.offset) +} + +func (clock *practiceQueueClock) advance(by time.Duration) { + clock.mu.Lock() + defer clock.mu.Unlock() + clock.offset += by +} + +// fakePracticeRunner stands in for the code runner. It is idempotent by run +// key like the real one, so a second submit of a key returns the stored run, +// and it counts the runs it started per practice item. +type fakePracticeRunner struct { + mu sync.Mutex + runs map[outbound.CodeRunKey]*fakePracticeRun + // started counts the runs started per submission. + started map[uuid.UUID]int + holding bool + busy int + failures int +} + +type fakePracticeRun struct { + request outbound.CodeRunRequest + finished bool +} + +func newFakePracticeRunner() *fakePracticeRunner { + return &fakePracticeRunner{runs: map[outbound.CodeRunKey]*fakePracticeRun{}, started: map[uuid.UUID]int{}} +} + +func (runner *fakePracticeRunner) Submit(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { + runner.mu.Lock() + defer runner.mu.Unlock() + if runner.busy > 0 { + runner.busy-- + return outbound.CodeRunStatus{State: outbound.CodeRunBusy, RetryAfter: fakeRunnerBusyWait}, nil + } + if runner.failures > 0 { + runner.failures-- + return outbound.CodeRunStatus{}, fmt.Errorf("fake runner: %w", outbound.ErrCodeRunnerInfrastructureFailure) + } + run, exists := runner.runs[request.Key] + if !exists { + run = &fakePracticeRun{request: request} + runner.runs[request.Key] = run + runner.started[request.Key.SubmissionID]++ + } + return runner.statusLocked(run), nil +} + +func (runner *fakePracticeRunner) Poll(_ context.Context, request outbound.CodeRunRequest) (outbound.CodeRunStatus, error) { + runner.mu.Lock() + defer runner.mu.Unlock() + run, exists := runner.runs[request.Key] + if !exists { + return outbound.CodeRunStatus{}, outbound.ErrCodeRunNotFound + } + return runner.statusLocked(run), nil +} + +func (runner *fakePracticeRunner) statusLocked(run *fakePracticeRun) outbound.CodeRunStatus { + if runner.holding && !run.finished { + return outbound.CodeRunStatus{State: outbound.CodeRunRunning, RunID: fakeRunnerRunID(run.request.Key)} + } + run.finished = true + result := outbound.CodeRunResult{Outcome: outbound.CodeOutcomeAccepted, Duration: 10 * time.Millisecond} + for _, group := range run.request.Groups { + groupResult := outbound.CodeGroupResult{ + ID: group.ID, Visibility: group.Visibility, Outcome: outbound.CodeOutcomeAccepted, + PassedTests: len(group.Tests), TotalTests: len(group.Tests), + } + for _, test := range group.Tests { + groupResult.Tests = append(groupResult.Tests, outbound.CodeTestResult{ID: test.ID, Outcome: outbound.CodeOutcomeAccepted, TimeMs: 1, MemoryKB: 512}) + } + result.Groups = append(result.Groups, groupResult) + } + return outbound.CodeRunStatus{State: outbound.CodeRunFinished, RunID: fakeRunnerRunID(run.request.Key), Result: &result} +} + +// fakeRunnerRunID is a stable run ID per run key, as the real runner client +// derives one. +func fakeRunnerRunID(key outbound.CodeRunKey) string { + return uuid.NewSHA1(key.SubmissionID, []byte{byte(key.Generation)}).String() +} + +// hold keeps new and unfinished runs running until it is turned off. +func (runner *fakePracticeRunner) hold(holding bool) { + runner.mu.Lock() + defer runner.mu.Unlock() + runner.holding = holding +} + +func (runner *fakePracticeRunner) answerBusy(times int) { + runner.mu.Lock() + defer runner.mu.Unlock() + runner.busy = times +} + +func (runner *fakePracticeRunner) failInfrastructure(times int) { + runner.mu.Lock() + defer runner.mu.Unlock() + runner.failures = times +} + +func (runner *fakePracticeRunner) runsOf(submissionID uuid.UUID) int { + runner.mu.Lock() + defer runner.mu.Unlock() + return runner.started[submissionID] +} + +func (runner *fakePracticeRunner) waitForRuns(t *testing.T, ctx context.Context, submissionID uuid.UUID, want int) { + t.Helper() + for ctx.Err() == nil { + if runner.runsOf(submissionID) >= want { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("runner did not start %d runs", want) +} + +// requireOneRunPerSubmission checks that every submission ran exactly once. +func (runner *fakePracticeRunner) requireOneRunPerSubmission(t *testing.T, want int) { + t.Helper() + runner.mu.Lock() + defer runner.mu.Unlock() + submissions := map[uuid.UUID]int{} + for key := range runner.runs { + submissions[key.SubmissionID]++ + } + if len(submissions) != want { + t.Fatalf("runner ran %d submissions, want %d", len(submissions), want) + } + for submission, runs := range submissions { + if runs != 1 { + t.Fatalf("submission %s ran %d times", submission, runs) + } + } +} + +func submitPracticeFinal(t *testing.T, ctx context.Context, harness *practiceHarness, candidate practiceCandidate, key string) { + t.Helper() + result, err := harness.service.SubmitFinal(ctx, practice.FinalCommand{ + ActorID: candidate.userID, AttemptID: domain.AssessmentAttemptID(candidate.attemptID), PracticeID: candidate.practiceID, + IdempotencyKey: key, Language: languagePointer(domain.TaskLanguagePython), Source: practiceSource, + }) + if err != nil || result.Practice.Status != domain.AssessmentPracticePending { + t.Fatalf("final submission = %+v, error %v", result, err) + } +} + +func latestPracticeSubmission(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string) uuid.UUID { + t.Helper() + var id uuid.UUID + if err := pool.QueryRow(ctx, `SELECT id FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = $2 ORDER BY created_at DESC LIMIT 1`, practiceID, mode).Scan(&id); err != nil { + t.Fatalf("read latest practice submission: %v", err) + } + return id +} + +type practiceJobRow struct { + state string + attempts int + generation int + errorClass string + leaseOwner uuid.UUID +} + +// readPracticeJob reads the job of the latest final submission of a practice. +func readPracticeJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) practiceJobRow { + t.Helper() + var job practiceJobRow + var owner *uuid.UUID + var class *string + if err := pool.QueryRow(ctx, `SELECT job.state, job.attempts, job.generation, job.last_error_class, job.lease_owner + FROM assessment_practice_jobs AS job + JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id + WHERE submission.practice_id = $1 AND submission.mode = 'final' + ORDER BY submission.created_at DESC LIMIT 1`, practiceID).Scan(&job.state, &job.attempts, &job.generation, &class, &owner); err != nil { + t.Fatalf("read practice job: %v", err) + } + if owner != nil { + job.leaseOwner = *owner + } + if class != nil { + job.errorClass = *class + } + return job +} + +func readPracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, mode string) string { + t.Helper() + var result []byte + if err := pool.QueryRow(ctx, `SELECT result FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = $2 ORDER BY created_at DESC LIMIT 1`, practiceID, mode).Scan(&result); err != nil || len(result) == 0 { + t.Fatalf("read practice result: %v (%d bytes)", err, len(result)) + } + var decoded domain.PracticeRunResult + if err := json.Unmarshal(result, &decoded); err != nil || decoded.Outcome != domain.PracticeOutcomeAccepted { + t.Fatalf("stored result %s, decode error %v", result, err) + } + return string(result) +} + +// assertNoPracticeResult checks that no final submission of the practice has +// a result. +func assertNoPracticeResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID) { + t.Helper() + var stored int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = 'final' AND result IS NOT NULL`, practiceID).Scan(&stored); err != nil { + t.Fatalf("count practice results: %v", err) + } + if stored != 0 { + t.Fatalf("%d practice results stored, want none", stored) + } +} + +func assertPracticeResultsStored(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want int) { + t.Helper() + var stored int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions WHERE result IS NOT NULL`).Scan(&stored); err != nil { + t.Fatalf("count practice results: %v", err) + } + if stored != want { + t.Fatalf("%d practice results stored, want %d", stored, want) + } +} + +func assertPracticeStatus(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, status, reason string) { + t.Helper() + var gotStatus string + var gotReason *string + if err := pool.QueryRow(ctx, `SELECT status, failure_reason FROM assessment_practices WHERE id = $1`, practiceID).Scan(&gotStatus, &gotReason); err != nil { + t.Fatalf("read practice status: %v", err) + } + if gotStatus != status || (gotReason != nil) != (reason != "") || (gotReason != nil && *gotReason != reason) { + t.Fatalf("practice status = %s %v, want %s %q", gotStatus, gotReason, status, reason) + } +} + +func practiceAttemptVersion(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 { + t.Helper() + var version int64 + if err := pool.QueryRow(ctx, `SELECT version FROM assessment_attempts WHERE id = $1`, attemptID).Scan(&version); err != nil { + t.Fatalf("read attempt version: %v", err) + } + return version +} + +func practiceJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool) map[string]int { + t.Helper() + rows, err := pool.Query(ctx, `SELECT state, count(*) FROM assessment_practice_jobs GROUP BY state`) + if err != nil { + t.Fatalf("count practice jobs: %v", err) + } + defer rows.Close() + states := map[string]int{} + for rows.Next() { + var state string + var count int + if err := rows.Scan(&state, &count); err != nil { + t.Fatalf("scan practice job count: %v", err) + } + states[state] = count + } + if err := rows.Err(); err != nil { + t.Fatalf("read practice job counts: %v", err) + } + return states +} + +func assertPracticeJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want map[string]int) { + t.Helper() + if got := practiceJobStates(t, ctx, pool); !sameJobStates(got, want) { + t.Fatalf("practice jobs = %v, want %v", got, want) + } +} + +func waitForPracticeJobStates(t *testing.T, ctx context.Context, pool *pgxpool.Pool, want map[string]int) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := practiceJobStates(t, ctx, pool) + if sameJobStates(got, want) { + return + } + if time.Now().After(deadline) || ctx.Err() != nil { + t.Fatalf("practice jobs = %v, want %v", got, want) + } + time.Sleep(20 * time.Millisecond) + } +} + +// sameJobStates compares the counts of the states in want; finished jobs of +// earlier cases are ignored unless want names them. +func sameJobStates(got, want map[string]int) bool { + for _, state := range []string{"queued", "running", "failed"} { + if got[state] != want[state] { + return false + } + } + if finished, named := want["finished"]; named && got["finished"] != finished { + return false + } + return true +} diff --git a/backend/integration_test/assessment_practice_runner_test.go b/backend/integration_test/assessment_practice_runner_test.go new file mode 100644 index 0000000..cf8c79d --- /dev/null +++ b/backend/integration_test/assessment_practice_runner_test.go @@ -0,0 +1,525 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/practice" +) + +const ( + practiceRunnerTestTimeout = 8 * time.Minute + // practiceRunnerBackoff moves the test clock past the first backoff of a + // failed try (10 s in the queue rig). + practiceRunnerBackoff = 11 * time.Second +) + +// TestAssessmentPracticeRunnerProtocol drives practice runs through the real +// router, the real queue worker, and the real TLS client of the code runner +// against a local fixture of the runner protocol. The fixture does not run +// code; see practiceRunnerFixture for what it decides. +func TestAssessmentPracticeRunnerProtocol(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), practiceRunnerTestTimeout) + defer cancel() + harness := newPracticeHarness(ctx, t, env, func(parts assessmentHarnessParts) (*practice.Service, error) { + return practice.NewService(parts.transactor, parts.keyring, parts.clock.Now, true) + }) + clock := &practiceQueueClock{} + runner := newPracticeRunnerFixture(t) + queue := newPracticeQueueRig(t, harness.pool, runner.client(t), clock) + + t.Run("python and go public runs finish and show the output of their own submission", func(t *testing.T) { + alpha := newPracticeCandidate(ctx, t, harness, "runner-alpha", 10) + beta := newPracticeCandidate(ctx, t, harness, "runner-beta", 20) + // Each candidate's own test expects a wrong sum, so the diagnostic of + // the failed test shows what that program printed for that input. + alphaRun := createPracticeRun(t, harness, alpha, "python", practiceRunnerPythonSource("alpha"), + []domain.PracticeTest{{Input: "40 2\n", ExpectedOutput: "41\n"}}, "runner-alpha-run") + betaRun := createPracticeRun(t, harness, beta, "go", practiceRunnerGoSource("beta"), + []domain.PracticeTest{{Input: "100 23\n", ExpectedOutput: "124\n"}}, "runner-beta-run") + if alphaRun.State != "queued" || betaRun.State != "queued" { + t.Fatalf("created runs are %q and %q, want queued", alphaRun.State, betaRun.State) + } + runsBefore := runner.runCount() + queue.drain(t, ctx) + + for _, expected := range []struct { + candidate practiceCandidate + run practiceRunnerRun + marker string + language string + output string + email string + }{ + {alpha, alphaRun, "alpha", "python3", "got 42", "runner-alpha@example.test"}, + {beta, betaRun, "beta", "go", "got 123", "runner-beta@example.test"}, + } { + read := readPracticeRunnerRun(t, harness, expected.candidate, expected.run.ID) + if read.State != "finished" || read.FailureReason != nil || read.FinishedAt == nil || read.Result == nil || read.Result.Outcome != "wrong_answer" { + t.Fatalf("run of %s = %+v, want finished with a wrong answer of the candidate's own test", expected.marker, read) + } + if len(read.Result.Tests) != 3 { + t.Fatalf("run of %s lists %d tests, want the 2 examples and the candidate's test", expected.marker, len(read.Result.Tests)) + } + for _, example := range read.Result.Tests[:2] { + if example.Source != "example" || example.Outcome != "accepted" || example.Diagnostic != nil { + t.Fatalf("example of %s = %+v, want accepted without a diagnostic", expected.marker, example) + } + } + own := read.Result.Tests[2] + if own.Source != "candidate" || own.Index != 1 || own.Outcome != "wrong_answer" || own.Diagnostic == nil || *own.Diagnostic != expected.output { + t.Fatalf("candidate test of %s = %+v, want a wrong answer with the output %q", expected.marker, own, expected.output) + } + + // The run behind the stored result belongs to this submission: the + // job keeps its runner run ID, and the runner started that run from + // this candidate's source. + job := readRunnerJob(t, ctx, harness.pool, expected.run.ID) + if job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.attempts != 0 || job.generation != 0 { + t.Fatalf("job of %s = %+v, want finished once with a runner run ID", expected.marker, job) + } + held, found := runner.run(job.runnerRunID.String()) + if !found || !strings.Contains(held.Request.Source, "marker: "+expected.marker+"\n") || string(held.Request.Language) != expected.language { + t.Fatalf("runner run %s = %+v (found %v), want the %s source of %s", job.runnerRunID, held.Request, found, expected.language, expected.marker) + } + requireRunnerRequestIsolated(t, runner, job.runnerRunID.String(), runnerIsolation{ + candidate: expected.candidate, email: expected.email, submissionID: expected.run.ID, + groups: []string{practice.PublicGroupID, practice.CustomGroupID}, forbidden: []string{practiceHiddenMarker, "hidden"}, + }) + } + if started := len(runner.runIDsSince(runsBefore)); started != 2 { + t.Fatalf("the runner started %d runs for two submissions, want 2", started) + } + // A candidate reads only their own run. + requireSessionProblem(t, practiceRunRead(t, harness, beta, alpha.attemptID, alphaRun.ID), http.StatusNotFound, "not_found") + requireSessionProblem(t, practiceRunRead(t, harness, beta, beta.attemptID, alphaRun.ID), http.StatusNotFound, "not_found") + assertPracticeStatus(t, ctx, harness.pool, alpha.practiceID, "not_started", "") + }) + + t.Run("a response cut after the runner accepted the run is repeated without a second run or result", func(t *testing.T) { + gamma := newPracticeCandidate(ctx, t, harness, "runner-gamma", 30) + runsBefore := runner.runCount() + runner.failNextAccept("cut") + submitPracticeFinal(t, ctx, harness, gamma, "runner-gamma-final") + submissionID := latestPracticeSubmission(t, ctx, harness.pool, gamma.practiceID, "final") + + if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry { + t.Fatalf("try with a cut response = %q claimed %v, error %v; want retry", outcome, claimed, err) + } + job := readRunnerJob(t, ctx, harness.pool, submissionID) + if job.state != "queued" || job.attempts != 1 || job.generation != 0 || job.errorClass != "runner_unavailable" || job.resultStored || job.runnerRunID != nil { + t.Fatalf("job after the cut = %+v, want queued on the same run key without a result", job) + } + assertPracticeStatus(t, ctx, harness.pool, gamma.practiceID, "pending", "") + if accepted := runner.runIDsSince(runsBefore); len(accepted) != 1 { + t.Fatalf("the runner accepted %d runs before the repeat, want 1", len(accepted)) + } + if _, claimed, err := queue.worker.RunOnce(ctx); err != nil || claimed { + t.Fatalf("claim before the backoff = %v, error %v; want none", claimed, err) + } + + clock.advance(practiceRunnerBackoff) + if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished { + t.Fatalf("repeat after the backoff = %q, error %v; want finished", outcome, err) + } + accepted := runner.runIDsSince(runsBefore) + job = readRunnerJob(t, ctx, harness.pool, submissionID) + if len(accepted) != 1 || job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.runnerRunID.String() != accepted[0] || job.generation != 0 { + t.Fatalf("job after the repeat = %+v with runs %v, want the single accepted run finished", job, accepted) + } + assertPracticeStatus(t, ctx, harness.pool, gamma.practiceID, "finished", "") + assertFinalResultCount(t, ctx, harness.pool, gamma.practiceID, 1) + requireRunnerRequestIsolated(t, runner, accepted[0], runnerIsolation{ + candidate: gamma, email: "runner-gamma@example.test", submissionID: submissionID, + groups: []string{"hidden-1", "hidden-2", "hidden-3"}, forbidden: []string{"public", "custom"}, + }) + }) + + t.Run("a run that outlasts the request timeout is joined on the repeat", func(t *testing.T) { + delta := newPracticeCandidate(ctx, t, harness, "runner-delta", 40) + runsBefore := runner.runCount() + runner.failNextAccept("stall") + run := createPracticeRun(t, harness, delta, "python", practiceRunnerPythonSource("delta"), nil, "runner-delta-run") + + if outcome, claimed, err := queue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry { + t.Fatalf("try that timed out = %q claimed %v, error %v; want retry", outcome, claimed, err) + } + job := readRunnerJob(t, ctx, harness.pool, run.ID) + if job.state != "queued" || job.attempts != 1 || job.generation != 0 || job.errorClass != "runner_unavailable" || job.resultStored { + t.Fatalf("job after the timeout = %+v, want queued on the same run key", job) + } + if read := readPracticeRunnerRun(t, harness, delta, run.ID); read.State != "queued" || read.FailureReason != nil || read.Result != nil { + t.Fatalf("run while the try is repeated = %+v, want queued", read) + } + + clock.advance(practiceRunnerBackoff) + if outcome, _, err := queue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFinished { + t.Fatalf("repeat after the timeout = %q, error %v; want finished", outcome, err) + } + accepted := runner.runIDsSince(runsBefore) + job = readRunnerJob(t, ctx, harness.pool, run.ID) + if len(accepted) != 1 || job.state != "finished" || !job.resultStored || job.runnerRunID == nil || job.runnerRunID.String() != accepted[0] { + t.Fatalf("job after the repeat = %+v with runs %v, want the single accepted run finished", job, accepted) + } + if read := readPracticeRunnerRun(t, harness, delta, run.ID); read.State != "finished" || read.Result == nil || read.Result.Outcome != "accepted" { + t.Fatalf("run after the repeat = %+v, want finished and accepted", read) + } + }) + + t.Run("a worker restarted with a new client joins the run of the dead one", func(t *testing.T) { + epsilon := newPracticeCandidate(ctx, t, harness, "runner-epsilon", 50) + submitPracticeFinal(t, ctx, harness, epsilon, "runner-epsilon-final") + submissionID := latestPracticeSubmission(t, ctx, harness.pool, epsilon.practiceID, "final") + runsBefore := runner.runCount() + runner.hold(true) + defer runner.hold(false) + + crashedPool := newPoolFor(ctx, t, harness.databaseURL) + crashed := queue.workerOn(t, crashedPool) + crashCtx, crash := context.WithCancel(ctx) + crashedDone := make(chan struct{}) + go func() { + defer close(crashedDone) + _, _, _ = crashed.worker.RunOnce(crashCtx) + }() + waitForRunnerRuns(t, ctx, runner, runsBefore+1) + // The process dies: its connections are gone, so the lease keeps the + // job running. + crashedPool.Close() + crash() + <-crashedDone + started := runner.runIDsSince(runsBefore) + if len(started) != 1 { + t.Fatalf("the dead worker started %d runs, want 1", len(started)) + } + + // The new process builds a new client from the same settings. + restartedRig := newPracticeQueueRig(t, harness.pool, runner.client(t), clock) + clock.advance(practiceQueueLease + time.Second) + runner.hold(false) + if outcome, claimed, err := restartedRig.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeFinished { + t.Fatalf("restarted worker = %q claimed %v, error %v; want the job finished", outcome, claimed, err) + } + job := readRunnerJob(t, ctx, harness.pool, submissionID) + if job.state != "finished" || job.attempts != 1 || job.generation != 0 || job.runnerRunID == nil || job.runnerRunID.String() != started[0] || !job.resultStored { + t.Fatalf("recovered job = %+v, want finished on the run %s with one counted takeover", job, started[0]) + } + if all := runner.runIDsSince(runsBefore); len(all) != 1 { + t.Fatalf("the runner holds %d runs for the submission, want 1", len(all)) + } + assertFinalResultCount(t, ctx, harness.pool, epsilon.practiceID, 1) + assertPracticeStatus(t, ctx, harness.pool, epsilon.practiceID, "finished", "") + }) + + t.Run("a stopped runner leaves a retryable state and changes nothing about the candidate", func(t *testing.T) { + stopped := newPracticeRunnerFixture(t) + stoppedQueue := newPracticeQueueRig(t, harness.pool, stopped.client(t), clock) + stopped.stop() + + zeta := newPracticeCandidate(ctx, t, harness, "runner-zeta", 60) + before := candidateGradeState(t, ctx, harness.pool, zeta) + run := createPracticeRun(t, harness, zeta, "python", practiceRunnerPythonSource("zeta"), nil, "runner-zeta-run") + + // Two tries fail and wait for their backoff; the run stays queued, + // which tells the client to read it again. + for try := 1; try <= 2; try++ { + if outcome, claimed, err := stoppedQueue.worker.RunOnce(ctx); err != nil || !claimed || outcome != practice.OutcomeRetry { + t.Fatalf("try %d on a stopped runner = %q claimed %v, error %v; want retry", try, outcome, claimed, err) + } + read := readPracticeRunnerRun(t, harness, zeta, run.ID) + if read.State != "queued" || read.FailureReason != nil || read.Result != nil || read.FinishedAt != nil { + t.Fatalf("run after try %d = %+v, want queued without a verdict", try, read) + } + clock.advance(practiceRunnerBackoff * 2) + } + if outcome, _, err := stoppedQueue.worker.RunOnce(ctx); err != nil || outcome != practice.OutcomeFailed { + t.Fatalf("last try on a stopped runner = %q, error %v; want failed without a verdict", outcome, err) + } + read := readPracticeRunnerRun(t, harness, zeta, run.ID) + if read.State != "failed" || read.FailureReason == nil || *read.FailureReason != "sandbox_error" || read.Result != nil || read.FinishedAt == nil { + t.Fatalf("run after the last try = %+v, want failed with sandbox_error and no result", read) + } + job := readRunnerJob(t, ctx, harness.pool, run.ID) + if job.state != "failed" || job.errorClass != "runner_unavailable" || job.resultStored || job.runnerRunID != nil { + t.Fatalf("job after the last try = %+v, want failed with no result and no runner run", job) + } + if after := candidateGradeState(t, ctx, harness.pool, zeta); after != before { + t.Fatalf("candidate state changed by an infrastructure failure:\nbefore %s\nafter %s", before, after) + } + assertPracticeStatus(t, ctx, harness.pool, zeta.practiceID, "not_started", "") + + // The failure is retryable: the same practice takes a new run, and the + // working runner finishes it. + again := createPracticeRun(t, harness, zeta, "python", practiceRunnerPythonSource("zeta-again"), nil, "runner-zeta-again") + queue.drain(t, ctx) + if read := readPracticeRunnerRun(t, harness, zeta, again.ID); read.State != "finished" || read.Result == nil || read.Result.Outcome != "accepted" { + t.Fatalf("run after the runner came back = %+v, want finished and accepted", read) + } + + // A final solution is no verdict either: the practice fails without a + // grade and accepts the solution again. + eta := newPracticeCandidate(ctx, t, harness, "runner-eta", 70) + etaBefore := candidateGradeState(t, ctx, harness.pool, eta) + submitPracticeFinal(t, ctx, harness, eta, "runner-eta-final") + stoppedQueue.drain(t, ctx) + assertPracticeStatus(t, ctx, harness.pool, eta.practiceID, "failed", "sandbox_error") + assertNoPracticeResult(t, ctx, harness.pool, eta.practiceID) + if after := candidateGradeState(t, ctx, harness.pool, eta); after != etaBefore { + t.Fatalf("candidate state changed by an infrastructure failure:\nbefore %s\nafter %s", etaBefore, after) + } + submitPracticeFinal(t, ctx, harness, eta, "runner-eta-final-again") + queue.drain(t, ctx) + assertPracticeStatus(t, ctx, harness.pool, eta.practiceID, "finished", "") + assertFinalResultCount(t, ctx, harness.pool, eta.practiceID, 1) + }) + + assertEverySubmissionHasOneJob(t, ctx, harness.pool) + assertEveryRunnerRunHasOneResult(t, ctx, harness.pool) +} + +func practiceRunnerPythonSource(marker string) string { + return practicePythonSum + "# marker: " + marker + "\n" +} + +func practiceRunnerGoSource(marker string) string { + return practiceGoSum + "// marker: " + marker + "\n" +} + +// practiceRunnerRun is a created run as the API answers it. +type practiceRunnerRun struct { + ID uuid.UUID + State string +} + +func createPracticeRun( + t *testing.T, + harness *practiceHarness, + candidate practiceCandidate, + language, source string, + tests []domain.PracticeTest, + key string, +) practiceRunnerRun { + t.Helper() + response := practiceRunRequest(t, harness, candidate, practiceRunBody(t, candidate.practiceID, language, source, tests), key) + if response.Code != http.StatusAccepted { + t.Fatalf("create %s run = %d %s", language, response.Code, response.Body.String()) + } + run := decodePracticeRun(t, response) + return practiceRunnerRun{ID: run.ID, State: run.State} +} + +// practiceRunnerRunBody decodes the fields of a run that these tests read. +type practiceRunnerRunBody struct { + ID uuid.UUID `json:"id"` + State string `json:"state"` + FinishedAt *time.Time `json:"finished_at"` + FailureReason *string `json:"failure_reason"` + Result *struct { + Outcome string `json:"outcome"` + Tests []struct { + Source string `json:"source"` + Index int `json:"index"` + Outcome string `json:"outcome"` + Diagnostic *string `json:"diagnostic"` + } `json:"tests"` + } `json:"result"` +} + +// readPracticeRunnerRun reads a run of the candidate's own attempt through +// the API and checks that the response is public. +func readPracticeRunnerRun(t *testing.T, harness *practiceHarness, candidate practiceCandidate, runID uuid.UUID) practiceRunnerRunBody { + t.Helper() + response := practiceRunRead(t, harness, candidate, candidate.attemptID, runID) + if response.Code != http.StatusOK { + t.Fatalf("read run = %d %s", response.Code, response.Body.String()) + } + assertPracticeResponseIsPublic(t, response) + var run practiceRunnerRunBody + if err := json.Unmarshal(response.Body.Bytes(), &run); err != nil || run.ID != runID { + t.Fatalf("run response %s: %v", response.Body.String(), err) + } + return run +} + +// runnerJobRow is the execution job of a submission with its stored outcome. +type runnerJobRow struct { + state string + attempts int + generation int + errorClass string + runnerRunID *uuid.UUID + resultStored bool +} + +func readRunnerJob(t *testing.T, ctx context.Context, pool *pgxpool.Pool, submissionID uuid.UUID) runnerJobRow { + t.Helper() + var job runnerJobRow + var class *string + if err := pool.QueryRow(ctx, `SELECT job.state, job.attempts, job.generation, job.last_error_class, job.runner_run_id, + submission.result IS NOT NULL + FROM assessment_practice_jobs AS job + JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id + WHERE job.submission_id = $1`, submissionID).Scan( + &job.state, &job.attempts, &job.generation, &class, &job.runnerRunID, &job.resultStored); err != nil { + t.Fatalf("read practice job: %v", err) + } + if class != nil { + job.errorClass = *class + } + return job +} + +func assertFinalResultCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, practiceID uuid.UUID, want int) { + t.Helper() + var stored int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_practice_submissions + WHERE practice_id = $1 AND mode = 'final' AND result IS NOT NULL`, practiceID).Scan(&stored); err != nil { + t.Fatalf("count final results: %v", err) + } + if stored != want { + t.Fatalf("%d final results stored, want %d", stored, want) + } +} + +// assertEveryRunnerRunHasOneResult checks that a runner run ID belongs to one +// finished job that has a result, and that no unfinished job has one. +func assertEveryRunnerRunHasOneResult(t *testing.T, ctx context.Context, pool *pgxpool.Pool) { + t.Helper() + var duplicated, withoutResult int + if err := pool.QueryRow(ctx, `SELECT + (SELECT count(*) FROM (SELECT runner_run_id FROM assessment_practice_jobs + WHERE runner_run_id IS NOT NULL GROUP BY runner_run_id HAVING count(*) > 1) AS repeated), + (SELECT count(*) FROM assessment_practice_jobs AS job + JOIN assessment_practice_submissions AS submission ON submission.id = job.submission_id + WHERE job.state = 'finished' AND job.runner_run_id IS NOT NULL AND submission.result IS NULL)`).Scan(&duplicated, &withoutResult); err != nil { + t.Fatalf("check runner runs: %v", err) + } + if duplicated != 0 || withoutResult != 0 { + t.Fatalf("%d runner runs repeat and %d have no result, want none", duplicated, withoutResult) + } +} + +// candidateGradeState is what an infrastructure failure must not change: the +// confirmed categories, the results, and the state and version of the attempt. +func candidateGradeState(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidate practiceCandidate) string { + t.Helper() + var state string + if err := pool.QueryRow(ctx, `SELECT jsonb_build_object( + 'categories', coalesce((SELECT jsonb_agg(to_jsonb(category) ORDER BY category.specialization) + FROM candidate_assessment_categories AS category WHERE category.candidate_id = $1), '[]'::jsonb), + 'results', (SELECT count(*) FROM assessment_attempt_results WHERE user_id = $1), + 'attempt', (SELECT jsonb_build_object('state', attempt.state, 'version', attempt.version) + FROM assessment_attempts AS attempt WHERE attempt.id = $2))::text`, + candidate.userID, candidate.attemptID).Scan(&state); err != nil { + t.Fatalf("read candidate grade state: %v", err) + } + return state +} + +func waitForRunnerRuns(t *testing.T, ctx context.Context, runner *practiceRunnerFixture, want int) { + t.Helper() + for ctx.Err() == nil { + if runner.runCount() >= want { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("runner did not accept %d runs", want) +} + +// runnerIsolation says what the runner may see of one submission. +type runnerIsolation struct { + candidate practiceCandidate + email string + submissionID uuid.UUID + // groups are the group IDs of the request, in order. + groups []string + // forbidden are texts that the request must not carry. + forbidden []string +} + +// requireRunnerRequestIsolated checks the wire form of a run: the path holds +// an opaque run ID, the headers hold only the transport and the service +// token, and the body holds the language, the source, the limits, and the +// groups, with nothing about the candidate, the attempt, or the submission. +func requireRunnerRequestIsolated(t *testing.T, runner *practiceRunnerFixture, runID string, want runnerIsolation) { + t.Helper() + var puts []runnerCall + for _, call := range runner.callsFor(runID) { + if call.Method == http.MethodPut { + puts = append(puts, call) + } + } + if len(puts) == 0 { + t.Fatalf("the runner saw no PUT of run %s", runID) + } + identifiers := []string{ + want.candidate.userID.String(), want.candidate.attemptID.String(), want.candidate.practiceID.String(), + want.candidate.additionalID.String(), want.submissionID.String(), want.email, want.candidate.cookie, want.candidate.csrf, + } + if slices.Contains(identifiers, runID) { + t.Fatalf("the run ID %s is a business identifier", runID) + } + parsed, err := uuid.Parse(runID) + if err != nil || parsed.Version() != 8 { + t.Fatalf("run ID %q is not an opaque version 8 UUID: %v", runID, err) + } + allowedHeaders := []string{"Accept", "Accept-Encoding", "Authorization", "Content-Length", "Content-Type", "User-Agent"} + for _, call := range puts { + for name, values := range call.Header { + if !slices.Contains(allowedHeaders, name) { + t.Fatalf("request to the runner carries the header %s", name) + } + for _, value := range values { + for _, identifier := range identifiers { + if strings.Contains(value, identifier) { + t.Fatalf("header %s carries an identifier of the candidate", name) + } + } + } + } + body := string(call.Body) + for _, text := range append(append([]string(nil), identifiers...), want.forbidden...) { + if text != "" && strings.Contains(body, text) { + t.Fatalf("request to the runner carries %q: %s", text, body) + } + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(call.Body, &fields); err != nil { + t.Fatalf("decode the request to the runner: %v", err) + } + names := make([]string, 0, len(fields)) + for name := range fields { + names = append(names, name) + } + slices.Sort(names) + if !slices.Equal(names, []string{"groups", "language", "limits", "source"}) { + t.Fatalf("request to the runner has the fields %v, want groups, language, limits, and source only", names) + } + var groups []struct { + ID string `json:"id"` + } + if err := json.Unmarshal(fields["groups"], &groups); err != nil { + t.Fatalf("decode the groups sent to the runner: %v", err) + } + got := make([]string, 0, len(groups)) + for _, group := range groups { + got = append(got, group.ID) + } + if !slices.Equal(got, want.groups) { + t.Fatalf("groups sent to the runner = %v, want %v", got, want.groups) + } + } +} diff --git a/backend/integration_test/assessment_signal_http_test.go b/backend/integration_test/assessment_signal_http_test.go new file mode 100644 index 0000000..235afd3 --- /dev/null +++ b/backend/integration_test/assessment_signal_http_test.go @@ -0,0 +1,442 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +const assessmentSignalHTTPTimeout = 6 * time.Minute + +func TestAssessmentSignalsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentSignalHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + t.Cleanup(harness.pool.Close) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.201:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.202:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + + trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "signal-training", "192.0.2.203:1234") + if trainingCreate.Code != http.StatusCreated { + t.Fatalf("create demo attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String()) + } + trainingAttempt, trainingItem := assessmentSignalAttemptItem(t, trainingCreate.Body.Bytes()) + grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.204:1234") + + trainingBody := assessmentSignalBody(t, trainingItem, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil) + trainingSignal := submitAssessmentSignal(t, harness, trainingAttempt, cookie, csrf, "signal-demo", trainingBody, "192.0.2.205:1234") + requireSessionProblem(t, trainingSignal, http.StatusConflict, "state_conflict") + + rootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "signal-root", "192.0.2.206:1234") + if rootCreate.Code != http.StatusCreated { + t.Fatalf("create real assessment attempt = %d %s", rootCreate.Code, rootCreate.Body.String()) + } + attemptID, itemID := assessmentSignalAttemptItem(t, rootCreate.Body.Bytes()) + occurredAt := time.Now().UTC().Truncate(time.Microsecond) + body := assessmentSignalBody(t, itemID, occurredAt, "fullscreen_exit", nil) + + badItemBody := assessmentSignalBody(t, uuid.New(), occurredAt, "fullscreen_exit", nil) + badItem := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-bad-item", badItemBody, "192.0.2.207:1234") + if badItem.Code != http.StatusBadRequest { + t.Fatalf("foreign item signal = %d %s, want 400", badItem.Code, badItem.Body.String()) + } + oldTimestampBody := assessmentSignalBody(t, itemID, occurredAt.Add(-10*time.Minute), "fullscreen_exit", nil) + oldTimestamp := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-old-time", oldTimestampBody, "192.0.2.208:1234") + if oldTimestamp.Code != http.StatusBadRequest { + t.Fatalf("out-of-window client timestamp = %d %s, want 400", oldTimestamp.Code, oldTimestamp.Body.String()) + } + + oversizedBody := `{"events":[]}` + strings.Repeat(" ", 32<<10) + oversized := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-oversized", oversizedBody, "192.0.2.209:1234") + requireSessionProblem(t, oversized, http.StatusRequestEntityTooLarge, "payload_too_large") + + accepted := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.210:1234") + assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 1) + if accepted.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("signal receipt Cache-Control = %q, want no-store", accepted.Header().Get("Cache-Control")) + } + var receipt map[string]any + if err := json.Unmarshal(accepted.Body.Bytes(), &receipt); err != nil || len(receipt) != 3 { + t.Fatalf("receipt fields = %+v, decode error %v", receipt, err) + } + for _, privateField := range []string{"events", "item_instance_id", "size_bytes", "answer", "score", "result"} { + if _, exposed := receipt[privateField]; exposed { + t.Fatalf("signal receipt exposed %q", privateField) + } + } + assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1) + assertAssessmentSignalImmutability(t, ctx, harness.pool, attemptID) + + replay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.211:1234") + if replay.Code != accepted.Code || replay.Body.String() != accepted.Body.String() { + t.Fatalf("same-key signal replay = %d %s, want original %d %s", replay.Code, replay.Body.String(), accepted.Code, accepted.Body.String()) + } + changedBody := assessmentSignalBody(t, itemID, occurredAt.Add(time.Second), "fullscreen_exit", nil) + changedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.212:1234") + requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused") + assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1) + expiredScope := harness.keyring.IdempotencyScope("assessment_attempt.signals", "signal-first", candidate.ID.String()) + applicationNow := harness.clock.Now() + if _, err := harness.pool.Exec(ctx, `UPDATE idempotency_records + SET created_at = $2::timestamptz - INTERVAL '25 hours', expires_at = $2::timestamptz - INTERVAL '1 second' + WHERE scope_hash = $1`, expiredScope[:], applicationNow); err != nil { + t.Fatalf("expire signal idempotency scope fixture: %v", err) + } + expiredReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.224:1234") + assertSignalReceipt(t, expiredReplay, http.StatusOK, "accepted", 1) + assertSignalStoredCounts(t, ctx, harness, attemptID, 2, 2, 1) + + assertAssessmentSignalMeasurementChecks(t, ctx, harness.pool, attemptID, itemID) + + concurrentBodies := []string{ + assessmentSignalBody(t, itemID, occurredAt.Add(2*time.Second), "copy", int32Pointer(12)), + assessmentSignalBody(t, itemID, occurredAt.Add(3*time.Second), "copy", int32Pointer(13)), + } + concurrentResponses := make([]*httptest.ResponseRecorder, len(concurrentBodies)) + start := make(chan struct{}) + var wait sync.WaitGroup + for index := range concurrentBodies { + wait.Add(1) + go func(index int) { + defer wait.Done() + <-start + concurrentResponses[index] = submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-concurrent", concurrentBodies[index], fmt.Sprintf("198.51.100.%d:1234", index+10)) + }(index) + } + close(start) + wait.Wait() + acceptedIndex := -1 + conflictIndex := -1 + for index, response := range concurrentResponses { + switch response.Code { + case http.StatusOK: + acceptedIndex = index + case http.StatusUnprocessableEntity: + requireSessionProblem(t, response, http.StatusUnprocessableEntity, "idempotency_key_reused") + conflictIndex = index + default: + t.Fatalf("concurrent signal %d = %d %s", index, response.Code, response.Body.String()) + } + } + if acceptedIndex < 0 || conflictIndex < 0 || acceptedIndex == conflictIndex { + t.Fatalf("concurrent same-key outcomes accepted=%d conflict=%d", acceptedIndex, conflictIndex) + } + assertSignalReceipt(t, concurrentResponses[acceptedIndex], http.StatusOK, "accepted", 1) + assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2) + + otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-other@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", otherCandidate.ID); err != nil { + t.Fatalf("set cascade candidate onboarding step: %v", err) + } + otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.213:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "192.0.2.220:1234"); response.Code != http.StatusOK { + t.Fatalf("save cascade candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "192.0.2.221:1234") + foreignAttempt := submitAssessmentSignal(t, harness, attemptID, otherCookie, otherCSRF, "signal-foreign", body, "192.0.2.214:1234") + requireSessionProblem(t, foreignAttempt, http.StatusNotFound, "not_found") + assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2) + otherRootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "signal-cascade", "192.0.2.222:1234") + if otherRootCreate.Code != http.StatusCreated { + t.Fatalf("create cascade candidate attempt = %d %s", otherRootCreate.Code, otherRootCreate.Body.String()) + } + otherAttemptID, otherItemID := assessmentSignalAttemptItem(t, otherRootCreate.Body.Bytes()) + otherSignalBody := assessmentSignalBody(t, otherItemID, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil) + otherAccepted := submitAssessmentSignal(t, harness, otherAttemptID, otherCookie, otherCSRF, "signal-cascade", otherSignalBody, "192.0.2.223:1234") + assertSignalReceipt(t, otherAccepted, http.StatusOK, "accepted", 1) + assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1) + + revokeC3 := assessmentAttemptHTTPRequest(t, harness, http.MethodDelete, "/api/v1/me/consents/c3", "", + sessionHTTPTestOrigin, cookie.Value, csrf, "", "192.0.2.215:1234") + if revokeC3.Code != http.StatusNoContent { + t.Fatalf("revoke C3 = %d %s", revokeC3.Code, revokeC3.Body.String()) + } + withoutC3 := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-no-c3", body, "192.0.2.216:1234") + requireSessionProblem(t, withoutC3, http.StatusForbidden, "forbidden") + grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.217:1234") + + seedAssessmentSignalCapacity(ctx, t, harness.pool, attemptID, itemID, 10000) + assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 2) + saturatedBody := assessmentSignalBody(t, itemID, occurredAt.Add(4*time.Second), "fullscreen_exit", nil) + saturated := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.218:1234") + assertSignalReceipt(t, saturated, http.StatusOK, "saturated", 0) + saturatedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.219:1234") + if saturatedReplay.Body.String() != saturated.Body.String() { + t.Fatalf("saturated replay = %s, want %s", saturatedReplay.Body.String(), saturated.Body.String()) + } + assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 3) + + for next := signalOutcomeCount(t, ctx, harness.pool, attemptID); next < 30; next++ { + key := fmt.Sprintf("signal-rate-%02d", next) + response := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, key, saturatedBody, fmt.Sprintf("203.0.113.%d:1234", next+1)) + assertSignalReceipt(t, response, http.StatusOK, "saturated", 0) + } + limitedKey := "signal-rate-retry" + limited := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, limitedKey, saturatedBody, "203.0.113.80:1234") + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("rate-limited signal response omitted Retry-After") + } + scope := harness.keyring.IdempotencyScope("assessment_attempt.signals", limitedKey, candidate.ID.String()) + var consumed int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash = $1", scope[:]).Scan(&consumed); err != nil { + t.Fatalf("check rejected idempotency scope: %v", err) + } + if consumed != 0 { + t.Fatalf("rate-limited idempotency scopes = %d, want 0", consumed) + } + assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 30) + + terminalizeAttempt(t, ctx, harness.pool, attemptID) + terminal := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-terminal", saturatedBody, "203.0.113.81:1234") + requireSessionProblem(t, terminal, http.StatusConflict, "state_conflict") + + if _, err := harness.pool.Exec(ctx, "DELETE FROM assessment_attempts WHERE id = $1", attemptID); err != nil { + t.Fatalf("delete attempt for signal cascade test: %v", err) + } + deletedAttemptReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "203.0.113.82:1234") + requireSessionProblem(t, deletedAttemptReplay, http.StatusNotFound, "not_found") + assertSignalStoredCounts(t, ctx, harness, attemptID, 0, 0, 0) + + _, accountDeleteErr := harness.pool.Exec(ctx, "DELETE FROM users WHERE id = $1", otherCandidate.ID) + assertSQLError(t, "delete account with retained consent history", accountDeleteErr, consentRestrictViolation, "consent_records_subject_id_fkey") + var retainedConsentRecords int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", otherCandidate.ID).Scan(&retainedConsentRecords); err != nil { + t.Fatalf("count retained consent records after rejected account deletion: %v", err) + } + if retainedConsentRecords == 0 { + t.Fatal("account deletion removed the candidate's retained consent records") + } + assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1) +} + +func assessmentSignalAttemptItem(t *testing.T, body []byte) (uuid.UUID, uuid.UUID) { + t.Helper() + var attempt struct { + ID uuid.UUID `json:"id"` + CurrentItem *struct { + ID uuid.UUID `json:"id"` + } `json:"current_item"` + } + if err := json.Unmarshal(body, &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil || attempt.CurrentItem.ID == uuid.Nil { + t.Fatalf("decode signal test attempt and item: %+v, error %v", attempt, err) + } + return attempt.ID, attempt.CurrentItem.ID +} + +func assessmentSignalBody(t *testing.T, itemID uuid.UUID, occurredAt time.Time, kind string, size *int32) string { + t.Helper() + event := map[string]any{ + "kind": kind, "item_instance_id": itemID, "occurred_at": occurredAt.UTC().Format(time.RFC3339Nano), + } + if size != nil { + event["size_bytes"] = *size + } + body, err := json.Marshal(map[string]any{"events": []any{event}}) + if err != nil { + t.Fatalf("marshal signal test body: %v", err) + } + return string(body) +} + +func int32Pointer(value int32) *int32 { return &value } + +func submitAssessmentSignal( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, + cookie *http.Cookie, + csrf, key, body, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + path := "/api/v1/me/assessment-attempts/" + attemptID.String() + "/signals" + return assessmentAttemptHTTPRequest(t, harness, http.MethodPost, path, body, + sessionHTTPTestOrigin, cookie.Value, csrf, key, remoteAddr) +} + +func assertSignalReceipt(t *testing.T, response *httptest.ResponseRecorder, status int, receiptStatus string, accepted int) { + t.Helper() + var receipt struct { + Status string `json:"status"` + AcceptedEvents int `json:"accepted_events"` + ReceivedAt time.Time `json:"received_at"` + } + if response.Code != status || json.Unmarshal(response.Body.Bytes(), &receipt) != nil || + receipt.Status != receiptStatus || receipt.AcceptedEvents != accepted || receipt.ReceivedAt.IsZero() { + t.Fatalf("signal receipt = %d %s, want %d/%s/%d", response.Code, response.Body.String(), status, receiptStatus, accepted) + } +} + +func assertSignalStoredCounts( + t *testing.T, + ctx context.Context, + harness *assessmentAttemptHTTPHarness, + attemptID uuid.UUID, + wantEvents, wantBatches, wantOutcomes int64, +) { + t.Helper() + for _, check := range []struct { + table string + want int64 + }{ + {table: "assessment_signal_events", want: wantEvents}, + {table: "assessment_signal_batches", want: wantBatches}, + {table: "assessment_signal_idempotency_outcomes", want: wantOutcomes}, + } { + var got int64 + query := "SELECT count(*) FROM " + check.table + " WHERE attempt_id = $1" + if err := harness.pool.QueryRow(ctx, query, attemptID).Scan(&got); err != nil { + t.Fatalf("count %s: %v", check.table, err) + } + if got != check.want { + t.Fatalf("%s rows = %d, want %d", check.table, got, check.want) + } + } +} + +func assertAssessmentSignalMeasurementChecks(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID, itemID uuid.UUID) { + t.Helper() + for index, kind := range []string{"focus_loss", "copy"} { + batchID := uuid.New() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin measurement check %d: %v", index, err) + } + if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count) + VALUES ($1, $2, clock_timestamp(), 1)`, batchID, attemptID); err != nil { + t.Fatalf("insert measurement boundary batch: %v", err) + } + _, err = tx.Exec(ctx, `INSERT INTO assessment_signal_events ( + batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes + ) VALUES ($1, $2, 1, $3, $4, clock_timestamp(), NULL, NULL)`, batchID, attemptID, itemID, kind) + assertPgError(t, "reject null measurement for "+kind, err, "23514", "assessment_signal_events_measurement") + if err := tx.Rollback(ctx); err != nil { + t.Fatalf("rollback measurement check %d: %v", index, err) + } + } +} + +func assertAssessmentSignalImmutability(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) { + t.Helper() + var batchID uuid.UUID + if err := pool.QueryRow(ctx, `SELECT id FROM assessment_signal_batches + WHERE attempt_id = $1 ORDER BY received_at, id LIMIT 1`, attemptID).Scan(&batchID); err != nil { + t.Fatalf("read signal batch for immutability checks: %v", err) + } + _, err := pool.Exec(ctx, "UPDATE assessment_signal_batches SET event_count = event_count WHERE id = $1", batchID) + assertPgError(t, "reject signal batch update", err, "23000", "assessment_signal_batches_immutable") + _, err = pool.Exec(ctx, "DELETE FROM assessment_signal_batches WHERE id = $1", batchID) + assertPgError(t, "reject direct signal batch deletion", err, "23000", "assessment_signal_batches_immutable") + var ordinal int32 + if err := pool.QueryRow(ctx, `SELECT ordinal FROM assessment_signal_events + WHERE batch_id = $1 ORDER BY ordinal LIMIT 1`, batchID).Scan(&ordinal); err != nil { + t.Fatalf("read signal event for immutability checks: %v", err) + } + _, err = pool.Exec(ctx, "UPDATE assessment_signal_events SET occurred_at = occurred_at WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal) + assertPgError(t, "reject signal event update", err, "23000", "assessment_signal_events_immutable") + _, err = pool.Exec(ctx, "DELETE FROM assessment_signal_events WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal) + assertPgError(t, "reject direct signal event deletion", err, "23000", "assessment_signal_events_immutable") + + var scopeHash []byte + if err := pool.QueryRow(ctx, `SELECT scope_hash FROM assessment_signal_idempotency_outcomes + WHERE attempt_id = $1 ORDER BY received_at LIMIT 1`, attemptID).Scan(&scopeHash); err != nil { + t.Fatalf("read signal outcome for immutability check: %v", err) + } + _, err = pool.Exec(ctx, "UPDATE assessment_signal_idempotency_outcomes SET status = status WHERE scope_hash = $1", scopeHash) + assertPgError(t, "reject signal outcome update", err, "23000", "assessment_signal_idempotency_outcomes_immutable") +} + +func seedAssessmentSignalCapacity( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + attemptID, itemID uuid.UUID, + wantTotal int64, +) { + t.Helper() + var existing int64 + if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_events WHERE attempt_id = $1", attemptID).Scan(&existing); err != nil { + t.Fatalf("read signal count before capacity fixture: %v", err) + } + remaining := wantTotal - existing + if remaining <= 0 { + t.Fatalf("capacity fixture has no remaining rows: existing=%d target=%d", existing, wantTotal) + } + batchCount := int((remaining + 49) / 50) + batchIDs := make([]uuid.UUID, batchCount) + for index := range batchIDs { + batchIDs[index] = uuid.New() + } + tx, err := pool.BeginTx(ctx, pgx.TxOptions{}) + if err != nil { + t.Fatalf("begin bounded capacity fixture: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events DISABLE TRIGGER assessment_signal_event_guard"); err != nil { + t.Fatalf("disable only the capacity backstop for isolated fixture: %v", err) + } + if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count) + SELECT batch.batch_id, $1, clock_timestamp(), LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer + FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)`, attemptID, batchIDs, remaining); err != nil { + t.Fatalf("insert bounded signal capacity batches: %v", err) + } + if _, err := tx.Exec(ctx, `WITH batches AS ( + SELECT batch.batch_id, LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer AS event_count + FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality) + ) + INSERT INTO assessment_signal_events ( + batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes + ) + SELECT batches.batch_id, $1, event.ordinality::integer, $4, 'fullscreen_exit', clock_timestamp(), NULL, NULL + FROM batches + CROSS JOIN LATERAL generate_series(1, batches.event_count) AS event(ordinality)`, attemptID, batchIDs, remaining, itemID); err != nil { + t.Fatalf("insert bounded signal capacity events: %v", err) + } + if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events ENABLE TRIGGER assessment_signal_event_guard"); err != nil { + t.Fatalf("restore signal capacity trigger: %v", err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit isolated signal capacity fixture: %v", err) + } +} + +func signalOutcomeCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 { + t.Helper() + var count int64 + if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_idempotency_outcomes WHERE attempt_id = $1", attemptID).Scan(&count); err != nil { + t.Fatalf("count signal receipts: %v", err) + } + return count +} diff --git a/backend/integration_test/assessment_signal_notice_http_test.go b/backend/integration_test/assessment_signal_notice_http_test.go new file mode 100644 index 0000000..0efb7ea --- /dev/null +++ b/backend/integration_test/assessment_signal_notice_http_test.go @@ -0,0 +1,135 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "lincodex/backend/internal/usecase/assessment" +) + +const assessmentSignalNoticePath = "/api/v1/me/assessment-signal-notice" + +type signalNoticeProjection struct { + NoticeVersion int `json:"notice_version"` + Acknowledged bool `json:"acknowledged"` + AcknowledgedAt *string `json:"acknowledged_at"` +} + +// noticeBody is the request body that acknowledges the given notice version. +func noticeBody(version int) string { + return fmt.Sprintf(`{"notice_version":%d}`, version) +} + +func decodeSignalNotice(t *testing.T, response *httptest.ResponseRecorder) signalNoticeProjection { + t.Helper() + if response.Code != http.StatusOK { + t.Fatalf("signal notice response = %d %s, want 200", response.Code, response.Body.String()) + } + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("signal notice Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + var notice signalNoticeProjection + if err := json.Unmarshal(response.Body.Bytes(), ¬ice); err != nil { + t.Fatalf("decode signal notice: %v", err) + } + return notice +} + +func TestAssessmentSignalNoticeOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + t.Cleanup(harness.pool.Close) + + // The tests follow the version the server requires, so a new text version + // needs no edit here. + current := int(assessment.CurrentSignalNoticeVersion) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "notice-owner@example.test", passwordHash, true) + other := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "notice-other@example.test", passwordHash, true) + employer := createAssessmentAvailabilityEmployer(ctx, t, harness.sessionHTTPHarness, "notice-employer@example.test", passwordHash) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.231:1234") + otherCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, other.Email.Address(), "192.0.2.232:1234") + employerCookie, employerCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.233:1234") + request := func(method, body, origin, sessionCookie, token string) *httptest.ResponseRecorder { + return assessmentAttemptHTTPRequest(t, harness, method, assessmentSignalNoticePath, body, origin, sessionCookie, token, "", "192.0.2.234:1234") + } + + anonymous := request(http.MethodGet, "", "", "", "") + requireSessionProblem(t, anonymous, http.StatusUnauthorized, "unauthenticated") + + before := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")) + if before.NoticeVersion != current || before.Acknowledged || before.AcknowledgedAt != nil { + t.Fatalf("notice before acknowledgement = %+v", before) + } + + requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, ""), + http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPut, `{"notice_version":1}`, "https://evil.example", cookie.Value, csrf), + http.StatusForbidden, "csrf_check_failed") + if rejected := request(http.MethodPut, `{"notice_version":0}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest { + t.Fatalf("version 0 = %d %s, want 400", rejected.Code, rejected.Body.String()) + } + if rejected := request(http.MethodPut, `{"notice_version":1,"accepted":true}`, sessionHTTPTestOrigin, cookie.Value, csrf); rejected.Code != http.StatusBadRequest { + t.Fatalf("unknown field = %d %s, want 400", rejected.Code, rejected.Body.String()) + } + requireSessionProblem(t, request(http.MethodPut, noticeBody(current+1), sessionHTTPTestOrigin, cookie.Value, csrf), + http.StatusConflict, "state_conflict") + // The previous version is no longer the one the server requires. + requireSessionProblem(t, request(http.MethodPut, noticeBody(current-1), sessionHTTPTestOrigin, cookie.Value, csrf), + http.StatusConflict, "state_conflict") + if untouched := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")); untouched.Acknowledged { + t.Fatalf("a refused request stored an acknowledgement: %+v", untouched) + } + + first := decodeSignalNotice(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, cookie.Value, csrf)) + if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != current { + t.Fatalf("first acknowledgement = %+v", first) + } + time.Sleep(5 * time.Millisecond) + repeat := decodeSignalNotice(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, cookie.Value, csrf)) + if repeat.AcknowledgedAt == nil || *repeat.AcknowledgedAt != *first.AcknowledgedAt { + t.Fatalf("a repeat changed the first acknowledgement time: first %+v, repeat %+v", first, repeat) + } + read := decodeSignalNotice(t, request(http.MethodGet, "", "", cookie.Value, "")) + if !read.Acknowledged || read.AcknowledgedAt == nil || *read.AcknowledgedAt != *first.AcknowledgedAt { + t.Fatalf("read after acknowledgement = %+v, want %+v", read, first) + } + + var rows int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_notice_acknowledgements WHERE user_id = $1", candidate.ID).Scan(&rows); err != nil || rows != 1 { + t.Fatalf("stored acknowledgement rows = %d, error %v, want exactly one", rows, err) + } + // An acknowledgement of version 1 stays stored but does not count for the current version. + if _, err := harness.pool.Exec(ctx, "INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) VALUES ($1, 1, now())", other.ID); err != nil { + t.Fatalf("store a version 1 acknowledgement: %v", err) + } + if foreign := decodeSignalNotice(t, request(http.MethodGet, "", "", otherCookie.Value, "")); foreign.Acknowledged { + t.Fatalf("another account inherited the acknowledgement: %+v", foreign) + } + + requireSessionProblem(t, request(http.MethodGet, "", "", employerCookie.Value, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPut, noticeBody(current), sessionHTTPTestOrigin, employerCookie.Value, employerCSRF), + http.StatusForbidden, "forbidden") + + // The acknowledgement is a record, not a consent: it creates no ledger row. + var consentRows int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1 AND purpose = 'c3'", candidate.ID).Scan(&consentRows); err != nil || consentRows != 0 { + t.Fatalf("C3 rows after acknowledgement = %d, error %v, want none", consentRows, err) + } +} diff --git a/backend/integration_test/assessment_signal_review_http_test.go b/backend/integration_test/assessment_signal_review_http_test.go new file mode 100644 index 0000000..ed2f2bb --- /dev/null +++ b/backend/integration_test/assessment_signal_review_http_test.go @@ -0,0 +1,770 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "log/slog" + "math/rand/v2" + "net/http" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/cli/assessmentreview" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/policy" + "lincodex/backend/internal/worker/jobrunner" +) + +const ( + reviewDuplicateIntegerAnswer = 123456 + reviewAddressOne = "192.0.2.77" + reviewAddressTwo = "198.51.100.88" + reviewAddressThree = "203.0.113.99" +) + +// reviewTestSignalPolicy returns thresholds that make the band deterministic +// for requests that arrive within milliseconds: the median deviation is off +// (it needs more answers than an attempt has), the review level is out of reach +// for the server signals that every fast test run produces, and the duplicate +// levels are low enough for a copied pair to reach them in a population of a +// handful of attempts, where a matched answer carries only a bit or two. +func reviewTestSignalPolicy() domain.AssessmentSignalPolicy { + signals := domain.DemoAssessmentSignalPolicy() + signals.FastAnswersAttention, signals.FastAnswersReview = 3, 1000 + signals.DeviationMinAnswers = 220 + signals.DeviatingAnswersAttention, signals.DeviatingAnswersReview = 1000, 1000 + signals.ParallelAlternationsAttention, signals.ParallelAlternationsReview = 2, 1000 + signals.ExtraNetworksAttention, signals.ExtraNetworksReview = 2, 1000 + signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 4, 6 + return signals +} + +// reviewUnreachableSignalPolicy is a later policy version under which the same +// behavior stays normal. +func reviewUnreachableSignalPolicy() domain.AssessmentSignalPolicy { + signals := reviewTestSignalPolicy() + signals.FastAnswersAttention, signals.FastAnswersReview = 1000, 1000 + signals.ParallelAlternationsAttention, signals.ParallelAlternationsReview = 1000, 1000 + signals.ExtraNetworksAttention, signals.ExtraNetworksReview = 1000, 1000 + signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 4096, 4096 + signals.ClientFocusLossAttentionMS = 24 * 60 * 60 * 1000 + signals.ClientClipboardEventsAttention, signals.ClientFullscreenExitsAttention = 1000, 1000 + return signals +} + +type reviewCandidate struct { + user domain.User + cookies [2]*http.Cookie + csrf [2]string +} + +// newReviewCandidate creates a verified candidate with a questionnaire and the +// C3 consent and logs in once per requested session. +func newReviewCandidate(ctx context.Context, t *testing.T, harness *assessmentAttemptHTTPHarness, email, addressBase string, sessions int) reviewCandidate { + t.Helper() + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + user := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", user.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + candidate := reviewCandidate{user: user} + for session := range sessions { + candidate.cookies[session], candidate.csrf[session] = loginConsentHTTP(t, harness.sessionHTTPHarness, email, fmt.Sprintf("%s.%d:1234", addressBase, 10+session)) + } + if response := assessmentAttemptQuestionnaireRequest(t, harness, candidate.cookies[0].Value, candidate.csrf[0], addressBase+".20:1234"); response.Code != http.StatusOK { + t.Fatalf("save questionnaire = %d %s", response.Code, response.Body.String()) + } + grantCurrentAttemptConsent(t, harness, candidate.cookies[0], candidate.csrf[0], addressBase+".21:1234") + return candidate +} + +func (candidate reviewCandidate) createAttempt(t *testing.T, harness *assessmentAttemptHTTPHarness, key, remoteAddr string) assessmentAnswerHTTPAttempt { + t.Helper() + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr) + var attempt assessmentAnswerHTTPAttempt + if response.Code != http.StatusCreated || json.Unmarshal(response.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create real attempt = %d %s", response.Code, response.Body.String()) + } + return attempt +} + +// answerAll submits every item of the attempt in order. Request i is sent by +// session i modulo the number of sessions and from the matching address. +func (candidate reviewCandidate) answerAll( + ctx context.Context, + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attempt assessmentAnswerHTTPAttempt, + sessions int, + addresses []string, + answerFor func(item assessmentAnswerHTTPItem) json.RawMessage, + keyPrefix string, +) assessmentAnswerHTTPAttempt { + t.Helper() + return candidate.answerFirst(ctx, t, harness, attempt, 0, sessions, addresses, answerFor, keyPrefix) +} + +// answerFirst answers the first count items, or all of them when count is zero. +func (candidate reviewCandidate) answerFirst( + ctx context.Context, + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attempt assessmentAnswerHTTPAttempt, + count, sessions int, + addresses []string, + answerFor func(item assessmentAnswerHTTPItem) json.RawMessage, + keyPrefix string, +) assessmentAnswerHTTPAttempt { + t.Helper() + items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) + if count > 0 { + items = items[:count] + } + version := attempt.Version + last := attempt + for index, item := range items { + body, err := json.Marshal(struct { + ExpectedVersion int64 `json:"expected_version"` + ItemID uuid.UUID `json:"item_id"` + Answer json.RawMessage `json:"answer"` + }{ExpectedVersion: version, ItemID: item.ID, Answer: answerFor(item)}) + if err != nil { + t.Fatalf("marshal answer: %v", err) + } + session := index % sessions + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), sessionHTTPTestOrigin, + candidate.cookies[session].Value, candidate.csrf[session], fmt.Sprintf("%s-%d", keyPrefix, item.Ordinal), + addresses[index%len(addresses)]+":4321") + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &last) != nil { + t.Fatalf("answer item %d = %d %s", item.Ordinal, response.Code, response.Body.String()) + } + version = last.Version + } + return last +} + +func (candidate reviewCandidate) finalize(t *testing.T, harness *assessmentAttemptHTTPHarness, attempt assessmentAnswerHTTPAttempt, key, remoteAddr string) { + t.Helper() + body, err := json.Marshal(map[string]int64{"expected_version": attempt.Version}) + if err != nil { + t.Fatalf("marshal finalization: %v", err) + } + response := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", string(body), sessionHTTPTestOrigin, + candidate.cookies[0].Value, candidate.csrf[0], key, remoteAddr) + if response.Code != http.StatusOK { + t.Fatalf("finalize attempt = %d %s", response.Code, response.Body.String()) + } +} + +func answerFromBody(t *testing.T, version int64, item assessmentAnswerHTTPItem, correct bool) json.RawMessage { + t.Helper() + var envelope struct { + Answer json.RawMessage `json:"answer"` + } + if err := json.Unmarshal(assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct), &envelope); err != nil { + t.Fatalf("decode fixture answer: %v", err) + } + return envelope.Answer +} + +func correctReviewAnswer(t *testing.T) func(assessmentAnswerHTTPItem) json.RawMessage { + return func(item assessmentAnswerHTTPItem) json.RawMessage { return answerFromBody(t, 1, item, true) } +} + +// copiedReviewAnswer gives every candidate the same wrong answer for the same +// family, whatever the seed: a constant number, and for an order the reverse of +// the identity order. +func copiedReviewAnswer(t *testing.T) func(assessmentAnswerHTTPItem) json.RawMessage { + return func(item assessmentAnswerHTTPItem) json.RawMessage { + if item.Variant.AnswerFormat == domain.AnswerFormatInteger { + return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%d}`, reviewDuplicateIntegerAnswer)) + } + tasks := item.Variant.Parameters["tasks"] + elements := make([]string, 0, tasks) + for task := tasks; task >= 1; task-- { + elements = append(elements, fmt.Sprintf("job_%d", task)) + } + answer, err := json.Marshal(map[string]any{"format": "order", "element_ids": elements}) + if err != nil { + t.Fatalf("marshal copied order answer: %v", err) + } + return answer + } +} + +// reviewJobWorker builds a scheduled job worker for the review kind. now is the +// clock of the worker: a clock far ahead also runs the jobs due at the +// deadlines of the attempts. +func reviewJobWorker(t *testing.T, harness *assessmentAttemptHTTPHarness, now func() time.Time, batch int) *jobrunner.Worker { + t.Helper() + settings := jobTestSettings(time.Second) + settings.BatchSize = batch + worker, err := jobrunner.New([]inbound.JobHandler{assessment.NewSignalReviewJob(nil)}, + postgresadapter.NewScheduledJobStore(harness.pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, now) + if err != nil { + t.Fatalf("jobrunner.New() error = %v", err) + } + return worker +} + +// runReviewJobs runs passes until none claims a job and fails on any retry or +// dead job: a review must succeed at once. +func runReviewJobs(ctx context.Context, t *testing.T, worker *jobrunner.Worker) int { + t.Helper() + done := 0 + for range 50 { + result, err := worker.RunDue(ctx) + if err != nil { + t.Fatalf("RunDue() error = %v", err) + } + if result.Retried != 0 || result.Dead != 0 || result.LeaseLost != 0 { + t.Fatalf("review job pass = %+v, want only finished jobs", result) + } + if result.Claimed == 0 { + return done + } + done += result.Done + } + t.Fatal("review jobs did not become idle") + return done +} + +func reviewNow() time.Time { return time.Now().UTC() } + +func reviewFarFuture() time.Time { return time.Now().UTC().Add(200 * time.Hour) } + +type storedReview struct { + Band string + Reasons []string + PolicyVersion int32 + PolicyID uuid.UUID + Fast int32 + Alternations int32 + ExtraNetworks int32 + MatchedInt int32 + Evidence int32 + ClipboardN int32 +} + +func readStoredReview(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness, attemptID uuid.UUID) (storedReview, bool) { + t.Helper() + var review storedReview + rows, err := harness.pool.Query(ctx, ` + SELECT r.band, r.reasons, p.version, r.policy_version_id, r.fast_answers, r.parallel_alternations, r.extra_networks, + r.matched_integer_items, r.duplicate_evidence_bits, r.client_clipboard_events + FROM assessment_attempt_reviews r JOIN policy_versions p ON p.id = r.policy_version_id WHERE r.attempt_id = $1`, attemptID) + if err != nil { + t.Fatalf("read stored review: %v", err) + } + defer rows.Close() + if !rows.Next() { + return storedReview{}, false + } + if err := rows.Scan(&review.Band, &review.Reasons, &review.PolicyVersion, &review.PolicyID, &review.Fast, &review.Alternations, + &review.ExtraNetworks, &review.MatchedInt, &review.Evidence, &review.ClipboardN); err != nil { + t.Fatalf("scan stored review: %v", err) + } + return review, true +} + +func newReviewHarness(ctx context.Context, t *testing.T, signals domain.AssessmentSignalPolicy) *assessmentAttemptHTTPHarness { + t.Helper() + env := bootstrap(t, postgresService, redisService) + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + t.Cleanup(harness.pool.Close) + seedAssessmentAttemptHTTPBankWithSignals(ctx, t, harness.pool, &signals) + return harness +} + +func TestAssessmentSignalReviewOverHTTP(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + oldSignals := reviewTestSignalPolicy() + harness := newReviewHarness(ctx, t, oldSignals) + + fast := newReviewCandidate(ctx, t, harness, "review-fast@example.test", "192.0.2", 2) + control := newReviewCandidate(ctx, t, harness, "review-control@example.test", "192.0.3", 2) + copyOne := newReviewCandidate(ctx, t, harness, "review-copy-one@example.test", "192.0.4", 1) + copyTwo := newReviewCandidate(ctx, t, harness, "review-copy-two@example.test", "192.0.5", 1) + abandoned := newReviewCandidate(ctx, t, harness, "review-abandoned@example.test", "192.0.6", 1) + + // Four attempts start under the first policy version. + fastAttempt := fast.createAttempt(t, harness, "review-fast-create", "192.0.2.30:1234") + copyOneAttempt := copyOne.createAttempt(t, harness, "review-copy-one-create", "192.0.4.30:1234") + copyTwoAttempt := copyTwo.createAttempt(t, harness, "review-copy-two-create", "192.0.5.30:1234") + abandonedAttempt := abandoned.createAttempt(t, harness, "review-abandoned-create", "192.0.6.30:1234") + + // A new policy version is published while they are in progress; an attempt + // that starts afterwards pins the new version. + newSignals := reviewUnreachableSignalPolicy() + newPolicy := integrationPolicy(11) + newPolicy.Assessment.MaxAttemptsPerWindow = 1 + demoAttemptPolicy := domain.DemoProductPolicyV2().Assessment + newPolicy.Assessment.Attempt, newPolicy.Assessment.Training = demoAttemptPolicy.Attempt, demoAttemptPolicy.Training + newPolicy.Assessment.Attempt.MaxSessions, newPolicy.Assessment.Attempt.IdleTimeoutSeconds = 1, 60 + newPolicy.Assessment.Signals = &newSignals + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + newVersion, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: newPolicy, + }) + if err != nil { + t.Fatalf("Publish(new signal policy) error = %v", err) + } + // A category opening is bound to one product policy version, so the + // category is opened again under the new version. + openAssessmentAttemptFixtureCategory(ctx, t, assessment.NewBank(postgresadapter.NewTransactor(harness.pool)), + newVersion.ID(), domain.AssessmentCategory("backend"), domain.SpecializationBackend, domain.GradeJunior) + controlAttempt := control.createAttempt(t, harness, "review-control-create", "192.0.3.30:1234") + + // Very fast answers, two logged-in sessions that take turns, three networks, + // and client paste events: the attempt gets attention. + addresses := []string{reviewAddressOne, reviewAddressTwo, reviewAddressThree} + fastItems := readAssessmentAnswerHTTPItems(t, ctx, harness, fastAttempt.ID) + for index := range 3 { + response := submitAssessmentSignal(t, harness, fastAttempt.ID, fast.cookies[1], fast.csrf[1], fmt.Sprintf("review-paste-%d", index), + assessmentSignalBody(t, fastItems[0].ID, time.Now().UTC().Truncate(time.Microsecond), "paste", int32Pointer(40)), reviewAddressTwo+":4321") + assertSignalReceipt(t, response, http.StatusOK, "accepted", 1) + } + fastDone := fast.answerAll(ctx, t, harness, fastAttempt, 2, addresses, correctReviewAnswer(t), "review-fast-answer") + fast.finalize(t, harness, fastDone, "review-fast-finalize", "192.0.2.31:1234") + + // The same behavior under the later version, from a candidate who started + // after the policy changed. + controlDone := control.answerAll(ctx, t, harness, controlAttempt, 2, addresses, correctReviewAnswer(t), "review-control-answer") + control.finalize(t, harness, controlDone, "review-control-finalize", "192.0.3.31:1234") + + // The reviews are computed by scheduled jobs after the attempts ended, not + // in the transactions of the candidates: nothing exists before the worker + // runs, and the results are already readable. + if _, found := readStoredReview(t, ctx, harness, fastAttempt.ID); found { + t.Fatal("a review exists before the review job ran: it was computed in the candidate's transaction") + } + var pendingJobs int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status = 'pending'`).Scan(&pendingJobs); err != nil || pendingJobs < 4 { + t.Fatalf("pending review jobs = %d (error %v), want a deadline job per answered attempt and an ended job per finalized one", pendingJobs, err) + } + immediate := reviewJobWorker(t, harness, reviewNow, 5) + runReviewJobs(ctx, t, immediate) + + fastReview, found := readStoredReview(t, ctx, harness, fastAttempt.ID) + if !found || fastReview.Band != "attention" { + t.Fatalf("fast attempt review = %+v (found %v), want band attention", fastReview, found) + } + for _, reason := range []string{"fast_answers", "parallel_sessions", "extra_networks", "client_signals"} { + if !slices.Contains(fastReview.Reasons, reason) { + t.Errorf("fast attempt reasons = %v, want %s", fastReview.Reasons, reason) + } + } + if slices.Contains(fastReview.Reasons, "duplicate_answers") || fastReview.ClipboardN != 3 || fastReview.ExtraNetworks != 2 { + t.Errorf("fast attempt reasons = %v, clipboard events = %d, extra networks = %d; want no duplicate flag, three paste events, and two extra networks", + fastReview.Reasons, fastReview.ClipboardN, fastReview.ExtraNetworks) + } + controlReview, found := readStoredReview(t, ctx, harness, controlAttempt.ID) + if !found || controlReview.Band != "normal" || len(controlReview.Reasons) != 0 { + t.Fatalf("attempt under the later policy version review = %+v (found %v), want band normal", controlReview, found) + } + if fastReview.PolicyVersion == newVersion.Version() || controlReview.PolicyVersion != newVersion.Version() || domain.PolicyVersionID(controlReview.PolicyID) != newVersion.ID() { + t.Fatalf("pinned policy versions = %d (old attempt) and %d (new attempt), want the old and then %d", fastReview.PolicyVersion, controlReview.PolicyVersion, newVersion.Version()) + } + if controlReview.Fast == 0 || controlReview.Alternations == 0 || controlReview.ExtraNetworks == 0 { + t.Fatalf("later-version review counted fast=%d alternations=%d extra networks=%d, want the facts kept even when the band is normal", controlReview.Fast, controlReview.Alternations, controlReview.ExtraNetworks) + } + + // The band changes neither the result nor the category data: the same + // correct answers give the same result whatever the band. + fastResult := readReviewCandidateResult(t, harness, fast, fastAttempt.ID) + controlResult := readReviewCandidateResult(t, harness, control, controlAttempt.ID) + for _, field := range []string{"outcome", "basic_score", "limitations", "mode"} { + if stringMustJSON(t, fastResult[field]) != stringMustJSON(t, controlResult[field]) { + t.Errorf("result field %s differs between the attention and the normal attempt: %v vs %v", field, fastResult[field], controlResult[field]) + } + } + if fastResult["outcome"] != "confirmed" { + t.Fatalf("attention attempt outcome = %v, want confirmed", fastResult["outcome"]) + } + var bandColumns int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns + WHERE table_schema = 'public' AND table_name LIKE 'assessment\_%' AND table_name <> 'assessment_attempt_reviews' + AND (column_name LIKE '%band%' OR column_name LIKE '%attention%')`).Scan(&bandColumns); err != nil || bandColumns != 0 { + t.Fatalf("assessment tables other than the review table carry %d band columns (error %v), want none", bandColumns, err) + } + + // Different seeds, identical answers: the first attempt has no duplicate + // flag until the other candidate has answered; then, when the second one + // ends, both are flagged. + oneItems := readAssessmentAnswerHTTPItems(t, ctx, harness, copyOneAttempt.ID) + twoItems := readAssessmentAnswerHTTPItems(t, ctx, harness, copyTwoAttempt.ID) + sameSeeds := 0 + for index := range oneItems { + if oneItems[index].Variant.Seed == twoItems[index].Variant.Seed { + sameSeeds++ + } + } + if sameSeeds == len(oneItems) { + t.Fatal("both copy attempts drew the same seeds; the test needs different seed variants") + } + oneDone := copyOne.answerAll(ctx, t, harness, copyOneAttempt, 1, []string{"192.0.4.40"}, copiedReviewAnswer(t), "review-copy-one-answer") + copyOne.finalize(t, harness, oneDone, "review-copy-one-finalize", "192.0.4.41:1234") + runReviewJobs(ctx, t, immediate) + firstAlone, found := readStoredReview(t, ctx, harness, copyOneAttempt.ID) + if !found || slices.Contains(firstAlone.Reasons, "duplicate_answers") { + t.Fatalf("first copied attempt review before the other answered = %+v (found %v), want no duplicate flag yet", firstAlone, found) + } + + // A third attempt copies the same answers and is abandoned: it never + // finalizes. While it runs, a match with it does not flag it. + abandonedItems := readAssessmentAnswerHTTPItems(t, ctx, harness, abandonedAttempt.ID) + abandoned.answerFirst(ctx, t, harness, abandonedAttempt, len(abandonedItems)-1, 1, []string{"192.0.6.40"}, copiedReviewAnswer(t), "review-abandoned-answer") + twoDone := copyTwo.answerAll(ctx, t, harness, copyTwoAttempt, 1, []string{"192.0.5.40"}, copiedReviewAnswer(t), "review-copy-two-answer") + copyTwo.finalize(t, harness, twoDone, "review-copy-two-finalize", "192.0.5.41:1234") + runReviewJobs(ctx, t, immediate) + for name, attemptID := range map[string]uuid.UUID{"first": copyOneAttempt.ID, "second": copyTwoAttempt.ID} { + review, found := readStoredReview(t, ctx, harness, attemptID) + if !found || review.Band != "review" || !slices.Contains(review.Reasons, "duplicate_answers") || review.MatchedInt == 0 || review.Evidence < 6 { + t.Errorf("%s copied attempt review = %+v (found %v), want band review with a duplicate flag and at least 6 evidence bits", name, review, found) + } + } + if _, found := readStoredReview(t, ctx, harness, abandonedAttempt.ID); found { + t.Fatal("the running attempt was flagged before it ended; it is flagged by its own job when it ends") + } + + // The abandoned attempt ends without being finalized (its state becomes + // terminal) and its job at the deadline reviews it. The clock of the worker + // is moved past the deadline. + terminalizeAttempt(t, ctx, harness.pool, abandonedAttempt.ID) + runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewFarFuture, 5)) + abandonedReview, found := readStoredReview(t, ctx, harness, abandonedAttempt.ID) + if !found || abandonedReview.Band != "review" || !slices.Contains(abandonedReview.Reasons, "duplicate_answers") { + t.Fatalf("abandoned attempt review = %+v (found %v), want it flagged when it ended", abandonedReview, found) + } + var unfinished int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status <> 'done'`).Scan(&unfinished); err != nil || unfinished != 0 { + t.Fatalf("unfinished review jobs = %d (error %v), want none", unfinished, err) + } + for name, attemptID := range map[string]uuid.UUID{"fast": fastAttempt.ID, "later-version": controlAttempt.ID} { + // Two honest attempts can coincide on a low-entropy answer by chance; + // the evidence stays below the attention level and raises no flag. + if review, _ := readStoredReview(t, ctx, harness, attemptID); slices.Contains(review.Reasons, "duplicate_answers") || review.Evidence >= oldSignals.DuplicateAttentionBits { + t.Errorf("%s attempt was flagged as a duplicate: %+v", name, review) + } + } + + // No candidate read carries the band, its reasons, or the facts behind it. + candidates := map[string]struct { + candidate reviewCandidate + attemptID uuid.UUID + }{ + "fast": {fast, fastAttempt.ID}, "later-version": {control, controlAttempt.ID}, + "copy-one": {copyOne, copyOneAttempt.ID}, "copy-two": {copyTwo, copyTwoAttempt.ID}, + } + for name, entry := range candidates { + for _, path := range []string{ + "/api/v1/me/assessment-attempts/" + entry.attemptID.String(), + "/api/v1/me/assessment-attempts/" + entry.attemptID.String() + "/result", + "/api/v1/me/assessment-availability", + } { + response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, path, "", "", entry.candidate.cookies[0].Value, "", "", "203.0.113.200:1234") + if response.Code != http.StatusOK { + t.Fatalf("%s candidate read %s = %d %s", name, path, response.Code, response.Body.String()) + } + lowered := strings.ToLower(response.Body.String()) + for _, forbidden := range []string{`"band"`, "attention", `"reasons"`, "fingerprint", "parallel_sessions", "fast_answers", "duplicate_answers", "client_signals", "review_band", "extra_networks"} { + if strings.Contains(lowered, forbidden) { + t.Errorf("%s candidate read %s contains %q: %s", name, path, forbidden, response.Body.String()) + } + } + } + } + + // The operator command is the only reader, and every read is recorded. + operator, err := assessment.NewReviewOperator(postgresadapter.NewTransactor(harness.pool)) + if err != nil { + t.Fatalf("NewReviewOperator() error = %v", err) + } + var output bytes.Buffer + command := assessmentreview.Command{AttemptID: domain.AssessmentAttemptID(fastAttempt.ID), Actor: "operator:integration"} + if err := assessmentreview.Execute(ctx, command, operator, &output); err != nil { + t.Fatalf("Execute(fast attempt) error = %v", err) + } + for _, want := range []string{"band: attention", fmt.Sprintf("policy_version: %d", fastReview.PolicyVersion), "fast_answers", "parallel_sessions", "extra_networks: 2"} { + if !strings.Contains(output.String(), want) { + t.Errorf("operator output lacks %q:\n%s", want, output.String()) + } + } + missing := assessmentreview.Command{AttemptID: domain.AssessmentAttemptID(uuid.New()), Actor: "operator:integration"} + if err := assessmentreview.Execute(ctx, missing, operator, &output); err == nil { + t.Fatal("Execute(unknown attempt) succeeded") + } + if err := assessmentreview.Execute(ctx, assessmentreview.Command{AttemptID: command.AttemptID, Actor: "alice"}, operator, &output); err == nil { + t.Fatal("Execute(actor without the operator prefix) succeeded") + } + var reads, foundReads, missingReads int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*), count(*) FILTER (WHERE found), count(*) FILTER (WHERE NOT found) FROM assessment_review_reads WHERE actor = 'operator:integration'`). + Scan(&reads, &foundReads, &missingReads); err != nil || reads != 2 || foundReads != 1 || missingReads != 1 { + t.Fatalf("audit records = %d (found %d, missing %d), error %v; want one found read and one miss", reads, foundReads, missingReads, err) + } + + // Facts, reviews, and the audit refuse edits, deletes, and truncation. + for _, statement := range []string{ + "UPDATE assessment_answer_observations SET elapsed_ms = 0", + "DELETE FROM assessment_attempt_origin_marks", + "UPDATE assessment_attempt_reviews SET policy_version_id = '" + newVersion.ID().String() + "' WHERE attempt_id = '" + fastAttempt.ID.String() + "'", + "DELETE FROM assessment_attempt_reviews", + "UPDATE assessment_review_reads SET actor = 'operator:other'", + "DELETE FROM assessment_review_reads", + "TRUNCATE assessment_review_reads", + } { + if _, err := harness.pool.Exec(ctx, statement); err == nil { + t.Errorf("statement %q succeeded", statement) + } + } + + // Origin marks are written when the session or the network changes, not for + // every request: the fast attempt alternates on every answer, the copied + // attempts keep one session and one network. + var oneMarks int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM assessment_attempt_origin_marks WHERE attempt_id = $1`, copyOneAttempt.ID).Scan(&oneMarks); err != nil || oneMarks != 1 { + t.Fatalf("origin marks of an attempt with one session and one network = %d (error %v), want 1", oneMarks, err) + } + + // Logs and stored rows carry no answer text, address, or session token. + privateValues := []string{ + reviewAddressOne, reviewAddressTwo, reviewAddressThree, "192.0.2.", "192.0.3.", "192.0.4.", "192.0.5.", "192.0.6.", + fmt.Sprint(reviewDuplicateIntegerAnswer), fast.cookies[0].Value, fast.cookies[1].Value, fast.csrf[0], + } + logs := harness.logs.String() + for _, private := range privateValues { + if strings.Contains(logs, private) { + t.Errorf("logs contain %q", private) + } + } + for _, table := range []string{"assessment_answer_observations", "assessment_attempt_origin_marks", "assessment_attempt_reviews", "assessment_review_reads", "scheduled_jobs"} { + var document string + if err := harness.pool.QueryRow(ctx, fmt.Sprintf("SELECT COALESCE(string_agg(row_to_json(t)::text, ' '), '') FROM %s t", table)).Scan(&document); err != nil { + t.Fatalf("read %s as text: %v", table, err) + } + for _, private := range privateValues[:8] { + if strings.Contains(document, private) { + t.Errorf("table %s contains %q", table, private) + } + } + if table != "scheduled_jobs" && strings.Contains(document, fmt.Sprint(reviewDuplicateIntegerAnswer)) { + t.Errorf("table %s contains answer text", table) + } + } +} + +// Honest candidates with different seeds, answering correctly or not at random, +// are not flagged as duplicates, while a pair that copies the same answers is. +// A population of a few dozen carries little evidence per matched answer, so +// the thresholds are scaled down for the test; the demo thresholds are +// evaluated against ten thousand rivals by a unit test instead. +func TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag(t *testing.T) { + const honestCandidates = 30 + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + signals := domain.DemoAssessmentSignalPolicy() + signals.DuplicateAttentionBits, signals.DuplicateReviewBits = 32, 44 + harness := newReviewHarness(ctx, t, signals) + + random := rand.New(rand.NewPCG(7, 11)) + honest := make([]assessmentAnswerHTTPAttempt, 0, honestCandidates) + for index := range honestCandidates { + candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-honest-%02d@example.test", index), fmt.Sprintf("10.%d.0", index), 1) + attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-honest-create-%d", index), fmt.Sprintf("10.%d.0.30:1234", index)) + done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("10.%d.0.40", index)}, func(item assessmentAnswerHTTPItem) json.RawMessage { + return answerFromBody(t, 1, item, random.IntN(2) == 0) + }, fmt.Sprintf("review-honest-answer-%d", index)) + candidate.finalize(t, harness, done, fmt.Sprintf("review-honest-finalize-%d", index), fmt.Sprintf("10.%d.0.41:1234", index)) + honest = append(honest, attempt) + } + copies := make([]assessmentAnswerHTTPAttempt, 0, 2) + for index := range 2 { + candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-population-copy-%d@example.test", index), fmt.Sprintf("11.%d.0", index), 1) + attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-population-copy-create-%d", index), fmt.Sprintf("11.%d.0.30:1234", index)) + done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("11.%d.0.40", index)}, copiedReviewAnswer(t), fmt.Sprintf("review-population-copy-answer-%d", index)) + candidate.finalize(t, harness, done, fmt.Sprintf("review-population-copy-finalize-%d", index), fmt.Sprintf("11.%d.0.41:1234", index)) + copies = append(copies, attempt) + } + runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewNow, 10)) + + strongest := int32(0) + for index, attempt := range honest { + review, found := readStoredReview(t, ctx, harness, attempt.ID) + if !found { + t.Fatalf("honest attempt %d has no review", index) + } + strongest = max(strongest, review.Evidence) + if slices.Contains(review.Reasons, "duplicate_answers") { + t.Errorf("honest attempt %d is flagged as a duplicate: %+v", index, review) + } + } + t.Logf("strongest chance evidence among %d honest attempts: %d bits (attention level %d)", honestCandidates, strongest, signals.DuplicateAttentionBits) + for index, attempt := range copies { + review, found := readStoredReview(t, ctx, harness, attempt.ID) + if !found || !slices.Contains(review.Reasons, "duplicate_answers") || review.Evidence < signals.DuplicateAttentionBits { + t.Errorf("copied attempt %d review = %+v (found %v), want a duplicate flag in a population of %d", index, review, found, honestCandidates) + } + } +} + +// Several copied attempts end at the same moment and their jobs run on +// separate workers at once: no job deadlocks or retries, and every attempt is +// flagged. +func TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt(t *testing.T) { + const ( + copiers = 4 + honest = 8 + ) + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + harness := newReviewHarness(ctx, t, reviewTestSignalPolicy()) + + // Honest attempts give the population its denominator: a value that every + // attempt of a tiny population shares carries no evidence at all. + for index := range honest { + candidate := newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-concurrent-honest-%d@example.test", index), fmt.Sprintf("13.%d.0", index), 1) + attempt := candidate.createAttempt(t, harness, fmt.Sprintf("review-concurrent-honest-create-%d", index), fmt.Sprintf("13.%d.0.30:1234", index)) + done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{fmt.Sprintf("13.%d.0.40", index)}, correctReviewAnswer(t), fmt.Sprintf("review-concurrent-honest-answer-%d", index)) + candidate.finalize(t, harness, done, fmt.Sprintf("review-concurrent-honest-finalize-%d", index), fmt.Sprintf("13.%d.0.41:1234", index)) + } + + candidates := make([]reviewCandidate, copiers) + attempts := make([]assessmentAnswerHTTPAttempt, copiers) + done := make([]assessmentAnswerHTTPAttempt, copiers) + for index := range copiers { + candidates[index] = newReviewCandidate(ctx, t, harness, fmt.Sprintf("review-concurrent-%d@example.test", index), fmt.Sprintf("12.%d.0", index), 1) + attempts[index] = candidates[index].createAttempt(t, harness, fmt.Sprintf("review-concurrent-create-%d", index), fmt.Sprintf("12.%d.0.30:1234", index)) + } + for index := range copiers { + done[index] = candidates[index].answerAll(ctx, t, harness, attempts[index], 1, []string{fmt.Sprintf("12.%d.0.40", index)}, copiedReviewAnswer(t), fmt.Sprintf("review-concurrent-answer-%d", index)) + } + var finalizing sync.WaitGroup + for index := range copiers { + finalizing.Add(1) + go func() { + defer finalizing.Done() + candidates[index].finalize(t, harness, done[index], fmt.Sprintf("review-concurrent-finalize-%d", index), fmt.Sprintf("12.%d.0.41:1234", index)) + }() + } + finalizing.Wait() + + var running sync.WaitGroup + start := make(chan struct{}) + for range copiers { + running.Add(1) + worker := reviewJobWorker(t, harness, reviewNow, 1) + go func() { + defer running.Done() + <-start + runReviewJobs(ctx, t, worker) + }() + } + close(start) + running.Wait() + + for index, attempt := range attempts { + review, found := readStoredReview(t, ctx, harness, attempt.ID) + if !found || review.Band != "review" || !slices.Contains(review.Reasons, "duplicate_answers") { + t.Errorf("copied attempt %d review = %+v (found %v), want it flagged", index, review, found) + } + } + var dead int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND (status = 'dead' OR attempts > 1)`).Scan(&dead); err != nil || dead != 0 { + t.Fatalf("review jobs that failed or were retried = %d (error %v), want none", dead, err) + } +} + +func readReviewCandidateResult(t *testing.T, harness *assessmentAttemptHTTPHarness, candidate reviewCandidate, attemptID uuid.UUID) map[string]any { + t.Helper() + response := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String()+"/result", "", "", + candidate.cookies[0].Value, "", "", "203.0.113.201:1234") + var result map[string]any + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &result) != nil { + t.Fatalf("read result = %d %s", response.Code, response.Body.String()) + } + return result +} + +// A review job takes the review lock of every attempt it writes before it reads +// any fact. While another writer holds the lock of an attempt, the job waits +// and does not read or write; after the writer commits, the job reads what was +// committed. This is what keeps a slow job from overwriting a newer review with +// an older evaluation. +func TestAssessmentSignalReviewJobWaitsForTheReviewLock(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + harness := newReviewHarness(ctx, t, reviewTestSignalPolicy()) + candidate := newReviewCandidate(ctx, t, harness, "review-lock@example.test", "14.0.0", 1) + attempt := candidate.createAttempt(t, harness, "review-lock-create", "14.0.0.30:1234") + done := candidate.answerAll(ctx, t, harness, attempt, 1, []string{"14.0.0.40"}, correctReviewAnswer(t), "review-lock-answer") + candidate.finalize(t, harness, done, "review-lock-finalize", "14.0.0.41:1234") + + transactor := postgresadapter.NewTransactor(harness.pool) + locked, release, finished := make(chan struct{}), make(chan struct{}), make(chan error, 1) + go func() { + finished <- transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.AssessmentSignals().LockReview(ctx, domain.AssessmentAttemptID(attempt.ID)); err != nil { + return err + } + close(locked) + <-release + return nil + }) + }() + <-locked + + jobFinished := make(chan struct{}) + go func() { + defer close(jobFinished) + runReviewJobs(ctx, t, reviewJobWorker(t, harness, reviewNow, 1)) + }() + select { + case <-jobFinished: + t.Fatal("the review job finished while another writer held the review lock") + case <-time.After(1500 * time.Millisecond): + } + if _, found := readStoredReview(t, ctx, harness, attempt.ID); found { + t.Fatal("a review was written while the review lock was held elsewhere") + } + var running int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM scheduled_jobs WHERE kind = 'assessment.signal_review' AND status = 'running'`).Scan(&running); err != nil || running != 1 { + t.Fatalf("running review jobs = %d (error %v), want the one waiting for the lock", running, err) + } + close(release) + if err := <-finished; err != nil { + t.Fatalf("lock holder transaction error = %v", err) + } + select { + case <-jobFinished: + case <-time.After(30 * time.Second): + t.Fatal("the review job did not finish after the lock was released") + } + if review, found := readStoredReview(t, ctx, harness, attempt.ID); !found || review.Fast == 0 { + t.Fatalf("review after the lock was released = %+v (found %v), want it computed from the committed facts", review, found) + } +} diff --git a/backend/integration_test/assessment_signal_review_migration_test.go b/backend/integration_test/assessment_signal_review_migration_test.go new file mode 100644 index 0000000..5d3ea92 --- /dev/null +++ b/backend/integration_test/assessment_signal_review_migration_test.go @@ -0,0 +1,102 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +const assessmentSignalReviewMigrationVersion = 33 + +// The audit of operator reads is durable evidence: rolling the schema back +// must not remove it as a side effect. An empty audit does not block the +// rollback, and the derived facts and reviews go with it. +func TestAssessmentSignalReviewMigrationDownRetainsAudit(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + + t.Run("a retained audit row blocks the rollback", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackAboveMigration(ctx, t, migrator, assessmentSignalReviewMigrationVersion) + if _, err := pool.Exec(ctx, `INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at) + VALUES ($1, $2, 'operator:retained', false, $3)`, uuid.New(), uuid.New(), time.Now().UTC()); err != nil { + t.Fatalf("insert retained audit row: %v", err) + } + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a retained audit", err, privacyIntegrityViolation, "assessment_review_reads_retained") + var tableExists bool + var rows int + if err := pool.QueryRow(ctx, `SELECT to_regclass('public.assessment_review_reads') IS NOT NULL`).Scan(&tableExists); err != nil || !tableExists { + t.Fatalf("audit table exists = %v (error %v) after a refused rollback", tableExists, err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM assessment_review_reads`).Scan(&rows); err != nil || rows != 1 { + t.Fatalf("retained audit rows = %d (error %v), want 1", rows, err) + } + if _, err := pool.Exec(ctx, `TRUNCATE assessment_review_reads`); err == nil { + t.Fatal("TRUNCATE of the audit table succeeded") + } + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + for _, status := range statuses { + if status.Version == assessmentSignalReviewMigrationVersion && !status.Applied { + t.Fatal("the migration is not applied after its guarded Down() failed") + } + } + }) + + t.Run("an empty audit lets the rollback remove the tables", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackAboveMigration(ctx, t, migrator, assessmentSignalReviewMigrationVersion) + if _, err := migrator.DownOne(ctx); err != nil { + t.Fatalf("DownOne() with an empty audit error = %v", err) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name IN ( + 'assessment_answer_observations', 'assessment_attempt_origin_marks', 'assessment_attempt_reviews', 'assessment_review_reads')`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("tables left after the rollback = %d (error %v), want none", remaining, err) + } + }) +} + +// rollBackAboveMigration rolls back every applied migration later than version. +func rollBackAboveMigration(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, version int64) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", version, err) + } + later := false + for _, status := range statuses { + if status.Applied && status.Version > version { + later = true + } + } + if !later { + return + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version <= version { + t.Fatalf("DownOne() while preparing migration %d = version %d, error %v", version, result.Version, err) + } + } +} diff --git a/backend/integration_test/assessment_watermark_http_test.go b/backend/integration_test/assessment_watermark_http_test.go new file mode 100644 index 0000000..031b8c4 --- /dev/null +++ b/backend/integration_test/assessment_watermark_http_test.go @@ -0,0 +1,148 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +const assessmentWatermarkHTTPTimeout = 6 * time.Minute + +// TestAssessmentWatermarkOverHTTP checks the mark on the path from the stored +// attempt to the response: a real attempt shows a code and a marked task text +// on every read, a training run shows neither, and the stored variant stays +// unmarked, so the reference answer and the grading never see the mark. +func TestAssessmentWatermarkOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), assessmentWatermarkHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv) + t.Cleanup(harness.pool.Close) + seedAssessmentAttemptHTTPBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "watermark-owner@example.test", passwordHash, true) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.231:1234") + if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.232:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + + training := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, + sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-training", "192.0.2.233:1234") + if training.Code != http.StatusCreated { + t.Fatalf("create training attempt = %d %s", training.Code, training.Body.String()) + } + if watermark, prompt := decodeWatermarkedAttempt(t, training.Body.Bytes()); watermark != "" || hasZeroWidth(prompt) { + t.Fatalf("training attempt carries watermark %q or a marked prompt, want neither", watermark) + } + + grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.237:1234") + create := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-root", "192.0.2.234:1234") + if create.Code != http.StatusCreated { + t.Fatalf("create real attempt = %d %s", create.Code, create.Body.String()) + } + attemptID, _ := assessmentSignalAttemptItem(t, create.Body.Bytes()) + code, prompt := decodeWatermarkedAttempt(t, create.Body.Bytes()) + + want := domainWatermark(t, harness, attemptID) + if code != want.Code().String() { + t.Fatalf("created attempt code = %q, want the code derived on the server %q", code, want.Code()) + } + marks := domain.ExtractAssessmentWatermarkCodes(prompt) + if len(marks) == 0 || marks[0] != want.Code() { + t.Fatalf("invisible mark of the prompt = %v, want %s", marks, want.Code()) + } + + // A later read, and a replay of the creation, give the same code and text. + read := assessmentAttemptHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/assessment-attempts/"+attemptID.String(), "", + "", cookie.Value, "", "", "192.0.2.235:1234") + if read.Code != http.StatusOK { + t.Fatalf("read attempt = %d %s", read.Code, read.Body.String()) + } + if readCode, readPrompt := decodeWatermarkedAttempt(t, read.Body.Bytes()); readCode != code || readPrompt != prompt { + t.Fatalf("read attempt code/prompt = %q/%q, want the created ones %q/%q", readCode, readPrompt, code, prompt) + } + replay := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "watermark-root", "192.0.2.236:1234") + if replayCode, replayPrompt := decodeWatermarkedAttempt(t, replay.Body.Bytes()); replay.Code != http.StatusCreated || replayCode != code || replayPrompt != prompt { + t.Fatalf("replayed creation = %d with code/prompt %q/%q, want the original ones", replay.Code, replayCode, replayPrompt) + } + + // The response carries nothing of the key or the seed. + for _, secret := range []string{"seed", "key"} { + var document map[string]any + if err := json.Unmarshal(read.Body.Bytes(), &document); err != nil { + t.Fatalf("decode attempt: %v", err) + } + if watermark, ok := document["watermark"].(map[string]any); !ok || len(watermark) != 1 { + t.Fatalf("watermark object = %+v, want only a code", document["watermark"]) + } + if _, exposed := document[secret]; exposed { + t.Fatalf("attempt response exposes %q", secret) + } + } + + // The stored variant is the unmarked statement; grading reads it. + var stored string + if err := harness.pool.QueryRow(ctx, `SELECT variant->>'Statement' FROM assessment_attempt_items WHERE attempt_id = $1 ORDER BY ordinal LIMIT 1`, attemptID).Scan(&stored); err != nil { + t.Fatalf("read the stored statement: %v", err) + } + if hasZeroWidth(stored) { + t.Fatal("the stored statement carries an invisible mark, want the mark only on the presented text") + } + if domain.CanonicalAssessmentText(prompt) != domain.CanonicalAssessmentText(stored) { + t.Fatalf("the presented prompt differs in meaning from the stored statement:\n%q\n%q", prompt, stored) + } +} + +func decodeWatermarkedAttempt(t *testing.T, body []byte) (code, prompt string) { + t.Helper() + var attempt struct { + Watermark *struct { + Code string `json:"code"` + } `json:"watermark"` + CurrentItem *struct { + Prompt string `json:"prompt"` + } `json:"current_item"` + } + if err := json.Unmarshal(body, &attempt); err != nil || attempt.CurrentItem == nil { + t.Fatalf("decode attempt: %+v, error %v", attempt, err) + } + if attempt.Watermark != nil { + code = attempt.Watermark.Code + } + return code, attempt.CurrentItem.Prompt +} + +func hasZeroWidth(text string) bool { + return strings.ContainsAny(text, "\u200b\u200c\u200d\u2060") +} + +func domainWatermark(t *testing.T, harness *assessmentAttemptHTTPHarness, attemptID uuid.UUID) domain.AssessmentWatermark { + t.Helper() + watermark, err := domain.NewAssessmentWatermark(harness.keyring.AssessmentWatermarkSeed(attemptID)) + if err != nil { + t.Fatalf("NewAssessmentWatermark() error = %v", err) + } + return watermark +} diff --git a/backend/integration_test/assessment_work_session_http_test.go b/backend/integration_test/assessment_work_session_http_test.go new file mode 100644 index 0000000..662fabf --- /dev/null +++ b/backend/integration_test/assessment_work_session_http_test.go @@ -0,0 +1,267 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" +) + +const ( + workPageOne = "page-one-AAAAAAAAAAAAAAAA" + workPageTwo = "page-two-BBBBBBBBBBBBBBBB" + workAgentOne = "TestBrowser/1.0 (Desktop; Workstation)" + workAgentTwo = "TestBrowser/2.0 (Phone; Handheld)" + workAgentThree = "TestBrowser/3.0 (Tablet; Slate)" +) + +func workSessionRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + method string, + attemptID uuid.UUID, + candidate reviewCandidate, + client, agent string, +) *httptest.ResponseRecorder { + t.Helper() + headers := map[string]string{"User-Agent": agent} + if client != "" { + headers["X-Attempt-Client"] = client + } + return assessmentAttemptHTTPRequestWithHeaders(t, harness, method, + "/api/v1/me/assessment-attempts/"+attemptID.String()+"/work-session", "", sessionHTTPTestOrigin, + candidate.cookies[0].Value, candidate.csrf[0], "", "192.0.2.40:4321", 20*time.Second, headers) +} + +func startSessionRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attempt assessmentAnswerHTTPAttempt, + candidate reviewCandidate, + key, client string, +) *httptest.ResponseRecorder { + t.Helper() + headers := map[string]string{"User-Agent": workAgentOne} + if client != "" { + headers["X-Attempt-Client"] = client + } + return assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/sessions", `{"expected_version":1}`, sessionHTTPTestOrigin, + candidate.cookies[0].Value, candidate.csrf[0], key, "192.0.2.41:4321", 20*time.Second, headers) +} + +func answerRequest( + t *testing.T, + harness *assessmentAttemptHTTPHarness, + attempt assessmentAnswerHTTPAttempt, + body []byte, + candidate reviewCandidate, + key, client string, +) *httptest.ResponseRecorder { + t.Helper() + headers := map[string]string{"User-Agent": workAgentOne} + if client != "" { + headers["X-Attempt-Client"] = client + } + return assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), sessionHTTPTestOrigin, + candidate.cookies[0].Value, candidate.csrf[0], key, "192.0.2.42:4321", 20*time.Second, headers) +} + +// TestAssessmentWorkSessionOverHTTP checks, with PostgreSQL, that one open page +// holds the work session of a real attempt: a second page is refused for the +// session and the answer until the first one releases it or stops renewing, the +// refusal is not stored under an idempotency key, the page and the User-Agent +// are kept only as keyed digests, and the weak capture signals and extra +// User-Agents reach the review band at attention at most. +func TestAssessmentWorkSessionOverHTTP(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout) + defer cancel() + signals := reviewTestSignalPolicy() + signals.ClientScreenshotKeysAttention, signals.ClientDevtoolsAttention = 2, 1 + signals.ExtraAgentsAttention, signals.ExtraAgentsReview = 2, 3 + harness := newReviewHarness(ctx, t, signals) + candidate := newReviewCandidate(ctx, t, harness, "work-session@example.test", "192.0.2", 1) + attempt := candidate.createAttempt(t, harness, "work-session-create", "192.0.2.30:1234") + items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) + answer := assessmentAnswerHTTPBody(t, 1, items[0]) + + // The first page holds the session; the answer carries no page identifier. + held := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentOne) + var lease struct { + HeldUntil time.Time `json:"held_until"` + RenewAfterSeconds int `json:"renew_after_seconds"` + } + if held.Code != http.StatusOK || json.Unmarshal(held.Body.Bytes(), &lease) != nil || lease.RenewAfterSeconds != 15 || + !lease.HeldUntil.After(time.Now()) || held.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("hold = %d %s, want a no-store lease that renews every 15 seconds", held.Code, held.Body.String()) + } + if strings.Contains(held.Body.String(), workPageOne) { + t.Fatalf("the lease %s repeats the page identifier", held.Body.String()) + } + if renewed := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentOne); renewed.Code != http.StatusOK { + t.Fatalf("renewal by the holder = %d %s", renewed.Code, renewed.Body.String()) + } + + // A second page is refused with an explanation-free 409 that changes nothing. + requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo), + http.StatusConflict, "state_conflict") + requireSessionProblem(t, startSessionRequest(t, harness, attempt, candidate, "work-start", workPageTwo), http.StatusConflict, "state_conflict") + requireSessionProblem(t, startSessionRequest(t, harness, attempt, candidate, "work-start-anonymous", ""), http.StatusConflict, "state_conflict") + requireSessionProblem(t, answerRequest(t, harness, attempt, answer, candidate, "work-answer", workPageTwo), http.StatusConflict, "state_conflict") + requireSessionProblem(t, answerRequest(t, harness, attempt, answer, candidate, "work-answer-anonymous", ""), http.StatusConflict, "state_conflict") + if stored := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_items WHERE attempt_id = $1 AND answer IS NOT NULL", attempt.ID); stored != 0 { + t.Fatalf("a refused answer was stored: %d answered items", stored) + } + + // The refusal was not stored under the key: the holder reuses both keys. + if resumed := startSessionRequest(t, harness, attempt, candidate, "work-start", workPageOne); resumed.Code != http.StatusOK { + t.Fatalf("session of the holder under the refused key = %d %s", resumed.Code, resumed.Body.String()) + } + var answered assessmentAnswerHTTPAttempt + first := answerRequest(t, harness, attempt, answer, candidate, "work-answer", workPageOne) + if first.Code != http.StatusOK || json.Unmarshal(first.Body.Bytes(), &answered) != nil || answered.Version != 2 { + t.Fatalf("answer of the holder under the refused key = %d %s", first.Code, first.Body.String()) + } + + // Another page cannot release the session of the holder, and a release + // never says whether it did anything. + if released := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageTwo, workAgentTwo); released.Code != http.StatusNoContent { + t.Fatalf("release by another page = %d %s, want 204", released.Code, released.Body.String()) + } + requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo), + http.StatusConflict, "state_conflict") + + // The first page closes: the second takes over at once, with another browser. + if released := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageOne, workAgentOne); released.Code != http.StatusNoContent { + t.Fatalf("release by the holder = %d %s", released.Code, released.Body.String()) + } + if repeat := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageOne, workAgentOne); repeat.Code != http.StatusNoContent { + t.Fatalf("repeated release = %d %s, want 204", repeat.Code, repeat.Body.String()) + } + if taken := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo); taken.Code != http.StatusOK { + t.Fatalf("hold by the second page after the release = %d %s", taken.Code, taken.Body.String()) + } + second := answerRequest(t, harness, answered, answer, candidate, "work-answer-after", workPageOne) + requireSessionProblem(t, second, http.StatusConflict, "state_conflict") + + // A page that is killed stops renewing: its hold ends by itself. + if _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempt_work_leases + SET acquired_at = acquired_at - INTERVAL '10 minutes', renewed_at = renewed_at - INTERVAL '10 minutes' WHERE attempt_id = $1`, attempt.ID); err != nil { + t.Fatalf("age the lease: %v", err) + } + if retaken := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentThree); retaken.Code != http.StatusOK { + t.Fatalf("hold after the other page stopped renewing = %d %s", retaken.Code, retaken.Body.String()) + } + + // Malformed identifiers, a foreign attempt, and a training run. + for _, bad := range []string{"short", strings.Repeat("a", 65), "has space has space"} { + response := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, bad, workAgentOne) + if response.Code != http.StatusBadRequest { + t.Fatalf("hold with page identifier %q = %d %s, want 400", bad, response.Code, response.Body.String()) + } + } + requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, uuid.New(), candidate, workPageOne, workAgentOne), http.StatusNotFound, "not_found") + missing := assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPut, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/work-session", "", sessionHTTPTestOrigin, + candidate.cookies[0].Value, candidate.csrf[0], "", "192.0.2.43:4321", 20*time.Second, nil) + if missing.Code != http.StatusBadRequest { + t.Fatalf("hold without a page identifier = %d %s, want 400", missing.Code, missing.Body.String()) + } + noCSRF := assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPut, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/work-session", "", sessionHTTPTestOrigin, + candidate.cookies[0].Value, "", "", "192.0.2.43:4321", 20*time.Second, map[string]string{"X-Attempt-Client": workPageOne}) + requireSessionProblem(t, noCSRF, http.StatusForbidden, "csrf_check_failed") + + // Only digests are stored: no column holds a page identifier or a User-Agent. + if rows := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_work_leases WHERE attempt_id = $1", attempt.ID); rows != 1 { + t.Fatalf("lease rows = %d, want one per attempt", rows) + } + for _, table := range []string{"assessment_attempt_work_leases", "assessment_attempt_origin_marks"} { + var dump string + if err := harness.pool.QueryRow(ctx, "SELECT coalesce(string_agg(t::text, ' '), '') FROM "+table+" AS t WHERE attempt_id = $1", attempt.ID).Scan(&dump); err != nil { + t.Fatalf("dump %s: %v", table, err) + } + for _, secret := range []string{workPageOne, workPageTwo, "TestBrowser", "Desktop", "Handheld"} { + if strings.Contains(dump, secret) { + t.Fatalf("%s holds %q, want only keyed digests", table, secret) + } + } + } + for _, agent := range []string{workAgentOne, workAgentTwo, workAgentThree} { + digest := harness.keyring.AssessmentAgentDigest(attempt.ID, agent) + if rows := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_origin_marks WHERE attempt_id = $1 AND agent_digest = $2 AND source = 'work_session'", attempt.ID, digest[:]); rows == 0 { + t.Fatalf("no work session mark carries the digest of %q", agent) + } + } + + // The weak capture signals are stored without a measurement and refused with one. + itemID := items[0].ID + at := time.Now().UTC().Truncate(time.Microsecond) + batch := func(events ...map[string]any) string { + encoded, err := json.Marshal(map[string]any{"events": events}) + if err != nil { + t.Fatalf("marshal capture batch: %v", err) + } + return string(encoded) + } + event := func(kind string, offset time.Duration) map[string]any { + return map[string]any{"kind": kind, "item_instance_id": itemID, "occurred_at": at.Add(offset).Format(time.RFC3339Nano)} + } + accepted := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-batch", + batch(event("screenshot_key", 0), event("screenshot_key", time.Second), event("devtools_open", 2*time.Second)), "192.0.2.44:4321") + assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 3) + withSize := event("screenshot_key", 3*time.Second) + withSize["size_bytes"] = 10 + if rejected := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-size", batch(withSize), "192.0.2.45:4321"); rejected.Code != http.StatusBadRequest { + t.Fatalf("screenshot key with a size = %d %s, want 400", rejected.Code, rejected.Body.String()) + } + if unknown := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-kind", batch(event("screen_recording", 0)), "192.0.2.46:4321"); unknown.Code != http.StatusBadRequest { + t.Fatalf("unknown signal kind = %d %s, want 400", unknown.Code, unknown.Body.String()) + } + if kinds := countRows(t, ctx, harness, "SELECT count(DISTINCT kind) FROM assessment_signal_events WHERE attempt_id = $1 AND kind IN ('screenshot_key', 'devtools_open')", attempt.ID); kinds != 2 { + t.Fatalf("stored capture kinds = %d, want both", kinds) + } + + // The band: three User-Agents, two screenshot keys, and open developer tools + // are only weak signals, so the band is attention and never review. + worker := reviewJobWorker(t, harness, reviewFarFuture, 10) + runReviewJobs(ctx, t, worker) + var band string + var reasons []string + var extraAgents, screenshotKeys, devtoolsOpens int32 + if err := harness.pool.QueryRow(ctx, `SELECT band, reasons, extra_agents, client_screenshot_keys, client_devtools_opens + FROM assessment_attempt_reviews WHERE attempt_id = $1`, attempt.ID).Scan(&band, &reasons, &extraAgents, &screenshotKeys, &devtoolsOpens); err != nil { + t.Fatalf("read the review: %v", err) + } + if band != string(domain.AssessmentReviewBandAttention) || extraAgents != 2 || screenshotKeys != 2 || devtoolsOpens != 1 { + t.Fatalf("review = band %s, %d extra agents, %d screenshot keys, %d detections; want attention, 2, 2, 1", band, extraAgents, screenshotKeys, devtoolsOpens) + } + for _, reason := range []string{string(domain.AssessmentReviewReasonExtraAgents), string(domain.AssessmentReviewReasonClientSignals)} { + found := false + for _, got := range reasons { + found = found || got == reason + } + if !found { + t.Fatalf("review reasons = %v, want %s among them", reasons, reason) + } + } +} + +func countRows(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness, query string, args ...any) int64 { + t.Helper() + var count int64 + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count rows (%s): %v", query, err) + } + return count +} diff --git a/backend/integration_test/bootstrap_retry_test.go b/backend/integration_test/bootstrap_retry_test.go new file mode 100644 index 0000000..568e35f --- /dev/null +++ b/backend/integration_test/bootstrap_retry_test.go @@ -0,0 +1,209 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "testing" + + "github.com/testcontainers/testcontainers-go" +) + +const rootlessPortBindFailureMessage = "Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp4 0.0.0.0:32912: bind: address already in use" + +type retryTestContainer struct { + testcontainers.Container + terminateCalls int + terminateErr error +} + +func (container *retryTestContainer) Terminate(context.Context, ...testcontainers.TerminateOption) error { + container.terminateCalls++ + return container.terminateErr +} + +func TestIsRootlessPortBindFailure(t *testing.T) { + tests := []struct { + name string + err error + want bool + }{ + {name: "rootless host port collision", err: errors.New(rootlessPortBindFailureMessage), want: true}, + {name: "unrelated address collision", err: errors.New("listen tcp4 0.0.0.0:32912: bind: address already in use")}, + {name: "rootless service bind failure", err: errors.New("Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp4 0.0.0.0:32912: bind: permission denied")}, + {name: "rootless IPv6 bind failure", err: errors.New("Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp6 [::]:32912: bind: address already in use")}, + {name: "nil error", err: nil}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := isRootlessPortBindFailure(test.err); got != test.want { + t.Fatalf("isRootlessPortBindFailure(%v) = %t, want %t", test.err, got, test.want) + } + }) + } +} + +func TestStartWithRootlessPortRetryCleansPartialContainer(t *testing.T) { + first := &retryTestContainer{} + second := &retryTestContainer{} + attempts := 0 + container, err := startWithRootlessPortRetry( + context.Background(), + func(context.Context) (testcontainers.Container, error) { + attempts++ + if attempts == 1 { + return first, errors.New(rootlessPortBindFailureMessage) + } + return second, nil + }, + func(ctx context.Context, container testcontainers.Container) error { + return container.Terminate(ctx) + }, + ) + if err != nil { + t.Fatalf("startWithRootlessPortRetry() error = %v", err) + } + if container != second { + t.Fatalf("startWithRootlessPortRetry() container = %v, want second container", container) + } + if attempts != 2 { + t.Fatalf("start attempts = %d, want 2", attempts) + } + if first.terminateCalls != 1 { + t.Fatalf("first container cleanup calls = %d, want 1", first.terminateCalls) + } + if second.terminateCalls != 0 { + t.Fatalf("successful container cleanup calls = %d, want 0", second.terminateCalls) + } +} + +func TestStartWithRootlessPortRetryStopsAtLimit(t *testing.T) { + startErr := errors.New(rootlessPortBindFailureMessage) + attempts := 0 + containers := make([]*retryTestContainer, 0, rootlessPortStartLimit) + container, err := startWithRootlessPortRetry( + context.Background(), + func(context.Context) (testcontainers.Container, error) { + attempts++ + partial := &retryTestContainer{} + containers = append(containers, partial) + return partial, startErr + }, + func(ctx context.Context, container testcontainers.Container) error { + return container.Terminate(ctx) + }, + ) + if err == nil { + t.Fatal("startWithRootlessPortRetry() error = nil, want attempt limit error") + } + if !errors.Is(err, startErr) { + t.Fatalf("startWithRootlessPortRetry() error = %v, want startup cause", err) + } + if container != containers[len(containers)-1] { + t.Fatalf("startWithRootlessPortRetry() container = %v, want final partial container", container) + } + if attempts != rootlessPortStartLimit { + t.Fatalf("start attempts = %d, want %d", attempts, rootlessPortStartLimit) + } + for index, partial := range containers[:len(containers)-1] { + if partial.terminateCalls != 1 { + t.Fatalf("retried container %d cleanup calls = %d, want 1", index, partial.terminateCalls) + } + } + final := containers[len(containers)-1] + if final.terminateCalls != 0 { + t.Fatalf("final container cleanup calls = %d, want caller-owned cleanup", final.terminateCalls) + } + if err := final.Terminate(context.Background()); err != nil { + t.Fatalf("caller cleanup of final container: %v", err) + } + if final.terminateCalls != 1 { + t.Fatalf("final container cleanup calls after caller cleanup = %d, want 1", final.terminateCalls) + } +} + +func TestStartWithRootlessPortRetryPreservesCleanupFailure(t *testing.T) { + startErr := errors.New(rootlessPortBindFailureMessage) + cleanupErr := errors.New("container remove failed") + partial := &retryTestContainer{} + attempts := 0 + container, err := startWithRootlessPortRetry( + context.Background(), + func(context.Context) (testcontainers.Container, error) { + attempts++ + return partial, startErr + }, + func(context.Context, testcontainers.Container) error { + return cleanupErr + }, + ) + if !errors.Is(err, startErr) || !errors.Is(err, cleanupErr) { + t.Fatalf("startWithRootlessPortRetry() error = %v, want start and cleanup causes", err) + } + if container != partial { + t.Fatalf("startWithRootlessPortRetry() container = %v, want partial container for final cleanup", container) + } + if attempts != 1 { + t.Fatalf("start attempts = %d, want 1 after cleanup failure", attempts) + } +} + +func TestStartWithRootlessPortRetryDoesNotRetryStartupFailure(t *testing.T) { + startErr := errors.New("service readiness failed") + partial := &retryTestContainer{} + attempts := 0 + container, err := startWithRootlessPortRetry( + context.Background(), + func(context.Context) (testcontainers.Container, error) { + attempts++ + return partial, startErr + }, + func(ctx context.Context, container testcontainers.Container) error { + return container.Terminate(ctx) + }, + ) + if !errors.Is(err, startErr) { + t.Fatalf("startWithRootlessPortRetry() error = %v, want startup error", err) + } + if container != partial { + t.Fatalf("startWithRootlessPortRetry() container = %v, want partial container for caller cleanup", container) + } + if attempts != 1 { + t.Fatalf("start attempts = %d, want 1", attempts) + } + if partial.terminateCalls != 0 { + t.Fatalf("partial container cleanup calls = %d, want caller-owned cleanup", partial.terminateCalls) + } +} + +func TestStartWithRootlessPortRetryStopsWhenContextIsCanceled(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + startErr := errors.New(rootlessPortBindFailureMessage) + partial := &retryTestContainer{} + attempts := 0 + container, err := startWithRootlessPortRetry( + ctx, + func(context.Context) (testcontainers.Container, error) { + attempts++ + cancel() + return partial, startErr + }, + func(ctx context.Context, container testcontainers.Container) error { + return container.Terminate(ctx) + }, + ) + if !errors.Is(err, context.Canceled) || !errors.Is(err, startErr) { + t.Fatalf("startWithRootlessPortRetry() error = %v, want cancellation and startup cause", err) + } + if container != nil { + t.Fatalf("startWithRootlessPortRetry() container = %v, want nil after cleanup", container) + } + if attempts != 1 { + t.Fatalf("start attempts = %d, want 1", attempts) + } + if partial.terminateCalls != 1 { + t.Fatalf("partial container cleanup calls = %d, want 1", partial.terminateCalls) + } +} diff --git a/backend/integration_test/bootstrap_test.go b/backend/integration_test/bootstrap_test.go index d80e173..d489b5b 100644 --- a/backend/integration_test/bootstrap_test.go +++ b/backend/integration_test/bootstrap_test.go @@ -5,14 +5,23 @@ package integration_test import ( "context" "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" "log/slog" + "regexp" "strings" "testing" "time" "github.com/testcontainers/testcontainers-go" + tcexec "github.com/testcontainers/testcontainers-go/exec" "github.com/testcontainers/testcontainers-go/modules/postgres" "github.com/testcontainers/testcontainers-go/wait" + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kgo" "lincodex/backend/config" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" @@ -25,6 +34,8 @@ const ( postgresImage = "postgres:alpine" redisImage = "redis:alpine" seaweedfsImage = "chrislusf/seaweedfs:latest" + // The same image and KRaft settings as deploy/docker/docker-compose.yml. + kafkaImage = "apache/kafka:latest" postgresDatabase = "health" postgresUser = "health" @@ -38,43 +49,85 @@ const ( cleanupTimeout = 30 * time.Second stopTimeout = 15 * time.Second shutdownTimeout = 5 * time.Second + rootlessPortStartLimit = 3 seaweedfsStartupTimeout = time.Minute storageReadyTimeout = 30 * time.Second readinessInterval = 100 * time.Millisecond readinessTimeout = 5 * time.Second redisTimeout = 300 * time.Millisecond storageTimeout = 2 * time.Second + // A cold JVM start under a busy Docker daemon, for example while other + // suites start containers, has exceeded one minute. + kafkaStartupTimeout = 3 * time.Minute + // startupLogTail bounds the container log printed when a start fails. + startupLogTail = 8 << 10 + kafkaReadyTimeout = 30 * time.Second + + seaweedfsS3Port = "8333/tcp" + seaweedfsFilerPort = "8888/tcp" + seaweedfsMasterPort = "9333/tcp" + seaweedfsVolumePort = "9340/tcp" + + kafkaClientPort = "9092/tcp" + // kafkaListenersFile is written by a post-start hook once the host port is + // mapped; the container entrypoint waits for it before launching the broker. + kafkaListenersFile = "/tmp/advertised-listeners" + // kafkaBrokerListener carries inter-broker traffic on container loopback. + kafkaBrokerListener = "BROKER://127.0.0.1:19092" + kafkaClusterIDSize = 16 ) +var rootlessPortBindFailure = regexp.MustCompile(`Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint [^\s]+ \([^)]*\): error while calling RootlessKit PortManager\.AddPort\(\): listen tcp4 0\.0\.0\.0:[1-9][0-9]{0,4}: bind: address already in use$`) + type service uint8 const ( postgresService service = iota redisService seaweedfsService + kafkaService ) +// seaweedfsEntrypoint mirrors deploy/docker/docker-compose.yml. Each start +// gets random signing keys, so the internal filer and volume HTTP APIs reject +// requests without a JWT minted inside the container. +var seaweedfsEntrypoint = []string{ + "/bin/sh", "-ec", + `for name in WEED_JWT_SIGNING_KEY WEED_JWT_SIGNING_READ_KEY WEED_JWT_FILER_SIGNING_KEY WEED_JWT_FILER_SIGNING_READ_KEY; do + export "$name=$(head -c 32 /dev/urandom | base64)" +done +exec /entrypoint.sh "$@"`, + "seaweedfs", +} + +// defaultServices form the full readiness environment. Kafka is not part of +// readiness, so it starts only for tests that select kafkaService. +var defaultServices = []service{postgresService, redisService, seaweedfsService} + type testEnvironment struct { Config config.Config Postgres *postgresadapter.HealthChecker Redis *redisadapter.Cache SeaweedFS *seaweedfs.Storage + // KafkaAdmin creates and deletes test topics; see kafka_helpers_test.go. + KafkaAdmin *kadm.Client owner *testing.T redisContainer testcontainers.Container seaweedfsContainer testcontainers.Container seaweedfsVolume string + kafkaContainer testcontainers.Container } // bootstrap creates an isolated environment owned by t. Child tests may reuse it. func bootstrap(t *testing.T, services ...service) *testEnvironment { t.Helper() if len(services) == 0 { - services = []service{postgresService, redisService, seaweedfsService} + services = defaultServices } for _, selected := range services { switch selected { - case postgresService, redisService, seaweedfsService: + case postgresService, redisService, seaweedfsService, kafkaService: default: t.Fatalf("unknown integration service: %d", selected) } @@ -83,9 +136,14 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment { "REDIS_PASSWORD": redisPassword, "REDIS_TIMEOUT": redisTimeout.String(), "SEAWEEDFS_ACCESS_KEY": seaweedfsAccessKey, + "IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab", "SEAWEEDFS_SECRET_KEY": seaweedfsSecretKey, "SEAWEEDFS_BUCKET": seaweedfsBucket, "SEAWEEDFS_TIMEOUT": storageTimeout.String(), + // Integration tests send no mail; disabled is the explicit choice. + "EMAIL_PROVIDER": "disabled", + "EMAIL_FROM": "no-reply@example.com", + "APP_PUBLIC_URL": "http://localhost:8080", } settings, err := config.LoadFromEnv(func(key string) (string, bool) { value, ok := fixtures[key] @@ -110,6 +168,8 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment { case seaweedfsService: env.prepareStorageVolume() env.startSeaweedFS(ctx, t) + case kafkaService: + env.startKafka(ctx, t) } started[selected] = true } @@ -126,19 +186,112 @@ func (env *testEnvironment) cleanupContainer(ctx context.Context, container test }) } +// startWithRootlessPortRetry retries only the daemon's rootless host-port bind +// collision. Docker reports this remote failure as text rather than syscall.Errno. +func startWithRootlessPortRetry( + ctx context.Context, + start func(context.Context) (testcontainers.Container, error), + terminate func(context.Context, testcontainers.Container) error, +) (testcontainers.Container, error) { + for attempt := 1; attempt <= rootlessPortStartLimit; attempt++ { + container, err := start(ctx) + if err == nil { + return container, nil + } + + if attempt == rootlessPortStartLimit || !isRootlessPortBindFailure(err) { + return container, fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err) + } + + if container != nil { + if cleanupErr := terminateFailedStart(ctx, container, terminate); cleanupErr != nil { + return container, errors.Join( + fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err), + fmt.Errorf("integration_test.startWithRootlessPortRetry - clean up failed container: %w", cleanupErr), + ) + } + } + if ctxErr := ctx.Err(); ctxErr != nil { + return nil, errors.Join( + fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err), + fmt.Errorf("integration_test.startWithRootlessPortRetry - retry canceled: %w", ctxErr), + ) + } + } + + return nil, errors.New("integration_test.startWithRootlessPortRetry - attempt limit reached") +} + +func terminateFailedStart( + ctx context.Context, + container testcontainers.Container, + terminate func(context.Context, testcontainers.Container) error, +) error { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + return terminate(cleanupCtx, container) +} + +func terminateTestContainer(ctx context.Context, container testcontainers.Container) error { + return testcontainers.TerminateContainer( + container, + testcontainers.StopContext(ctx), + testcontainers.StopTimeout(shutdownTimeout), + ) +} + +func isRootlessPortBindFailure(err error) bool { + return err != nil && rootlessPortBindFailure.MatchString(err.Error()) +} + +// logContainerTail prints the end of a container log after a failed start, +// so a startup timeout shows what the service was doing. +func logContainerTail(ctx context.Context, t *testing.T, container testcontainers.Container, name string) { + t.Helper() + if container == nil { + return + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + logs, err := container.Logs(ctx) + if err != nil { + t.Logf("read %s container log: %v", name, err) + return + } + defer logs.Close() + data, err := io.ReadAll(logs) + if err != nil { + t.Logf("read %s container log: %v", name, err) + } + if len(data) > startupLogTail { + data = data[len(data)-startupLogTail:] + } + t.Logf("%s container log tail:\n%s", name, data) +} + func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) { t.Helper() - container, err := postgres.Run(ctx, postgresImage, - postgres.WithDatabase(postgresDatabase), - postgres.WithUsername(postgresUser), - postgres.WithPassword(postgresPassword), - postgres.BasicWaitStrategies(), - ) + container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) { + postgresContainer, err := postgres.Run(ctx, postgresImage, + postgres.WithDatabase(postgresDatabase), + postgres.WithUsername(postgresUser), + postgres.WithPassword(postgresPassword), + postgres.BasicWaitStrategies(), + ) + if postgresContainer == nil { + return nil, err + } + return postgresContainer, err + }, terminateTestContainer) env.cleanupContainer(ctx, container, "PostgreSQL") if err != nil { t.Fatalf("start PostgreSQL container: %v", err) } - databaseURL, err := container.ConnectionString(ctx, "sslmode=disable") + postgresContainer, ok := container.(*postgres.PostgresContainer) + if !ok { + t.Fatalf("start PostgreSQL container: unexpected container type %T", container) + } + databaseURL, err := postgresContainer.ConnectionString(ctx, "sslmode=disable") if err != nil { t.Fatalf("get PostgreSQL connection string: %v", err) } @@ -152,19 +305,22 @@ func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) { if err := env.Postgres.Check(ctx); err != nil { t.Fatalf("PostgreSQL readiness: %v", err) } + applyMigrations(ctx, t, env.Config.DatabaseURL) } func (env *testEnvironment) startRedis(ctx context.Context, t *testing.T) { t.Helper() - container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ - ContainerRequest: testcontainers.ContainerRequest{ - Image: redisImage, - ExposedPorts: []string{"6379/tcp"}, - Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"}, - WaitingFor: wait.ForLog("Ready to accept connections"), - }, - Started: true, - }) + container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) { + return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: testcontainers.ContainerRequest{ + Image: redisImage, + ExposedPorts: []string{"6379/tcp"}, + Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"}, + WaitingFor: wait.ForLog("Ready to accept connections"), + }, + Started: true, + }) + }, terminateTestContainer) env.cleanupContainer(ctx, container, "Redis") if err != nil { t.Fatalf("start Redis container: %v", err) @@ -219,32 +375,37 @@ func (env *testEnvironment) prepareStorageVolume() { func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) { t.Helper() - container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ - ContainerRequest: testcontainers.ContainerRequest{ - Image: seaweedfsImage, - ExposedPorts: []string{"8333/tcp"}, - Env: map[string]string{ - "AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey, - "AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey, - "S3_BUCKET": env.Config.SeaweedFSBucket, + container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) { + return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: testcontainers.ContainerRequest{ + Image: seaweedfsImage, + // Only the S3 port is used by the adapter. The internal ports are + // published so tests can prove they refuse unauthenticated access. + ExposedPorts: []string{seaweedfsS3Port, seaweedfsFilerPort, seaweedfsMasterPort, seaweedfsVolumePort}, + Entrypoint: seaweedfsEntrypoint, + Env: map[string]string{ + "AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey, + "AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey, + "S3_BUCKET": env.Config.SeaweedFSBucket, + }, + Cmd: []string{ + "mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", "-whiteList=127.0.0.1,@", + "-webdav=false", "-admin.ui=false", "-s3.iam=false", + "-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false", + "-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false", + }, + Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")}, + WaitingFor: wait.ForHTTP("/healthz").WithPort(seaweedfsS3Port).WithStartupTimeout(seaweedfsStartupTimeout), }, - Cmd: []string{ - "mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", - "-webdav=false", "-admin.ui=false", "-s3.iam=false", - "-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false", - "-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false", - }, - Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")}, - WaitingFor: wait.ForHTTP("/healthz").WithPort("8333/tcp").WithStartupTimeout(seaweedfsStartupTimeout), - }, - Started: true, - }) + Started: true, + }) + }, terminateTestContainer) env.cleanupContainer(ctx, container, "SeaweedFS") if err != nil { t.Fatalf("start SeaweedFS container: %v", err) } env.seaweedfsContainer = container - endpoint, err := container.PortEndpoint(ctx, "8333/tcp", "http") + endpoint, err := container.PortEndpoint(ctx, seaweedfsS3Port, "http") if err != nil { t.Fatalf("get SeaweedFS endpoint: %v", err) } @@ -253,6 +414,44 @@ func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) { waitForStorage(ctx, t, env.SeaweedFS) } +// seaweedfsInternalEndpoint returns a host URL for an internal SeaweedFS port. +func (env *testEnvironment) seaweedfsInternalEndpoint(ctx context.Context, t *testing.T, port string) string { + t.Helper() + if env.seaweedfsContainer == nil { + t.Fatal("SeaweedFS was not selected in bootstrap") + } + endpoint, err := env.seaweedfsContainer.PortEndpoint(ctx, port, "http") + if err != nil { + t.Fatalf("get SeaweedFS internal endpoint: %v", err) + } + return endpoint +} + +// assignSeaweedFSVolume asks the master for a file ID from inside the +// container, where the whitelist allows it, and returns the fid with the +// signed volume write token the master hands out. +func (env *testEnvironment) assignSeaweedFSVolume(ctx context.Context, t *testing.T) (string, string) { + t.Helper() + code, output, err := env.seaweedfsContainer.Exec(ctx, []string{ + "sh", "-ec", `curl -sf -D - -o /tmp/assign http://127.0.0.1:9333/dir/assign | sed -n "s/^[Aa]uthorization: //p" | tr -d "\r"; cat /tmp/assign`, + }, tcexec.Multiplexed()) + if err != nil || code != 0 { + t.Fatalf("assign SeaweedFS volume: exit %d, %v", code, err) + } + data, err := io.ReadAll(output) + if err != nil { + t.Fatal(err) + } + token, body, _ := strings.Cut(string(data), "\n") + var assignment struct { + FID string `json:"fid"` + } + if err := json.Unmarshal([]byte(body), &assignment); err != nil || assignment.FID == "" || token == "" { + t.Fatalf("unexpected volume assignment: %v", err) + } + return assignment.FID, token +} + func (env *testEnvironment) newStorage(t *testing.T, settings config.Config) *seaweedfs.Storage { t.Helper() storage, cleanup, err := seaweedfs.NewStorage(settings) @@ -276,6 +475,126 @@ func (env *testEnvironment) recreateSeaweedFS(ctx context.Context, t *testing.T) env.startSeaweedFS(ctx, t) } +func (env *testEnvironment) startKafka(ctx context.Context, t *testing.T) { + t.Helper() + clusterID := make([]byte, kafkaClusterIDSize) + if _, err := rand.Read(clusterID); err != nil { + t.Fatalf("generate Kafka cluster ID: %v", err) + } + container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) { + return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + ContainerRequest: testcontainers.ContainerRequest{ + Image: kafkaImage, + ExposedPorts: []string{kafkaClientPort}, + Env: kafkaEnvironment(base64.RawURLEncoding.EncodeToString(clusterID)), + // The advertised client address contains the host port, which is + // known only after the container starts. + Entrypoint: []string{"sh", "-c", "while [ ! -s " + kafkaListenersFile + " ]; do sleep 0.1; done; " + + "KAFKA_ADVERTISED_LISTENERS=\"$(cat " + kafkaListenersFile + ")\" exec /__cacert_entrypoint.sh /etc/kafka/docker/run"}, + // The image declares these paths as volumes. Compose keeps data in a + // named volume; a test broker needs no persistence, so tmpfs for all + // three leaves no anonymous volumes behind. + Tmpfs: map[string]string{ + "/var/lib/kafka/data": "rw,size=256m,mode=1777", + "/etc/kafka/secrets": "rw,size=1m,mode=0755", + "/mnt/shared/config": "rw,size=1m,mode=0755", + }, + LifecycleHooks: []testcontainers.ContainerLifecycleHooks{{ + PostStarts: []testcontainers.ContainerHook{advertiseKafkaListeners}, + }}, + WaitingFor: wait.ForLog("Kafka Server started").WithStartupTimeout(kafkaStartupTimeout), + }, + Started: true, + }) + }, terminateTestContainer) + env.cleanupContainer(ctx, container, "Kafka") + if err != nil { + logContainerTail(ctx, t, container, "Kafka") + t.Fatalf("start Kafka container: %v", err) + } + env.kafkaContainer = container + address, err := container.PortEndpoint(ctx, kafkaClientPort, "") + if err != nil { + t.Fatalf("get Kafka address: %v", err) + } + env.Config.KafkaBrokers = []string{address} + if err := env.Config.ValidateKafka(); err != nil { + t.Fatalf("invalid Kafka test configuration: %v", err) + } + // kadm serves topic metadata from a cache for up to MetadataMinAge (5s by + // default); assertions about created or deleted topics need current state. + env.KafkaAdmin = kadm.NewClient(env.newKafkaClient(env.owner, kgo.MetadataMinAge(readinessInterval))) + waitForKafka(ctx, t, env.KafkaAdmin) +} + +// kafkaEnvironment mirrors the Compose broker: one KRaft broker and controller, +// explicit topic creation, single replicas, and a bounded heap. +func kafkaEnvironment(clusterID string) map[string]string { + return map[string]string{ + "CLUSTER_ID": clusterID, + "KAFKA_NODE_ID": "1", + "KAFKA_PROCESS_ROLES": "broker,controller", + // Clients reach PLAINTEXT through the mapped host port, which does not + // resolve inside the container. Inter-broker traffic therefore uses a + // loopback listener, like the controller. + "KAFKA_LISTENERS": "PLAINTEXT://0.0.0.0:9092," + kafkaBrokerListener + ",CONTROLLER://127.0.0.1:9093", + "KAFKA_LISTENER_SECURITY_PROTOCOL_MAP": "PLAINTEXT:PLAINTEXT,BROKER:PLAINTEXT,CONTROLLER:PLAINTEXT", + "KAFKA_CONTROLLER_LISTENER_NAMES": "CONTROLLER", + "KAFKA_INTER_BROKER_LISTENER_NAME": "BROKER", + "KAFKA_CONTROLLER_QUORUM_VOTERS": "1@127.0.0.1:9093", + "KAFKA_LOG_DIRS": "/var/lib/kafka/data", + "KAFKA_AUTO_CREATE_TOPICS_ENABLE": "false", + "KAFKA_NUM_PARTITIONS": "1", + "KAFKA_DEFAULT_REPLICATION_FACTOR": "1", + "KAFKA_MIN_INSYNC_REPLICAS": "1", + "KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR": "1", + "KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR": "1", + "KAFKA_TRANSACTION_STATE_LOG_MIN_ISR": "1", + "KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR": "1", + "KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR": "1", + "KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS": "0", + "KAFKA_HEAP_OPTS": "-Xms256m -Xmx512m", + // A non-empty value keeps the image from opening a JMX port. + "KAFKA_JMX_OPTS": "-Djava.rmi.server.hostname=127.0.0.1", + } +} + +func advertiseKafkaListeners(ctx context.Context, container testcontainers.Container) error { + if err := wait.ForMappedPort(kafkaClientPort).WaitUntilReady(ctx, container); err != nil { + return fmt.Errorf("integration_test.advertiseKafkaListeners - wait for mapped port: %w", err) + } + address, err := container.PortEndpoint(ctx, kafkaClientPort, "") + if err != nil { + return fmt.Errorf("integration_test.advertiseKafkaListeners - get client address: %w", err) + } + listeners := "PLAINTEXT://" + address + "," + kafkaBrokerListener + if err := container.CopyToContainer(ctx, []byte(listeners), kafkaListenersFile, 0o644); err != nil { + return fmt.Errorf("integration_test.advertiseKafkaListeners - write listeners: %w", err) + } + return nil +} + +func waitForKafka(ctx context.Context, t *testing.T, admin *kadm.Client) { + t.Helper() + // The startup log line does not prove that the advertised listener is + // reachable from the host through the mapped port. + ctx, cancel := context.WithTimeout(ctx, kafkaReadyTimeout) + defer cancel() + ticker := time.NewTicker(readinessInterval) + defer ticker.Stop() + for { + brokers, err := admin.ListBrokers(ctx) + if err == nil && len(brokers) > 0 { + return + } + select { + case <-ctx.Done(): + t.Fatalf("wait for Kafka broker metadata: brokers %v, error %v", brokers, err) + case <-ticker.C: + } + } +} + func waitForStorage(ctx context.Context, t *testing.T, storage *seaweedfs.Storage) { t.Helper() // The S3 listener starts before mini finishes provisioning configured buckets. diff --git a/backend/integration_test/candidate_card_access_migration_test.go b/backend/integration_test/candidate_card_access_migration_test.go new file mode 100644 index 0000000..209f2b5 --- /dev/null +++ b/backend/integration_test/candidate_card_access_migration_test.go @@ -0,0 +1,117 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" +) + +const candidateCardAccessMigrationVersion = 30 + +func TestCandidateCardAccessMigrationDownRetainsHistory(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + // The organization is created while the latest schema is in place: its creation + // needs the holdings table, which the rollback below removes. + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ + ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now, + } + candidate := identity.createUser(t, "candidate@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) + organizationFixture := organizationFixture{ + ctx: ctx, pool: pool, identity: identity, + transactor: postgresadapter.NewTransactor(pool), now: now, + } + owner := organizationFixture.employer(t, "owner@example.com") + organization := organizationFixture.create(t, owner, organizationFixture.completeProfile(t, "Example Company"), now) + rollBackToCandidateCardAccessVersion(ctx, t, migrator) + + if _, err := pool.Exec(ctx, `INSERT INTO candidate_card_access_events ( + id, candidate_id, organization_id, actor_id, kind, field_codes, occurred_at + ) VALUES ($1, $2, $3, $4, 'card_viewed', ARRAY['stack']::text[], $5)`, + uuid.New(), candidate.ID, organization.ID(), owner.ID, now); err != nil { + t.Fatalf("insert retained card access event: %v", err) + } + + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with retained card access history", err, privacyIntegrityViolation, "candidate_card_access_events_retained") + + var tableExists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass('public.candidate_card_access_events') IS NOT NULL`).Scan(&tableExists); err != nil { + t.Fatalf("check access history table after refused rollback: %v", err) + } + if !tableExists { + t.Fatal("candidate_card_access_events was removed despite retained history") + } + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1`, candidate.ID).Scan(&count); err != nil { + t.Fatalf("read retained access event after refused rollback: %v", err) + } + if count != 1 { + t.Fatalf("retained access event count = %d, want 1", count) + } + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() after refused rollback: %v", err) + } + version30Applied := false + for _, status := range statuses { + if status.Version == candidateCardAccessMigrationVersion { + version30Applied = status.Applied + break + } + } + if !version30Applied { + t.Fatal("migration 30 is not applied after its guarded Down() failed") + } +} + +func rollBackToCandidateCardAccessVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err) + } + version30Applied := false + laterMigrationApplied := false + for _, status := range statuses { + if !status.Applied { + continue + } + if status.Version == candidateCardAccessMigrationVersion { + version30Applied = true + } + if status.Version > candidateCardAccessMigrationVersion { + laterMigrationApplied = true + } + } + if !version30Applied { + t.Fatalf("migration %d is not applied", candidateCardAccessMigrationVersion) + } + if !laterMigrationApplied { + return + } + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() while preparing migration %d: %v", candidateCardAccessMigrationVersion, err) + } + if result.Version <= candidateCardAccessMigrationVersion { + t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, candidateCardAccessMigrationVersion) + } + } +} diff --git a/backend/integration_test/candidate_privacy_http_test.go b/backend/integration_test/candidate_privacy_http_test.go new file mode 100644 index 0000000..10bffc6 --- /dev/null +++ b/backend/integration_test/candidate_privacy_http_test.go @@ -0,0 +1,549 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" +) + +const candidatePrivacyHTTPTestTimeout = 5 * time.Minute + +type candidatePrivacyHTTPHarness struct { + *sessionHTTPHarness + key domain.CandidateViewPseudonymKey + settings *candidateprivacy.Service +} + +func TestCandidatePrivacyHTTPReadsRecheckCurrentVisibility(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyHTTPTestTimeout) + defer cancel() + harness := newCandidatePrivacyHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, usersDependentTables...) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), harness.clock.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + + now := harness.clock.Now() + identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + organizations := organizationFixture{ + ctx: ctx, pool: harness.pool, identity: identity, + transactor: postgresadapter.NewTransactor(harness.pool), now: now, + } + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, + organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, now: now} + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-target@example.test", passwordHash, true) + candidates := []domain.User{candidate} + for index := 1; index < 5; index++ { + other := privacy.candidate(t, fmt.Sprintf("privacy-cohort-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, privacy, other) + candidates = append(candidates, other) + } + for _, member := range candidates { + input := domain.CandidateProfileInput{Stack: privacyCohortConfirmedItems("go")} + if member.ID == candidate.ID { + input.FullName = confirmedDecision("Private Candidate Name") + input.Email = confirmedDecision("private-card-email@example.test") + } + profiles.save(t, member.ID, input, 0) + if member.ID == candidate.ID { + continue + } + c2 := privacy.grant(t, member.ID, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, member.ID, c2.ID(), 0, domain.CardFieldStack) + } + + employer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now) + organizationA := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization A"), now) + organizationB := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization B"), now) + organizationC := organizations.create(t, employer, organizations.completeProfile(t, "Privacy organization C"), now) + inactiveOrganization := organizations.create(t, employer, organizations.completeProfile(t, "Privacy inactive organization"), now) + organizations.setMembershipState(t, inactiveOrganization.ID(), employer.ID, domain.MembershipStateLeft) + foreignEmployer := createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, "privacy-foreign-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreignOrganization := organizations.create(t, foreignEmployer, organizations.completeProfile(t, "Privacy foreign organization"), now) + + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.170:1234") + employerCookie, _ := loginConsentHTTP(t, harness.sessionHTTPHarness, employer.Email.Address(), "192.0.2.171:1234") + initialSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.172:1234") + if initialSettings.Code != http.StatusOK || initialSettings.Header().Get("Cache-Control") != "no-store" || + !strings.Contains(initialSettings.Body.String(), `"state":"closed"`) || !strings.Contains(initialSettings.Body.String(), `"closed_reason":"never_published"`) { + t.Fatalf("initial privacy settings = %d Cache-Control=%q %s", initialSettings.Code, initialSettings.Header().Get("Cache-Control"), initialSettings.Body.String()) + } + c2Grant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF, + "c2", privacyC2Version, sessionHTTPTestOrigin) + if c2Grant.Code != http.StatusOK { + t.Fatalf("C2 grant = %d %s", c2Grant.Code, c2Grant.Body.String()) + } + publication := harness.request(t, http.MethodPut, "/api/v1/me/privacy/publication", + `{"expected_version":0,"state":"published","fields":["stack"]}`, + sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.173:1234") + if publication.Code != http.StatusOK || publication.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("publication = %d Cache-Control=%q %s", publication.Code, publication.Header().Get("Cache-Control"), publication.Body.String()) + } + + aliasA, err := harness.key.ForOrganization(organizationA.ID(), candidate.ID) + if err != nil { + t.Fatalf("ForOrganization(A) error = %v", err) + } + aliasB, err := harness.key.ForOrganization(organizationB.ID(), candidate.ID) + if err != nil { + t.Fatalf("ForOrganization(B) error = %v", err) + } + if aliasA == aliasB { + t.Fatalf("organization-scoped aliases unexpectedly match: %q", aliasA) + } + assertCandidatePrivacyContactPortFixture(t, ctx, harness, employer.ID, organizationA.ID(), candidate.ID, aliasA) + unknownOrganization := uuid.New() + for _, test := range []struct { + name string + organizationID uuid.UUID + wantStatus int + wantCode string + useCandidate bool + }{ + {name: "active employer membership", organizationID: organizationA.ID(), wantStatus: http.StatusOK}, + {name: "candidate account", organizationID: organizationA.ID(), wantStatus: http.StatusForbidden, wantCode: "forbidden", useCandidate: true}, + {name: "inactive membership", organizationID: inactiveOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"}, + {name: "foreign membership", organizationID: foreignOrganization.ID(), wantStatus: http.StatusNotFound, wantCode: "not_found"}, + {name: "unknown organization", organizationID: unknownOrganization, wantStatus: http.StatusNotFound, wantCode: "not_found"}, + } { + t.Run(test.name, func(t *testing.T) { + cookie := employerCookie.Value + if test.useCandidate { + cookie = candidateCookie.Value + } + response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, test.organizationID, aliasA, cookie) + if response.Code != test.wantStatus { + t.Fatalf("card response = %d %s, want %d", response.Code, response.Body.String(), test.wantStatus) + } + if test.wantCode != "" { + requireSessionProblem(t, response, test.wantStatus, test.wantCode) + } + if test.wantStatus == http.StatusOK { + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("card Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + var card struct { + Pseudonym string `json:"pseudonym"` + Stack []string `json:"stack"` + } + if err := json.Unmarshal(response.Body.Bytes(), &card); err != nil || card.Pseudonym != aliasA || len(card.Stack) != 1 || card.Stack[0] != "go" { + t.Fatalf("anonymous card = %+v, %v; body=%s", card, err, response.Body.String()) + } + for _, privateValue := range []string{candidate.ID.String(), candidate.Email.Address(), "Private Candidate Name", "private-card-email@example.test"} { + if strings.Contains(response.Body.String(), privateValue) { + t.Errorf("anonymous card contains private value %q", privateValue) + } + } + } + }) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationA.ID(), []string{"stack"}) + + preview := harness.request(t, http.MethodGet, "/api/v1/me/privacy/preview", "", "", candidateCookie.Value, "", "192.0.2.174:1234") + if preview.Code != http.StatusOK || preview.Header().Get("Cache-Control") != "no-store" || + strings.Contains(preview.Body.String(), aliasA) || strings.Contains(preview.Body.String(), candidate.ID.String()) { + t.Fatalf("private preview = %d Cache-Control=%q %s", preview.Code, preview.Header().Get("Cache-Control"), preview.Body.String()) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + + hideA := harness.request(t, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(), + "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.175:1234") + if hideA.Code != http.StatusOK || hideA.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("hide organization A = %d Cache-Control=%q %s", hideA.Code, hideA.Header().Get("Cache-Control"), hideA.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusNotFound { + t.Fatalf("card after hiding A = %d %s, want generic 404", response.Code, response.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusOK { + t.Fatalf("card for B after hiding A = %d %s, want independent organization access", response.Code, response.Body.String()) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1) + assertPrivacyCardAccessFields(t, ctx, harness.pool, candidate.ID, organizationB.ID(), []string{"stack"}) + unhideA := harness.request(t, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+organizationA.ID().String(), + "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.176:1234") + if unhideA.Code != http.StatusNoContent { + t.Fatalf("unhide organization A = %d %s, want 204", unhideA.Code, unhideA.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationA.ID(), aliasA, employerCookie.Value); response.Code != http.StatusOK { + t.Fatalf("card after unhiding A = %d %s, want restored visibility while C2 is active", response.Code, response.Body.String()) + } + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 1) + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationA.ID(), 2) + directHidden, err := harness.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: candidate.ID, Limit: 20}) + if err != nil || len(directHidden.Items) != 0 || directHidden.HasMore { + t.Fatalf("direct hidden organization list = %+v, %v; want an empty page after unhide", directHidden, err) + } + hiddenList := harness.request(t, http.MethodGet, "/api/v1/me/privacy/hidden-organizations", "", "", candidateCookie.Value, "", "192.0.2.177:1234") + if hiddenList.Code != http.StatusOK || !strings.Contains(hiddenList.Body.String(), `"items":[]`) || hiddenList.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("hidden organizations after unhide = %d Cache-Control=%q %s", hiddenList.Code, hiddenList.Header().Get("Cache-Control"), hiddenList.Body.String()) + } + privacyHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/history", "", "", candidateCookie.Value, "", "192.0.2.178:1234") + if privacyHistory.Code != http.StatusOK || !strings.Contains(privacyHistory.Body.String(), "publication_opened") || + !strings.Contains(privacyHistory.Body.String(), "organization_hidden") || !strings.Contains(privacyHistory.Body.String(), "organization_unhidden") { + t.Fatalf("privacy history = %d %s", privacyHistory.Code, privacyHistory.Body.String()) + } + accessHistory := harness.request(t, http.MethodGet, "/api/v1/me/privacy/access-history", "", "", candidateCookie.Value, "", "192.0.2.179:1234") + if accessHistory.Code != http.StatusOK || accessHistory.Header().Get("Cache-Control") != "no-store" || !strings.Contains(accessHistory.Body.String(), "Privacy organization A") || !strings.Contains(accessHistory.Body.String(), "Privacy organization B") { + t.Fatalf("card access history = %d Cache-Control=%q %s", accessHistory.Code, accessHistory.Header().Get("Cache-Control"), accessHistory.Body.String()) + } + + // Hold the candidate account row so the employer read reaches and waits on + // its FOR SHARE visibility lock. Commit the competing hide only after the + // lock wait is observed; a visibility recheck must reject the stale cohort. + lockTx, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin visibility race transaction: %v", err) + } + defer func() { _ = lockTx.Rollback(context.Background()) }() + if _, err := lockTx.Exec(ctx, `SELECT id FROM users WHERE id = $1 FOR UPDATE`, candidate.ID); err != nil { + t.Fatalf("lock candidate row for visibility race: %v", err) + } + aliasC, err := harness.key.ForOrganization(organizationC.ID(), candidate.ID) + if err != nil { + t.Fatalf("ForOrganization(C) error = %v", err) + } + raceResult := make(chan *httptest.ResponseRecorder, 1) + go func() { + raceResult <- candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationC.ID(), aliasC, employerCookie.Value) + }() + monitor := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-monitor") + if waitEvent, waiting := waitForLockWait(ctx, monitor, "candidate-privacy-http"); !waiting || waitEvent == "" { + t.Fatalf("card read did not wait for candidate visibility lock, wait event %q", waitEvent) + } + if _, err := lockTx.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, organizationC.ID(), now.Add(time.Second)); err != nil { + t.Fatalf("commit concurrent candidate hide fixture: %v", err) + } + if err := lockTx.Commit(ctx); err != nil { + t.Fatalf("commit visibility race transaction: %v", err) + } + raceResponse := <-raceResult + if raceResponse.Code != http.StatusNotFound { + t.Fatalf("card read that waited behind a hide = %d %s, want generic 404", raceResponse.Code, raceResponse.Body.String()) + } + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0) + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationC.ID(), 0) + + revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.180:1234") + if revoke.Code != http.StatusNoContent { + t.Fatalf("C2 revoke = %d %s, want 204", revoke.Code, revoke.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound { + t.Fatalf("card after C2 revoke = %d %s, want generic 404", response.Code, response.Body.String()) + } + regrant := consentGrantHTTP(t, harness.sessionHTTPHarness, candidateCookie, candidateCSRF, + "c2", privacyC2Version, sessionHTTPTestOrigin) + if regrant.Code != http.StatusOK { + t.Fatalf("C2 regrant = %d %s", regrant.Code, regrant.Body.String()) + } + if response := candidatePrivacyCardRequest(t, harness.sessionHTTPHarness, organizationB.ID(), aliasB, employerCookie.Value); response.Code != http.StatusNotFound { + t.Fatalf("card after C2 regrant without republication = %d %s, want generic 404", response.Code, response.Body.String()) + } + closedSettings := harness.request(t, http.MethodGet, "/api/v1/me/privacy", "", "", candidateCookie.Value, "", "192.0.2.181:1234") + if closedSettings.Code != http.StatusOK || !strings.Contains(closedSettings.Body.String(), `"state":"closed"`) { + t.Fatalf("settings after C2 revoke and regrant = %d %s, want closed publication", closedSettings.Code, closedSettings.Body.String()) + } + assertPrivacyCardAccessCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1) + assertPrivacyCardViewQuotaCount(t, ctx, harness.pool, candidate.ID, organizationB.ID(), 1) +} + +func newCandidatePrivacyHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *candidatePrivacyHTTPHarness { + t.Helper() + pool := env.newPoolWithApplicationName(ctx, t, "candidate-privacy-http") + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + consentStore := postgresadapter.NewConsentStore(pool) + consentQueries := consent.NewQueryService(consentStore, clock.Now) + consentCommands := consent.NewService(transactor, clock.Now) + privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + quota := companyquota.NewService(clock.Now) + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now) + privacyViews, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + consentHandler := v1.NewConsentHandler(consentQueries, consentCommands) + privacyHandler := v1.NewPrivacyHandler(privacyViews, privacySettings, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &candidatePrivacyHTTPHarness{ + sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, + key: key, settings: privacySettings, + } +} + +func candidatePrivacyCardRequest(t *testing.T, harness *sessionHTTPHarness, organizationID uuid.UUID, handle, cookie string) *httptest.ResponseRecorder { + t.Helper() + path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", organizationID, handle) + return harness.request(t, http.MethodGet, path, "", "", cookie, "", "192.0.2.190:1234") +} + +func assertPrivacyCardAccessCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed'`, candidateID, organizationID).Scan(&count); err != nil { + t.Fatalf("count candidate card access events: %v", err) + } + if count != want { + t.Fatalf("card access event count = %d, want %d", count, want) + } +} + +func assertPrivacyCardViewQuotaCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, candidateID, organizationID).Scan(&count); err != nil { + t.Fatalf("count card-view quota usage: %v", err) + } + if count != want { + t.Fatalf("card-view quota usage count = %d, want %d", count, want) + } +} + +func assertPrivacyCardAccessFields(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, want []string) { + t.Helper() + var fields []string + if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id LIMIT 1`, candidateID, organizationID).Scan(&fields); err != nil { + t.Fatalf("read card-view audit fields: %v", err) + } + if len(fields) != len(want) { + t.Fatalf("card-view audit fields = %v, want %v", fields, want) + } + for index := range fields { + if fields[index] != want[index] { + t.Fatalf("card-view audit fields = %v, want %v", fields, want) + } + } +} + +type candidatePrivacyContactGrantState uint8 + +const ( + candidatePrivacyContactGrantAbsent candidatePrivacyContactGrantState = iota + candidatePrivacyContactGrantActive + candidatePrivacyContactGrantRevoked +) + +type candidatePrivacyContactGrantFixture struct { + state candidatePrivacyContactGrantState + workflowAccepted bool + organizationID uuid.UUID + candidateID uuid.UUID + fields domain.ContactFieldSet +} + +func (fixture *candidatePrivacyContactGrantFixture) currentFields(organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) { + if fixture == nil || fixture.state != candidatePrivacyContactGrantActive || + fixture.organizationID != organizationID || fixture.candidateID != candidateID { + return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed + } + // Workflow acceptance is deliberately not used as authorization evidence. + return fixture.fields, nil +} + +type candidatePrivacyContactTransactor struct { + inner outbound.Transactor + fixture *candidatePrivacyContactGrantFixture +} + +func (transactor candidatePrivacyContactTransactor) WithinTransaction( + ctx context.Context, + fn func(context.Context, outbound.UnitOfWork) error, +) error { + return transactor.inner.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + view := candidatePrivacyContactView{ + PrivacyViewRepository: unit.PrivacyView(), + fixture: transactor.fixture, + } + return fn(ctx, candidatePrivacyContactUnit{UnitOfWork: unit, view: view}) + }) +} + +type candidatePrivacyContactUnit struct { + outbound.UnitOfWork + + view outbound.PrivacyViewRepository +} + +func (unit candidatePrivacyContactUnit) PrivacyView() outbound.PrivacyViewRepository { + return unit.view +} + +type candidatePrivacyContactView struct { + outbound.PrivacyViewRepository + fixture *candidatePrivacyContactGrantFixture +} + +func (view candidatePrivacyContactView) CurrentFields(_ context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error) { + return view.fixture.currentFields(organizationID, candidateID) +} + +func assertCandidatePrivacyContactPortFixture( + t *testing.T, + ctx context.Context, + harness *candidatePrivacyHTTPHarness, + actorID, organizationID, candidateID uuid.UUID, + handle string, +) { + t.Helper() + fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail, domain.ContactFieldPhone) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + fixture := &candidatePrivacyContactGrantFixture{ + organizationID: organizationID, + candidateID: candidateID, + fields: fields, + } + transactor := candidatePrivacyContactTransactor{ + inner: postgresadapter.NewTransactor(harness.pool), + fixture: fixture, + } + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(harness.pool), harness.key, harness.clock.Now) + quota := companyquota.NewService(harness.clock.Now) + service, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: projector, PseudonymKey: harness.key, Clock: harness.clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + + for _, test := range []struct { + name string + state candidatePrivacyContactGrantState + want bool + }{ + {name: "active grant returns selected fields", state: candidatePrivacyContactGrantActive, want: true}, + {name: "workflow acceptance without a grant stays closed", state: candidatePrivacyContactGrantAbsent}, + {name: "revoked grant stays closed", state: candidatePrivacyContactGrantRevoked}, + } { + t.Run(test.name, func(t *testing.T) { + fixture.state = test.state + fixture.workflowAccepted = true + got, err := service.CurrentContactFields(ctx, actorID, organizationID, handle) + if test.want { + if err != nil { + t.Fatalf("CurrentContactFields() error = %v", err) + } + gotFields := got.Fields() + wantFields := fields.Fields() + if len(gotFields) != len(wantFields) { + t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields) + } + for index := range wantFields { + if gotFields[index] != wantFields[index] { + t.Fatalf("CurrentContactFields() = %v, want exactly %v", gotFields, wantFields) + } + } + } else if !errors.Is(err, outbound.ErrContactAccessClosed) { + t.Fatalf("CurrentContactFields() error = %v, want closed contact access", err) + } + assertPrivacyContactAudit(t, ctx, harness.pool, candidateID, organizationID, test.want) + }) + } +} + +func assertPrivacyContactAudit(t *testing.T, ctx context.Context, pool *pgxpool.Pool, candidateID, organizationID uuid.UUID, checkFields bool) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&count); err != nil { + t.Fatalf("count contact-read audit events: %v", err) + } + if count != 1 { + t.Fatalf("contact-read audit count = %d, want one successful read and no records for denied reads", count) + } + if !checkFields { + return + } + var fields []string + if err := pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidateID, organizationID).Scan(&fields); err != nil { + t.Fatalf("read contact-read audit fields: %v", err) + } + if len(fields) != 2 || fields[0] != "email" || fields[1] != "phone" { + t.Fatalf("contact-read audit fields = %v, want [email phone]", fields) + } +} diff --git a/backend/integration_test/candidate_privacy_test.go b/backend/integration_test/candidate_privacy_test.go new file mode 100644 index 0000000..6abe38e --- /dev/null +++ b/backend/integration_test/candidate_privacy_test.go @@ -0,0 +1,1128 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/policy" +) + +const ( + candidatePrivacyTestTimeout = 3 * time.Minute + privacyForeignKeyViolation = "23503" + privacyCheckViolation = "23514" + privacyIntegrityViolation = "23000" + privacyC2Version = "c2-2026-10-01" + privacyC1Version = "c1-2026-10-01" +) + +var ( + candidatePublicationsTable = pgx.Identifier{"candidate_publications"} + candidateSearchStatusesTable = pgx.Identifier{"candidate_search_statuses"} + candidateHiddenOrganizationsTable = pgx.Identifier{"candidate_hidden_organizations"} + candidatePrivacyEventsTable = pgx.Identifier{"candidate_privacy_events"} + candidateCardAccessEventsTable = pgx.Identifier{"candidate_card_access_events"} + // candidatePrivacyTables reference users, organizations, and the consent + // ledger, so every TRUNCATE of those names them through + // usersDependentTables. + candidatePrivacyTables = []pgx.Identifier{ + candidateCardAccessEventsTable, candidatePrivacyEventsTable, candidateHiddenOrganizationsTable, + candidateSearchStatusesTable, candidatePublicationsTable, + } +) + +// candidatePrivacyFixture works on the bootstrap database. The tables are +// truncated between subtests; the product policy is immutable and shared. +type candidatePrivacyFixture struct { + ctx context.Context + pool *pgxpool.Pool + queries *sqlc.Queries + identity identityFixture + organizations organizationFixture + ledger *postgresadapter.ConsentStore + policy domain.PolicyVersion + now time.Time +} + +func TestCandidatePrivacyStorage(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + policies := postgresadapter.NewPolicyStore(pool) + if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + latest, err := policies.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil { + t.Fatalf("GetLatest(product) error = %v", err) + } + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity, + organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now}, + ledger: postgresadapter.NewConsentStore(pool), + policy: latest, + now: now, + } + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("a new profile has no published state and nothing hidden", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + // Saving a full profile, as the profile contract does, opens nothing. + profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now} + profiles.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna Sokolova")}, 0) + + for _, table := range candidatePrivacyTables { + assertRowCount(ctx, t, pool, table, 0) + } + if _, err := fixture.queries.ReadCandidatePublication(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("ReadCandidatePublication() error = %v, want no row: the profile is closed by default", err) + } + if _, err := fixture.queries.ReadCandidateSearchStatus(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("ReadCandidateSearchStatus() error = %v, want no row", err) + } + if total, err := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(candidate.ID)); err != nil || total != 0 { + t.Fatalf("CountCandidateHiddenOrganizations() = %d, %v, want 0", total, err) + } + // The domain reads the absence as a closed profile at version 0. + closed, err := domain.NewPublication(candidate.ID) + if err != nil || closed.State() != domain.PublicationClosed || closed.ClosedReason() != domain.ClosedNeverPublished || closed.Version() != 0 { + t.Fatalf("NewPublication() = %v %v v%d, %v, want closed and never published", closed.State(), closed.ClosedReason(), closed.Version(), err) + } + }) + + t.Run("publication refers to the C2 record and a revocation closes it", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack, domain.CardFieldCategories) + if published.State() != domain.PublicationPublished || published.Version() != 1 || published.ConsentRecordID() != c2.ID() || + !published.Fields().Equal(domainFields(t, domain.CardFieldCategories, domain.CardFieldStack)) { + t.Fatalf("stored publication = %v v%d, want published at version 1 under the C2 record", published.State(), published.Version()) + } + + // Revoking C2 in the ledger closes the card with no write to the setting. + before := fixture.rawPublication(t, candidate.ID) + fixture.revokeC2(t, candidate.ID, now) + if after := fixture.rawPublication(t, candidate.ID); after != before { + t.Fatalf("revoking C2 changed the stored publication: %+v -> %+v", before, after) + } + revoked := fixture.loadPublication(t, candidate.ID) + if revoked.State() != domain.PublicationClosed || revoked.ClosedReason() != domain.ClosedConsentRevoked || !revoked.Fields().IsEmpty() { + t.Fatalf("after the revocation = %v (%v), want closed because the consent was revoked", revoked.State(), revoked.ClosedReason()) + } + + // A new C2 grant publishes nothing by itself. + newC2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Minute)) + if again := fixture.loadPublication(t, candidate.ID); again.State() != domain.PublicationClosed { + t.Fatalf("a new C2 grant left the card %v, want closed until the candidate publishes again", again.State()) + } + reopened := fixture.publish(t, candidate.ID, newC2.ID(), 1, domain.CardFieldStack) + if reopened.State() != domain.PublicationPublished || reopened.ConsentRecordID() != newC2.ID() || reopened.Version() != 2 { + t.Fatalf("republished = %v v%d under %s, want the new record at version 2", reopened.State(), reopened.Version(), reopened.ConsentRecordID()) + } + + // Closing is an explicit change that keeps the evidence. + change, err := reopened.Apply(mustPublicationRequest(t, domain.PublicationClosed), 2, uuid.Nil, now.Add(time.Hour)) + if err != nil || !change.Changed { + t.Fatalf("Apply(close) = %+v, %v", change, err) + } + fixture.storePublication(t, change.Publication, 2) + closed := fixture.loadPublication(t, candidate.ID) + if closed.State() != domain.PublicationClosed || closed.ClosedReason() != domain.ClosedByCandidate || closed.Version() != 3 || !closed.PublishedAt().Equal(reopened.PublishedAt()) { + t.Fatalf("closed = %v (%v) v%d, want closed by the candidate with the last publication time", closed.State(), closed.ClosedReason(), closed.Version()) + } + }) + + t.Run("the publication row refuses a consent that is not the account's C2 and fields that are not card fields", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + other := fixture.candidate(t, "other@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + otherC2 := fixture.grant(t, other.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + c1 := fixture.grant(t, candidate.ID, domain.ConsentPurposePersonalData, privacyC1Version, now.Add(-time.Hour)) + + insert := func(user uuid.UUID, consent uuid.UUID, state string, fields []string, closedAt pgtype.Timestamptz) error { + _, err := fixture.queries.InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(user), State: state, Fields: fields, ConsentRecordID: uuidParam(consent), + PublishedAt: timeParam(now), ClosedAt: closedAt, At: timeParam(now), + }) + return err + } + for _, test := range []struct { + name string + err error + sqlstate string + }{ + {"another account's C2", insert(candidate.ID, otherC2.ID(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation}, + {"a C1 record", insert(candidate.ID, c1.ID(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation}, + {"an unknown record", insert(candidate.ID, uuid.New(), "published", []string{"stack"}, pgtype.Timestamptz{}), privacyForeignKeyViolation}, + {"the full name as a field", insert(candidate.ID, c2.ID(), "published", []string{"full_name"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"a phone as a field", insert(candidate.ID, c2.ID(), "published", []string{"phone"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"fields out of order", insert(candidate.ID, c2.ID(), "published", []string{"stack", "categories"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"a repeated field", insert(candidate.ID, c2.ID(), "published", []string{"stack", "stack"}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"published without a field", insert(candidate.ID, c2.ID(), "published", []string{}, pgtype.Timestamptz{}), privacyCheckViolation}, + {"closed with a field", insert(candidate.ID, c2.ID(), "closed", []string{"stack"}, timeParam(now)), privacyCheckViolation}, + {"an unknown state", insert(candidate.ID, c2.ID(), "draft", []string{"stack"}, pgtype.Timestamptz{}), privacyCheckViolation}, + } { + if code := sqlState(test.err); code != test.sqlstate { + t.Errorf("%s: SQLSTATE = %q (%v), want %s", test.name, code, test.err, test.sqlstate) + } + } + assertRowCount(ctx, t, pool, candidatePublicationsTable, 0) + + // A C2 record that a publication refers to cannot be deleted. + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, c2.ID()) + if code := sqlState(err); code == "" { + t.Fatal("a C2 record behind a publication was deleted") + } + }) + + t.Run("a stale version updates nothing and a first publication is created once", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + + _, err := fixture.queries.InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(candidate.ID), State: "published", Fields: []string{"stack"}, ConsentRecordID: uuidParam(c2.ID()), + PublishedAt: timeParam(now), At: timeParam(now), + }) + if !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a second first-publication error = %v, want no row", err) + } + _, err = fixture.queries.UpdateCandidatePublication(ctx, sqlc.UpdateCandidatePublicationParams{ + UserID: uuidParam(candidate.ID), ExpectedVersion: 0, State: "published", Fields: []string{"location"}, ConsentRecordID: uuidParam(c2.ID()), + PublishedAt: timeParam(now), At: timeParam(now), + }) + if !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("an update over a stale version error = %v, want no row", err) + } + if got := fixture.loadPublication(t, candidate.ID); got.Version() != 1 || !got.Fields().Equal(domainFields(t, domain.CardFieldStack)) { + t.Fatal("a stale update changed the publication") + } + }) + + t.Run("looking stores its confirmation under the policy version and lapses without a write", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + status := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 0, now) + if status.StoredValue() != domain.SearchStatusLooking || !status.ConfirmedAt().Equal(now) || status.PolicyVersionID() != fixture.policy.ID() || status.Version() != 1 { + t.Fatalf("stored status = %v confirmed %v under %v, want looking confirmed now under the policy version", status.StoredValue(), status.ConfirmedAt(), status.PolicyVersionID()) + } + // The interval is the one of the policy version, 30 days in the demo. + interval := fixture.policy.Policy().SearchStatus.SearchingConfirmationInterval.Duration() + if !status.LapsesAt().Equal(now.Add(interval)) { + t.Fatalf("lapses at %v, want %v", status.LapsesAt(), now.Add(interval)) + } + + before := fixture.rawSearchStatus(t, candidate.ID) + lapsedAt := status.LapsesAt().Add(time.Second) + if loaded := fixture.loadSearchStatus(t, candidate.ID); loaded.Effective(lapsedAt) != domain.SearchStatusNotLooking || !loaded.Lapsed(lapsedAt) || loaded.Effective(now) != domain.SearchStatusLooking { + t.Fatal("the stored status does not lapse at its lapse time") + } + if fixture.rawSearchStatus(t, candidate.ID) != before { + t.Fatal("a lapse changed the stored status: it must be computed, never written") + } + + // Confirming again after the lapse is an explicit change over the current version. + confirmed := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 1, lapsedAt) + if confirmed.Version() != 2 || !confirmed.ConfirmedAt().Equal(lapsedAt) || confirmed.Effective(lapsedAt) != domain.SearchStatusLooking { + t.Fatalf("confirmed again = v%d %v, want version 2 and looking", confirmed.Version(), confirmed.Effective(lapsedAt)) + } + cleared := fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusNotLooking, 2, lapsedAt.Add(time.Hour)) + if cleared.StoredValue() != domain.SearchStatusNotLooking || !cleared.ConfirmedAt().IsZero() || cleared.Version() != 3 { + t.Fatalf("cleared = %v v%d, want not_looking carrying no confirmation", cleared.StoredValue(), cleared.Version()) + } + }) + + t.Run("the status row refuses a looking without its confirmation and has no link to a consent", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + insert := func(status string, confirmed, lapses pgtype.Timestamptz, policyID pgtype.UUID) error { + _, err := fixture.queries.InsertCandidateSearchStatus(ctx, sqlc.InsertCandidateSearchStatusParams{ + UserID: uuidParam(candidate.ID), Status: status, ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(now), + }) + return err + } + policyID := uuidParam(fixture.policy.ID().UUID()) + for _, test := range []struct { + name string + err error + sqlstate string + }{ + {"looking without a confirmation", insert("looking", pgtype.Timestamptz{}, pgtype.Timestamptz{}, policyID), privacyCheckViolation}, + {"looking without a lapse time", insert("looking", timeParam(now), pgtype.Timestamptz{}, policyID), privacyCheckViolation}, + {"looking that lapses before it is confirmed", insert("looking", timeParam(now), timeParam(now.Add(-time.Hour)), policyID), privacyCheckViolation}, + {"looking without a policy version", insert("looking", timeParam(now), timeParam(now.Add(time.Hour)), pgtype.UUID{}), privacyCheckViolation}, + {"looking under an unknown policy version", insert("looking", timeParam(now), timeParam(now.Add(time.Hour)), uuidParam(uuid.New())), privacyForeignKeyViolation}, + {"not looking with a confirmation", insert("not_looking", timeParam(now), timeParam(now.Add(time.Hour)), policyID), privacyCheckViolation}, + {"an unknown status", insert("open", pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{}), privacyCheckViolation}, + } { + if code := sqlState(test.err); code != test.sqlstate { + t.Errorf("%s: SQLSTATE = %q (%v), want %s", test.name, code, test.err, test.sqlstate) + } + } + + // The status is not a consent: its only foreign key is the account; the policy version is checked by a trigger. + rows, err := pool.Query(ctx, ` + SELECT confrelid::regclass::text FROM pg_constraint + WHERE conrelid = 'candidate_search_statuses'::regclass AND contype = 'f' ORDER BY 1`) + if err != nil { + t.Fatalf("list the foreign keys: %v", err) + } + references, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil || !slices.Equal(references, []string{"users"}) { + t.Fatalf("candidate_search_statuses references %v (%v), want only users (the policy version is checked by a trigger)", references, err) + } + var consentColumns int + if err := pool.QueryRow(ctx, ` + SELECT count(*) FROM information_schema.columns + WHERE table_name IN ('candidate_search_statuses', 'candidate_hidden_organizations') AND column_name LIKE '%consent%'`).Scan(&consentColumns); err != nil || consentColumns != 0 { + t.Fatalf("the status and hiding tables have %d consent columns (%v), want none", consentColumns, err) + } + }) + + t.Run("the search status leaves C2, the publication, and the hidden organizations as they were", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + organization := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldCategories, domain.CardFieldLocation) + fixture.hide(t, candidate.ID, organization.ID(), now) + + consentBefore := fixture.rawConsentRecords(t, candidate.ID) + publicationBefore := fixture.rawPublication(t, candidate.ID) + hiddenBefore := fixture.rawHidden(t, candidate.ID) + + fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 0, now.Add(time.Minute)) + fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusLooking, 1, now.Add(2*time.Minute)) + fixture.setSearchStatus(t, candidate.ID, domain.SearchStatusNotLooking, 2, now.Add(3*time.Minute)) + + if fixture.rawConsentRecords(t, candidate.ID) != consentBefore { + t.Error("updating the search status changed the consent ledger") + } + if fixture.rawPublication(t, candidate.ID) != publicationBefore { + t.Error("updating the search status changed the publication") + } + if fixture.rawHidden(t, candidate.ID) != hiddenBefore { + t.Error("updating the search status changed the hidden organizations") + } + if published := fixture.loadPublication(t, candidate.ID); published.State() != domain.PublicationPublished || published.Version() != 1 { + t.Fatal("updating the search status changed the effective publication") + } + }) + + t.Run("a hidden organization belongs to the candidate and is unique", func(t *testing.T) { + reset(t) + first := fixture.candidate(t, "first@example.com") + second := fixture.candidate(t, "second@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + globex := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Globex Synthetic LLC"), now) + + fixture.hide(t, first.ID, acme.ID(), now) + // The pair is unique: a second insert returns no row and keeps the original time. + _, err := fixture.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{ + UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID()), At: timeParam(now.Add(time.Hour)), + }) + if !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("hiding the same organization twice error = %v, want no row", err) + } + record, err := fixture.queries.GetCandidateHiddenOrganization(ctx, sqlc.GetCandidateHiddenOrganizationParams{UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID())}) + if err != nil || !record.HiddenAt.Time.Equal(now) || record.OrganizationName != "Acme Synthetic LLC" { + t.Fatalf("GetCandidateHiddenOrganization() = %+v, %v, want the original record with the current name", record, err) + } + if _, err := fixture.pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, first.ID, acme.ID(), now); sqlState(err) != organizationUniqueViolation { + t.Fatalf("a raw duplicate hiding SQLSTATE = %q, want %s", sqlState(err), organizationUniqueViolation) + } + + // Another candidate hides the same organization independently and reads only their own records. + fixture.hide(t, second.ID, acme.ID(), now.Add(time.Minute)) + fixture.hide(t, second.ID, globex.ID(), now.Add(2*time.Minute)) + if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(first.ID)); total != 1 { + t.Fatalf("the first candidate has %d hidden organizations, want 1", total) + } + page, err := fixture.queries.ListCandidateHiddenOrganizations(ctx, sqlc.ListCandidateHiddenOrganizationsParams{UserID: uuidParam(second.ID), RowLimit: 1}) + if err != nil || len(page) != 1 || uuid.UUID(page[0].OrganizationID.Bytes) != globex.ID() { + t.Fatalf("first page = %+v, %v, want the newest hiding", page, err) + } + next, err := fixture.queries.ListCandidateHiddenOrganizations(ctx, sqlc.ListCandidateHiddenOrganizationsParams{ + UserID: uuidParam(second.ID), RowLimit: 10, AfterHiddenAt: page[0].HiddenAt, AfterOrganizationID: page[0].OrganizationID, + }) + if err != nil || len(next) != 1 || uuid.UUID(next[0].OrganizationID.Bytes) != acme.ID() { + t.Fatalf("next page = %+v, %v, want the older hiding", next, err) + } + + // An unknown organization is refused by the reference, and the caller + // answers it as it answers an organization the candidate cannot see. + _, err = fixture.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{ + UserID: uuidParam(first.ID), OrganizationID: uuidParam(uuid.New()), At: timeParam(now), + }) + if sqlState(err) != privacyForeignKeyViolation { + t.Fatalf("hiding an unknown organization SQLSTATE = %q, want %s", sqlState(err), privacyForeignKeyViolation) + } + // Lifting a hiding deletes it once; a repeat deletes nothing. + lift := sqlc.DeleteCandidateHiddenOrganizationParams{UserID: uuidParam(first.ID), OrganizationID: uuidParam(acme.ID())} + if deleted, err := fixture.queries.DeleteCandidateHiddenOrganization(ctx, lift); err != nil || uuid.UUID(deleted.Bytes) != acme.ID() { + t.Fatalf("DeleteCandidateHiddenOrganization() = %v, %v, want the organization", deleted, err) + } + if _, err := fixture.queries.DeleteCandidateHiddenOrganization(ctx, lift); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a repeated delete error = %v, want no row", err) + } + if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(second.ID)); total != 2 { + t.Fatalf("lifting the first candidate's hiding left the second with %d records, want 2", total) + } + // The organization cannot be deleted while a candidate hides it. + if _, err := pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, globex.ID()); sqlState(err) == "" { + t.Fatal("an organization that a candidate hides was deleted") + } + }) + + t.Run("a candidate hides at most 1000 organizations", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + limit := domain.MaxHiddenOrganizations + // The organizations are created in bulk with one owner; the deferred + // owner trigger sees the membership of the same transaction. + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil { + t.Fatalf("create holding: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id) + SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3) + FROM generate_series(1, $2::int) AS n`, now, limit+1, employer.ID); err != nil { + t.Fatalf("create organizations: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + SELECT gen_random_uuid(), id, $1, 'owner', 'active', $2, $2 FROM organizations WHERE name LIKE 'Bulk %'`, employer.ID, now); err != nil { + t.Fatalf("create memberships: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + SELECT $1, id, $2 FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id LIMIT $3`, candidate.ID, now, limit); err != nil { + t.Fatalf("hide %d organizations: %v", limit, err) + } + _, err = tx.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + SELECT $1, id, $2 FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id DESC LIMIT 1 OFFSET 0`, candidate.ID, now) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != privacyCheckViolation || pgError.ConstraintName != "candidate_hidden_organizations_limit" { + t.Fatalf("hiding organization %d error = %v, want SQLSTATE %s on candidate_hidden_organizations_limit", limit+1, err, privacyCheckViolation) + } + }) + + t.Run("the history is append-only and keeps the published fields with their times", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + organization := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + change, err := published.Apply(mustPublicationRequest(t, domain.PublicationPublished, domain.CardFieldStack, domain.CardFieldLocation), 1, c2.ID(), now.Add(time.Minute)) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + fixture.storePublication(t, change.Publication, 1) + fixture.recordPublicationEvent(t, change, now.Add(time.Minute)) + fixture.hide(t, candidate.ID, organization.ID(), now.Add(2*time.Minute)) + + page, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{UserID: uuidParam(candidate.ID), RowLimit: 10}) + if err != nil || len(page) != 3 { + t.Fatalf("ListCandidatePrivacyEvents() = %d rows, %v, want 3", len(page), err) + } + kinds := []string{page[0].Kind, page[1].Kind, page[2].Kind} + if !slices.Equal(kinds, []string{"organization_hidden", "publication_changed", "publication_opened"}) { + t.Fatalf("event kinds = %v, want newest first", kinds) + } + if !slices.Equal(page[1].Fields, []string{"location", "stack"}) || uuid.UUID(page[1].ConsentRecordID.Bytes) != c2.ID() || !page[1].OccurredAt.Time.Equal(now.Add(time.Minute)) { + t.Fatalf("the change event = %v under %v at %v, want the published fields, the C2 record, and the time", page[1].Fields, page[1].ConsentRecordID, page[1].OccurredAt.Time) + } + if page[0].OrganizationName.String != "Acme Synthetic LLC" { + t.Fatalf("the hiding event names %q, want the current name resolved at read time", page[0].OrganizationName.String) + } + var nameColumns int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'candidate_privacy_events' AND column_name LIKE '%name%'`).Scan(&nameColumns); err != nil || nameColumns != 0 { + t.Fatalf("the history table has %d name columns (%v), want none: it stores identifiers only", nameColumns, err) + } + // Pagination continues after the position of the last row. + next, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{ + UserID: uuidParam(candidate.ID), RowLimit: 10, AfterOccurredAt: page[0].OccurredAt, AfterID: page[0].ID, + }) + if err != nil || len(next) != 2 { + t.Fatalf("next page = %d rows, %v, want 2", len(next), err) + } + + // Append-only: no UPDATE, and no DELETE once the account is confirmed. + for _, test := range []struct{ statement, constraint string }{ + {`UPDATE candidate_privacy_events SET occurred_at = occurred_at + interval '1 hour'`, "candidate_privacy_events_immutable"}, + } { + _, err := pool.Exec(ctx, test.statement) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != privacyIntegrityViolation || pgError.ConstraintName != test.constraint { + t.Fatalf("%q error = %v, want SQLSTATE %s on %s", test.statement, err, privacyIntegrityViolation, test.constraint) + } + } + if _, err := pool.Exec(ctx, `UPDATE users SET email_verified_at = $2 WHERE id = $1`, candidate.ID, now); err != nil { + t.Fatalf("confirm the account: %v", err) + } + _, err = pool.Exec(ctx, `DELETE FROM candidate_privacy_events`) + var retained *pgconn.PgError + if !errors.As(err, &retained) || retained.Code != privacyIntegrityViolation || retained.ConstraintName != "candidate_privacy_events_retained" { + t.Fatalf("deleting the history of a confirmed account error = %v, want SQLSTATE %s on candidate_privacy_events_retained", err, privacyIntegrityViolation) + } + for name, params := range map[string]sqlc.InsertCandidatePrivacyEventParams{ + "a publication without fields": {Kind: "publication_opened", Fields: []string{}, ConsentRecordID: uuidParam(c2.ID())}, + "a publication without a consent": {Kind: "publication_changed", Fields: []string{"stack"}}, + "a hiding without an organization": {Kind: "organization_hidden"}, + "a status event with an organization": {Kind: "search_status_cleared", OrganizationID: uuidParam(organization.ID())}, + "a closing with a field": {Kind: "publication_closed", Fields: []string{"stack"}}, + "an unknown kind": {Kind: "published"}, + } { + params.ID, params.UserID, params.OccurredAt = uuidParam(uuid.Must(uuid.NewV7())), uuidParam(candidate.ID), timeParam(now) + if err := fixture.queries.InsertCandidatePrivacyEvent(ctx, params); sqlState(err) != privacyCheckViolation { + t.Errorf("%s: SQLSTATE = %q (%v), want %s", name, sqlState(err), err, privacyCheckViolation) + } + } + // An account with history cannot be deleted until a procedure handles it. + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); sqlState(err) == "" { + t.Fatal("an account with consent and privacy history was deleted") + } + }) + + t.Run("closing over a revoked C2 stores the closing and records it", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + fixture.revokeC2(t, candidate.ID, now) + + revoked := fixture.loadPublication(t, candidate.ID) + change, err := revoked.Apply(mustPublicationRequest(t, domain.PublicationClosed), 1, uuid.Nil, now.Add(time.Minute)) + if err != nil || !change.Changed || change.Event != domain.PrivacyEventPublicationClosed { + t.Fatalf("Apply(close over a revoked C2) = %+v, %v, want a recorded closing", change, err) + } + fixture.storePublication(t, change.Publication, 1) + fixture.recordPublicationEvent(t, change, now.Add(time.Minute)) + + var stored string + if err := pool.QueryRow(ctx, `SELECT state FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&stored); err != nil || stored != "closed" { + t.Fatalf("stored state = %q (%v), want the row normalized to closed", stored, err) + } + if closed := fixture.loadPublication(t, candidate.ID); closed.ClosedReason() != domain.ClosedByCandidate || closed.Version() != 2 { + t.Fatalf("closed = %v v%d, want closed by the candidate at version 2", closed.ClosedReason(), closed.Version()) + } + page, err := fixture.queries.ListCandidatePrivacyEvents(ctx, sqlc.ListCandidatePrivacyEventsParams{UserID: uuidParam(candidate.ID), RowLimit: 10}) + if err != nil || len(page) != 2 || page[0].Kind != "publication_closed" { + t.Fatalf("history = %d rows, %v, want the closing newest", len(page), err) + } + }) + + t.Run("an organization reads a publication only through the effective view and not when hidden", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + globex := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Globex Synthetic LLC"), now) + read := func(organization uuid.UUID) error { + _, err := fixture.queries.ReadPublicationVisibleToOrganization(ctx, sqlc.ReadPublicationVisibleToOrganizationParams{ + UserID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization), + }) + return err + } + if err := read(acme.ID()); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a closed-by-default profile read error = %v, want no row", err) + } + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + published := fixture.publish(t, candidate.ID, c2.ID(), 0, domain.CardFieldStack) + if err := read(acme.ID()); err != nil { + t.Fatalf("a published profile read error = %v, want a row", err) + } + fixture.hide(t, candidate.ID, acme.ID(), now) + if err := read(acme.ID()); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a hidden organization read error = %v, want no row, the same as an unpublished profile", err) + } + if err := read(globex.ID()); err != nil { + t.Fatalf("another organization read error = %v, want a row", err) + } + fixture.revokeC2(t, candidate.ID, now) + if err := read(globex.ID()); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("a read after the C2 revocation error = %v, want no row", err) + } + _ = published + }) + + t.Run("a revocation racing with a publication either refuses it or closes the card after it", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + c2 := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + // The publication holds the share lock: the revocation waits for it. + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + locked, err := fixture.queries.WithTx(tx).LockCurrentC2Record(ctx, uuidParam(candidate.ID)) + if err != nil || uuid.UUID(locked.Bytes) != c2.ID() { + t.Fatalf("LockCurrentC2Record() = %v, %v, want the C2 record", locked, err) + } + if _, err := fixture.queries.WithTx(tx).InsertCandidatePublication(ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(candidate.ID), State: "published", Fields: []string{"stack"}, ConsentRecordID: locked, PublishedAt: timeParam(now), At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidatePublication() error = %v", err) + } + revoked := make(chan error, 1) + go func() { + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: candidate.ID, Purpose: domain.ConsentPurposePublication, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: now.Add(time.Minute), + }) + if err == nil { + _, err = fixture.ledger.ConsentLedger().Revoke(ctx, revocation) + } + revoked <- err + }() + select { + case err := <-revoked: + t.Fatalf("the revocation did not wait for the publication transaction (error = %v)", err) + case <-time.After(300 * time.Millisecond): + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit: %v", err) + } + if err := <-revoked; err != nil { + t.Fatalf("the revocation error = %v", err) + } + if after := fixture.loadPublication(t, candidate.ID); after.State() != domain.PublicationClosed || after.ClosedReason() != domain.ClosedConsentRevoked { + t.Fatalf("after the race = %v (%v), want closed because the consent was revoked", after.State(), after.ClosedReason()) + } + + // A revocation that committed first leaves nothing to lock: the publication is refused. + if _, err := fixture.queries.LockCurrentC2Record(ctx, uuidParam(candidate.ID)); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("LockCurrentC2Record() after the revocation error = %v, want no row", err) + } + }) + + t.Run("the unverified account cleanup removes its hidden organizations and history and spares a confirmed account", func(t *testing.T) { + reset(t) + stale := fixture.candidate(t, "stale@example.com") + confirmed := fixture.candidate(t, "confirmed@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + acme := fixture.organizations.create(t, employer, fixture.organizations.completeProfile(t, "Acme Synthetic LLC"), now) + fixture.hide(t, stale.ID, acme.ID(), now) + fixture.hide(t, confirmed.ID, acme.ID(), now) + if _, err := pool.Exec(ctx, `UPDATE users SET email_verified_at = $3 WHERE id = ANY($1) OR id = $2`, []uuid.UUID{confirmed.ID}, employer.ID, now); err != nil { + t.Fatalf("confirm the accounts: %v", err) + } + deleted, err := fixture.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{Cutoff: timeParam(now.Add(48 * time.Hour)), BatchLimit: 10}) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedUsersRegisteredBefore() = %d, %v, want the one unverified account", deleted, err) + } + assertRowCount(ctx, t, pool, candidateHiddenOrganizationsTable, 1) + assertRowCount(ctx, t, pool, candidatePrivacyEventsTable, 1) + // A confirmed account is not deleted through the history either. + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, confirmed.ID); sqlState(err) == "" { + t.Fatal("a confirmed account with privacy history was deleted") + } + }) + + t.Run("the cleanup deletes unverified accounts with a C2, a publication, and history, whatever the C2 history", func(t *testing.T) { + reset(t) + // The cleanup deletes the consent records and the account in one + // statement of data-modifying CTEs. The cascade from the account to the + // publication, which the restricting reference to the C2 record would + // block, depends on the order in which PostgreSQL applies them; this + // scenario fails if a change to the statement or to the references + // breaks that order. + full := fixture.candidate(t, "full@example.com") + fullC2 := fixture.grant(t, full.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + fixture.publish(t, full.ID, fullC2.ID(), 0, domain.CardFieldStack) + + regranted := fixture.candidate(t, "regranted@example.com") + oldC2 := fixture.grant(t, regranted.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-2*time.Hour)) + fixture.publish(t, regranted.ID, oldC2.ID(), 0, domain.CardFieldLocation) + fixture.revokeC2(t, regranted.ID, now.Add(-time.Hour)) + fixture.grant(t, regranted.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-30*time.Minute)) + + consentOnly := fixture.candidate(t, "consent-only@example.com") + fixture.grant(t, consentOnly.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(-time.Hour)) + + deleted, err := fixture.queries.DeleteUnverifiedUsersRegisteredBefore(ctx, sqlc.DeleteUnverifiedUsersRegisteredBeforeParams{Cutoff: timeParam(now.Add(48 * time.Hour)), BatchLimit: 10}) + if err != nil || deleted != 3 { + t.Fatalf("DeleteUnverifiedUsersRegisteredBefore() = %d, %v, want the three unverified accounts", deleted, err) + } + for _, table := range slices.Concat(candidatePrivacyTables, []pgx.Identifier{consentRecordsTable, {"users"}}) { + assertRowCount(ctx, t, pool, table, 0) + } + }) + + t.Run("concurrent hidings at the bound let exactly one through", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + employer := fixture.organizations.employer(t, "owner@example.com") + const parallel = 8 + limit := domain.MaxHiddenOrganizations + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, $2)`, employer.ID, now); err != nil { + t.Fatalf("create holding: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations (id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id) + SELECT gen_random_uuid(), 'Bulk ' || n, 'e0', 'confirmed_email', $1, 1, $1, $1, (SELECT id FROM holdings WHERE founder_account_id = $3) + FROM generate_series(1, $2::int) AS n`, now, limit-1+parallel, employer.ID); err != nil { + t.Fatalf("create organizations: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + SELECT gen_random_uuid(), id, $1, 'owner', 'active', $2, $2 FROM organizations WHERE name LIKE 'Bulk %'`, employer.ID, now); err != nil { + t.Fatalf("create memberships: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) + SELECT $1, id, $2 FROM (SELECT id FROM organizations WHERE name LIKE 'Bulk %' ORDER BY id LIMIT $3) AS first`, candidate.ID, now, limit-1); err != nil { + t.Fatalf("hide %d organizations: %v", limit-1, err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit: %v", err) + } + rows, err := pool.Query(ctx, ` + SELECT id FROM organizations WHERE name LIKE 'Bulk %' AND id NOT IN (SELECT organization_id FROM candidate_hidden_organizations)`) + if err != nil { + t.Fatalf("list the free organizations: %v", err) + } + free, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID]) + if err != nil || len(free) != parallel { + t.Fatalf("free organizations = %d, %v, want %d", len(free), err, parallel) + } + results := make([]error, parallel) + var wait sync.WaitGroup + for index := range parallel { + wait.Add(1) + go func() { + defer wait.Done() + _, results[index] = pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, candidate.ID, free[index], now) + }() + } + wait.Wait() + succeeded := 0 + for _, err := range results { + var pgError *pgconn.PgError + switch { + case err == nil: + succeeded++ + case errors.As(err, &pgError) && pgError.ConstraintName == "candidate_hidden_organizations_limit": + default: + t.Fatalf("a concurrent hiding error = %v, want success or the limit", err) + } + } + if succeeded != 1 { + t.Fatalf("%d concurrent hidings succeeded at the bound, want exactly 1", succeeded) + } + if total, _ := fixture.queries.CountCandidateHiddenOrganizations(ctx, uuidParam(candidate.ID)); int(total) != limit { + t.Fatalf("hidden organizations = %d, want exactly %d", total, limit) + } + }) + + t.Run("the privacy tables hold no profile value, name, contact, or file", func(t *testing.T) { + rows, err := pool.Query(ctx, ` + SELECT table_name || '.' || column_name FROM information_schema.columns + WHERE table_schema = 'public' AND table_name LIKE 'candidate\_%' AND table_name IN ( + 'candidate_publications', 'candidate_search_statuses', 'candidate_hidden_organizations', 'candidate_privacy_events') + ORDER BY 1`) + if err != nil { + t.Fatalf("list the columns: %v", err) + } + columns, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("collect the columns: %v", err) + } + for _, column := range columns { + for _, forbidden := range []string{"email", "phone", "telegram", "contact", "full_name", "salary", "resume", "file", "value", "claim"} { + if containsWord(column, forbidden) { + t.Errorf("the column %s looks like %q", column, forbidden) + } + } + } + }) +} + +func TestCandidateCardAccessEventRetentionAndActorAnonymization(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity, + organizations: organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now}, + ledger: postgresadapter.NewConsentStore(pool), now: now, + } + truncateTables(ctx, t, pool, usersDependentTables...) + + candidate := fixture.candidate(t, "privacy-owner@example.test") + verifyPrivacyCohortCandidate(t, fixture, candidate) + organizationOwner := fixture.organizations.employer(t, "privacy-organization-owner@example.test") + organization := fixture.organizations.create(t, organizationOwner, + fixture.organizations.completeProfile(t, "Access history organization"), now) + actor := fixture.candidate(t, "privacy-viewer@example.test") + + access, err := domain.NewCandidateCardAccess(domain.CandidateCardAccessInput{ + CandidateID: candidate.ID, OrganizationID: organization.ID(), ActorID: actor.ID, + Kind: domain.CandidateCardAccessCardViewed, OccurredAt: now, + }) + if err != nil { + t.Fatalf("NewCandidateCardAccess() error = %v", err) + } + queries := sqlc.New(pool) + if err := queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{ + ID: uuidParam(access.ID()), CandidateID: uuidParam(candidate.ID), OrganizationID: uuidParam(organization.ID()), + ActorID: uuidParam(actor.ID), Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: timeParam(access.OccurredAt()), + }); err != nil { + t.Fatalf("InsertCandidateCardAccessEvent(pseudonym-only) error = %v", err) + } + + _, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET field_codes = ARRAY['location'] WHERE id = $1`, access.ID()) + assertPgError(t, "reject card access field update", err, privacyIntegrityViolation, "candidate_card_access_events_immutable") + _, err = pool.Exec(ctx, `UPDATE candidate_card_access_events SET actor_id = NULL WHERE id = $1`, access.ID()) + assertPgError(t, "reject direct card access actor anonymization", err, privacyIntegrityViolation, "candidate_card_access_events_immutable") + _, err = pool.Exec(ctx, `DELETE FROM candidate_card_access_events WHERE id = $1`, access.ID()) + assertPgError(t, "reject card access deletion", err, privacyIntegrityViolation, "candidate_card_access_events_retained") + + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, actor.ID); err != nil { + t.Fatalf("DELETE audit actor = %v", err) + } + var storedCandidate, storedOrganization uuid.UUID + var storedActor pgtype.UUID + var kind string + var fields []string + if err := pool.QueryRow(ctx, `SELECT candidate_id, organization_id, actor_id, kind, field_codes FROM candidate_card_access_events WHERE id = $1`, access.ID()). + Scan(&storedCandidate, &storedOrganization, &storedActor, &kind, &fields); err != nil { + t.Fatalf("read retained card access = %v", err) + } + if storedCandidate != candidate.ID || storedOrganization != organization.ID() || storedActor.Valid || + kind != string(domain.CandidateCardAccessCardViewed) || len(fields) != 0 { + t.Fatalf("retained access = candidate %s org %s actor %+v kind %s fields %v", storedCandidate, storedOrganization, storedActor, kind, fields) + } +} + +func containsWord(column, word string) bool { + for _, part := range splitIdentifier(column) { + if part == word { + return true + } + } + return false +} + +func splitIdentifier(identifier string) []string { + var parts []string + start := 0 + for index, character := range identifier { + if character == '_' || character == '.' { + parts = append(parts, identifier[start:index]) + start = index + 1 + } + } + return append(parts, identifier[start:]) +} + +func sqlState(err error) string { + var pgError *pgconn.PgError + if errors.As(err, &pgError) { + return pgError.Code + } + return "" +} + +func uuidParam(id uuid.UUID) pgtype.UUID { return pgtype.UUID{Bytes: id, Valid: true} } + +func timeParam(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} } + +func domainFields(t *testing.T, fields ...domain.CardField) domain.CardFieldSet { + t.Helper() + set, err := domain.NewCardFieldSet(fields) + if err != nil { + t.Fatalf("NewCardFieldSet() error = %v", err) + } + return set +} + +func mustPublicationRequest(t *testing.T, state domain.PublicationState, fields ...domain.CardField) domain.PublicationRequest { + t.Helper() + request, err := domain.NewPublicationRequest(state, fields) + if err != nil { + t.Fatalf("NewPublicationRequest() error = %v", err) + } + return request +} + +func (fixture candidatePrivacyFixture) candidate(t *testing.T, email string) domain.User { + t.Helper() + return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-24*time.Hour)) +} + +func (fixture candidatePrivacyFixture) grant(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose, version domain.ConsentTextVersion, at time.Time) domain.ConsentRecord { + t.Helper() + text, err := fixture.ledger.ConsentTexts().Get(fixture.ctx, purpose, version) + if err != nil { + t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err) + } + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), + Source: domain.ConsentSourceConsentSettings, GrantedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + record, created, err := fixture.ledger.ConsentLedger().Grant(fixture.ctx, grant) + if err != nil || !created { + t.Fatalf("Grant(%s) = %v, %v, want a new record", purpose, created, err) + } + return record +} + +func (fixture candidatePrivacyFixture) revokeC2(t *testing.T, subject uuid.UUID, at time.Time) { + t.Helper() + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject, Purpose: domain.ConsentPurposePublication, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + if revoked, err := fixture.ledger.ConsentLedger().Revoke(fixture.ctx, revocation); err != nil || len(revoked) == 0 { + t.Fatalf("Revoke(c2) = %v, %v, want the record", revoked, err) + } +} + +// loadPublication reads the stored setting with its ledger state the way a +// repository does and returns the closed default when there is no row. +func (fixture candidatePrivacyFixture) loadPublication(t *testing.T, userID uuid.UUID) domain.Publication { + t.Helper() + row, err := fixture.queries.ReadCandidatePublication(fixture.ctx, uuidParam(userID)) + if errors.Is(err, pgx.ErrNoRows) { + publication, err := domain.NewPublication(userID) + if err != nil { + t.Fatalf("NewPublication() error = %v", err) + } + return publication + } + if err != nil { + t.Fatalf("ReadCandidatePublication() error = %v", err) + } + publication, err := domain.RestorePublication(domain.StoredPublication{ + UserID: userID, State: row.State, Fields: row.Fields, ConsentRecordID: row.ConsentRecordID.Bytes, + PublishedAt: row.PublishedAt.Time, ClosedAt: row.ClosedAt.Time, Version: row.Version, ConsentRevoked: row.ConsentRevokedAt.Valid, + }) + if err != nil { + t.Fatalf("RestorePublication() error = %v", err) + } + return publication +} + +// publish applies a publication request over expectedVersion with the given +// C2 record and stores the result the way a repository does. +func (fixture candidatePrivacyFixture) publish(t *testing.T, userID, consent uuid.UUID, expectedVersion int64, fields ...domain.CardField) domain.Publication { + t.Helper() + current := fixture.loadPublication(t, userID) + change, err := current.Apply(mustPublicationRequest(t, domain.PublicationPublished, fields...), expectedVersion, consent, fixture.now) + if err != nil || !change.Changed { + t.Fatalf("Apply(publish) = %+v, %v, want a change", change, err) + } + fixture.storePublication(t, change.Publication, expectedVersion) + fixture.recordPublicationEvent(t, change, fixture.now) + return fixture.loadPublication(t, userID) +} + +func (fixture candidatePrivacyFixture) storePublication(t *testing.T, publication domain.Publication, expectedVersion int64) { + t.Helper() + closedAt := pgtype.Timestamptz{} + if !publication.ClosedAt().IsZero() { + closedAt = timeParam(publication.ClosedAt()) + } + if expectedVersion == 0 { + if _, err := fixture.queries.InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(publication.UserID()), State: string(publication.StoredState()), Fields: publication.StoredFields(), + ConsentRecordID: uuidParam(publication.ConsentRecordID()), PublishedAt: timeParam(publication.PublishedAt()), ClosedAt: closedAt, At: timeParam(fixture.now), + }); err != nil { + t.Fatalf("InsertCandidatePublication() error = %v", err) + } + return + } + if _, err := fixture.queries.UpdateCandidatePublication(fixture.ctx, sqlc.UpdateCandidatePublicationParams{ + UserID: uuidParam(publication.UserID()), ExpectedVersion: expectedVersion, State: string(publication.StoredState()), Fields: publication.StoredFields(), + ConsentRecordID: uuidParam(publication.ConsentRecordID()), PublishedAt: timeParam(publication.PublishedAt()), ClosedAt: closedAt, At: timeParam(fixture.now), + }); err != nil { + t.Fatalf("UpdateCandidatePublication() error = %v", err) + } +} + +func (fixture candidatePrivacyFixture) recordPublicationEvent(t *testing.T, change domain.PublicationChange, at time.Time) { + t.Helper() + event, err := domain.NewPublicationEvent(change, at) + if err != nil { + t.Fatalf("NewPublicationEvent() error = %v", err) + } + params := sqlc.InsertCandidatePrivacyEventParams{ + ID: uuidParam(event.ID()), UserID: uuidParam(event.UserID()), Kind: string(event.Kind()), OccurredAt: timeParam(event.OccurredAt()), + } + if event.HasFieldSet() { + params.Fields = event.Fields().Codes() + } + if event.ConsentRecordID() != uuid.Nil { + params.ConsentRecordID = uuidParam(event.ConsentRecordID()) + } + if err := fixture.queries.InsertCandidatePrivacyEvent(fixture.ctx, params); err != nil { + t.Fatalf("InsertCandidatePrivacyEvent() error = %v", err) + } +} + +func (fixture candidatePrivacyFixture) loadSearchStatus(t *testing.T, userID uuid.UUID) domain.SearchStatus { + t.Helper() + row, err := fixture.queries.ReadCandidateSearchStatus(fixture.ctx, uuidParam(userID)) + if errors.Is(err, pgx.ErrNoRows) { + status, err := domain.NewSearchStatus(userID) + if err != nil { + t.Fatalf("NewSearchStatus() error = %v", err) + } + return status + } + if err != nil { + t.Fatalf("ReadCandidateSearchStatus() error = %v", err) + } + status, err := domain.RestoreSearchStatus(domain.StoredSearchStatus{ + UserID: userID, Status: row.Status, ConfirmedAt: row.ConfirmedAt.Time, LapsesAt: row.LapsesAt.Time, + PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), Version: row.Version, + }) + if err != nil { + t.Fatalf("RestoreSearchStatus() error = %v", err) + } + return status +} + +// setSearchStatus applies a status request with the stored policy version and +// stores the result the way a repository does. +func (fixture candidatePrivacyFixture) setSearchStatus(t *testing.T, userID uuid.UUID, value domain.SearchStatusValue, expectedVersion int64, at time.Time) domain.SearchStatus { + t.Helper() + confirmation, err := domain.NewSearchStatusConfirmation(fixture.policy.ID(), fixture.policy.Policy().SearchStatus) + if err != nil { + t.Fatalf("NewSearchStatusConfirmation() error = %v", err) + } + change, err := fixture.loadSearchStatus(t, userID).Apply(value, expectedVersion, confirmation, at) + if err != nil || !change.Changed { + t.Fatalf("Apply(%s) = %+v, %v, want a change", value, change, err) + } + next := change.Status + confirmed, lapses, policyID := pgtype.Timestamptz{}, pgtype.Timestamptz{}, pgtype.UUID{} + if next.StoredValue() == domain.SearchStatusLooking { + confirmed, lapses, policyID = timeParam(next.ConfirmedAt()), timeParam(next.LapsesAt()), uuidParam(next.PolicyVersionID().UUID()) + } + if expectedVersion == 0 { + _, err = fixture.queries.InsertCandidateSearchStatus(fixture.ctx, sqlc.InsertCandidateSearchStatusParams{ + UserID: uuidParam(userID), Status: string(next.StoredValue()), ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(at), + }) + } else { + _, err = fixture.queries.UpdateCandidateSearchStatus(fixture.ctx, sqlc.UpdateCandidateSearchStatusParams{ + UserID: uuidParam(userID), ExpectedVersion: expectedVersion, Status: string(next.StoredValue()), + ConfirmedAt: confirmed, LapsesAt: lapses, PolicyVersionID: policyID, At: timeParam(at), + }) + } + if err != nil { + t.Fatalf("store the search status: %v", err) + } + return fixture.loadSearchStatus(t, userID) +} + +// hide stores a hiding and its history event the way a repository does. +func (fixture candidatePrivacyFixture) hide(t *testing.T, userID, organizationID uuid.UUID, at time.Time) { + t.Helper() + hidden, err := domain.NewHiddenOrganization(userID, organizationID, at) + if err != nil { + t.Fatalf("NewHiddenOrganization() error = %v", err) + } + if _, err := fixture.queries.InsertCandidateHiddenOrganization(fixture.ctx, sqlc.InsertCandidateHiddenOrganizationParams{ + UserID: uuidParam(hidden.UserID()), OrganizationID: uuidParam(hidden.OrganizationID()), At: timeParam(hidden.HiddenAt()), + }); err != nil { + t.Fatalf("InsertCandidateHiddenOrganization() error = %v", err) + } + event, err := domain.NewOrganizationEvent(domain.PrivacyEventOrganizationHidden, userID, organizationID, at) + if err != nil { + t.Fatalf("NewOrganizationEvent() error = %v", err) + } + if err := fixture.queries.InsertCandidatePrivacyEvent(fixture.ctx, sqlc.InsertCandidatePrivacyEventParams{ + ID: uuidParam(event.ID()), UserID: uuidParam(userID), Kind: string(event.Kind()), OccurredAt: timeParam(at), + OrganizationID: uuidParam(organizationID), + }); err != nil { + t.Fatalf("InsertCandidatePrivacyEvent() error = %v", err) + } +} + +// The raw readers return a comparable text of the rows, so a test can prove +// that an operation left a table exactly as it was. +func (fixture candidatePrivacyFixture) rawPublication(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(p::text, ';'), '') FROM candidate_publications p WHERE user_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawSearchStatus(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(s::text, ';'), '') FROM candidate_search_statuses s WHERE user_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawHidden(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(h::text, ';' ORDER BY organization_id), '') FROM candidate_hidden_organizations h WHERE user_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawConsentRecords(t *testing.T, userID uuid.UUID) string { + t.Helper() + return fixture.rawRows(t, `SELECT coalesce(string_agg(c::text, ';' ORDER BY id), '') FROM consent_records c WHERE subject_id = $1`, userID) +} + +func (fixture candidatePrivacyFixture) rawRows(t *testing.T, query string, userID uuid.UUID) string { + t.Helper() + var text string + if err := fixture.pool.QueryRow(fixture.ctx, query, userID).Scan(&text); err != nil { + t.Fatalf("read raw rows: %v", err) + } + return text +} diff --git a/backend/integration_test/candidate_profile_http_test.go b/backend/integration_test/candidate_profile_http_test.go new file mode 100644 index 0000000..be1b715 --- /dev/null +++ b/backend/integration_test/candidate_profile_http_test.go @@ -0,0 +1,538 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + profileusecase "lincodex/backend/internal/usecase/profile" +) + +const candidateProfileHTTPTestTimeout = 5 * time.Minute + +func TestCandidateProfileOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), candidateProfileHTTPTestTimeout) + defer cancel() + harness := newCandidateProfileHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, usersDependentTables...) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + candidate := createSessionHTTPUser(ctx, t, harness, "profile-owner@example.test", passwordHash, true) + otherCandidate := createSessionHTTPUser(ctx, t, harness, "profile-other@example.test", passwordHash, true) + employer := createOrganizationHTTPUser(ctx, t, harness, "profile-employer@example.test", passwordHash, domain.ScenarioEmployer, true, now) + for _, user := range []domain.User{candidate, otherCandidate} { + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", user.ID); err != nil { + t.Fatalf("set candidate profile onboarding step: %v", err) + } + } + candidateCookie, candidateCSRF := loginCandidateProfileHTTP(t, harness, candidate.Email.Address()) + otherCookie, otherCSRF := loginCandidateProfileHTTP(t, harness, otherCandidate.Email.Address()) + employerCookie, _ := loginCandidateProfileHTTP(t, harness, employer.Email.Address()) + + initial := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.101:1234") + if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("empty profile = %d Cache-Control=%q, want 200 no-store: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String()) + } + var emptyResponse candidateProfileHTTPResponse + if err := json.Unmarshal(initial.Body.Bytes(), &emptyResponse); err != nil { + t.Fatalf("decode empty profile: %v", err) + } + if emptyResponse.Version != 0 || emptyResponse.FullName.Status != "unknown" || len(emptyResponse.ExperienceOverlaps) != 0 { + t.Fatalf("empty profile = %+v, want version 0 and no overlapping periods", emptyResponse) + } + + missingAcknowledgement := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 0, "Private Profile Owner", false), candidateCookie, candidateCSRF, "192.0.2.102:1234") + if missingAcknowledgement.Code != http.StatusBadRequest || !strings.Contains(missingAcknowledgement.Body.String(), "/experience/1/started_on") { + t.Fatalf("overlapping periods without acknowledgement = %d %s, want field validation", missingAcknowledgement.Code, missingAcknowledgement.Body.String()) + } + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 0, 0) + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile") + + firstSave := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 0, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.103:1234") + if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("save profile = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String()) + } + var saved candidateProfileHTTPResponse + if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil { + t.Fatalf("decode saved profile: %v", err) + } + if saved.Version != 1 || saved.FullName.Value == nil || *saved.FullName.Value != "Private Profile Owner" || + len(saved.ExperienceOverlaps) != 1 || saved.ExperienceOverlaps[0].Status != "confirmed" || + len(saved.ConfirmedCategories) != 0 { + t.Fatalf("saved profile = %+v, want version 1 with confirmed period overlap", saved) + } + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1) + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire") + assertCandidateProfileHistoryCannotBeUpdated(t, ctx, harness, candidate.ID) + + reversedPeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 0, "2021-01", "2020-12"), + candidateCookie, candidateCSRF, "192.0.2.111:1234") + if reversedPeriod.Code != http.StatusBadRequest || !strings.Contains(reversedPeriod.Body.String(), "/experience/0/ended_on") { + t.Fatalf("reversed experience period = %d %s, want a fixed ended_on validation error", reversedPeriod.Code, reversedPeriod.Body.String()) + } + futurePeriod := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateWithExperience(t, 1, "Private Profile Owner", 1, "2999-01", nil), + candidateCookie, candidateCSRF, "192.0.2.112:1234") + if futurePeriod.Code != http.StatusBadRequest || !strings.Contains(futurePeriod.Body.String(), "/experience/1/started_on") { + t.Fatalf("future experience period = %d %s, want a fixed started_on validation error", futurePeriod.Code, futurePeriod.Body.String()) + } + for _, forbiddenField := range []struct { + name string + value any + }{ + {name: "confirmed_categories", value: []any{map[string]any{"specialization": "backend", "grade": "senior"}}}, + {name: "user_id", value: uuid.NewString()}, + } { + body := candidateProfileUpdateWithUnknownField(t, + candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), forbiddenField.name, forbiddenField.value) + response := candidateProfileHTTPRequest(t, harness, http.MethodPut, body, candidateCookie, candidateCSRF, "192.0.2.113:1234") + if response.Code != http.StatusBadRequest { + t.Fatalf("profile update with %s = %d %s, want 400", forbiddenField.name, response.Code, response.Body.String()) + } + } + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1) + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire") + + stale := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 0, "Stale Profile Name", true), candidateCookie, candidateCSRF, "192.0.2.104:1234") + requireSessionProblem(t, stale, http.StatusPreconditionFailed, "version_conflict") + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1) + + noOp := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 1, "Private Profile Owner", true), candidateCookie, candidateCSRF, "192.0.2.105:1234") + if noOp.Code != http.StatusOK { + t.Fatalf("no-op profile save = %d %s, want 200", noOp.Code, noOp.Body.String()) + } + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1) + + otherRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", otherCookie, "", "192.0.2.106:1234") + var otherProfile candidateProfileHTTPResponse + if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &otherProfile) != nil || + otherProfile.Version != 0 || otherProfile.FullName.Value != nil { + t.Fatalf("another candidate's profile = %d %s, want an empty version-0 profile", otherRead.Code, otherRead.Body.String()) + } + employerRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", employerCookie, "", "192.0.2.107:1234") + requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden") + for _, foreignPath := range []string{ + "/api/v1/me/profile/" + otherCandidate.ID.String(), + "/api/v1/me/profile/" + uuid.NewString(), + } { + foreignRead := harness.request(t, http.MethodGet, foreignPath, "", sessionHTTPTestOrigin, candidateCookie, "", "192.0.2.114:1234") + if foreignRead.Code != http.StatusNotFound || strings.Contains(foreignRead.Body.String(), "Private Profile Owner") { + t.Fatalf("foreign profile path %s = %d %s, want a non-disclosing 404", foreignPath, foreignRead.Code, foreignRead.Body.String()) + } + } + + // A no-op on an unsaved profile advances onboarding without inventing a + // profile version or a history row. + emptySave := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateEmptyProfileUpdateBody(t), otherCookie, otherCSRF, "192.0.2.108:1234") + if emptySave.Code != http.StatusOK { + t.Fatalf("empty profile save = %d %s, want 200", emptySave.Code, emptySave.Body.String()) + } + assertCandidateProfileRows(t, ctx, harness, otherCandidate.ID, 0, 0) + assertCandidateProfileOnboarding(t, ctx, harness, otherCandidate.ID, "candidate_questionnaire") + + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_profile' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("reset candidate onboarding for rollback test: %v", err) + } + removeHistoryFailure := installCandidateProfileHistoryInsertFailure(t, ctx, harness) + historyFailure := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 1, "Failed History Write", true), candidateCookie, candidateCSRF, "192.0.2.115:1234") + if historyFailure.Code != http.StatusInternalServerError { + t.Fatalf("profile save with history failure = %d %s, want 500", historyFailure.Code, historyFailure.Body.String()) + } + removeHistoryFailure() + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1) + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile") + + // Failure after history insertion must also roll back the profile and + // history when the onboarding transition fails in the same transaction. + removeOnboardingFailure := installCandidateProfileOnboardingFailure(t, ctx, harness) + rollbackAttempt := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.116:1234") + if rollbackAttempt.Code != http.StatusInternalServerError { + t.Fatalf("profile save with onboarding failure = %d %s, want 500", rollbackAttempt.Code, rollbackAttempt.Body.String()) + } + removeOnboardingFailure() + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 1, 1) + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_profile") + unchanged := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.117:1234") + var unchangedProfile candidateProfileHTTPResponse + if unchanged.Code != http.StatusOK || json.Unmarshal(unchanged.Body.Bytes(), &unchangedProfile) != nil || + unchangedProfile.FullName.Value == nil || *unchangedProfile.FullName.Value != "Private Profile Owner" { + t.Fatalf("profile after failed transaction = %d %s, want old claims", unchanged.Code, unchanged.Body.String()) + } + updated := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 1, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.118:1234") + var updatedProfile candidateProfileHTTPResponse + if updated.Code != http.StatusOK || json.Unmarshal(updated.Body.Bytes(), &updatedProfile) != nil || + updatedProfile.Version != 2 || updatedProfile.FullName.Value == nil || *updatedProfile.FullName.Value != "Private Profile Owner Updated" { + t.Fatalf("profile save after rolled-back attempt = %d %s, want version 2", updated.Code, updated.Body.String()) + } + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2) + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_questionnaire") + + // Once onboarding has moved past the profile step, saving again does not + // move it back or override its current step. + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_assessment' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("move onboarding to a later step: %v", err) + } + if response := candidateProfileHTTPRequest(t, harness, http.MethodPut, + candidateProfileUpdateBody(t, 2, "Private Profile Owner Updated", true), candidateCookie, candidateCSRF, "192.0.2.109:1234"); response.Code != http.StatusOK { + t.Fatalf("profile save after later onboarding step = %d %s", response.Code, response.Body.String()) + } + assertCandidateProfileOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment") + + for _, privateValue := range []string{ + candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(), + "Private Profile Owner", "Private Profile Owner Updated", "Stale Profile Name", "Failed History Write", + "Example Private Employer", "Private career history", + } { + if strings.Contains(harness.logs.String(), privateValue) { + t.Fatalf("profile HTTP logs contain private value %q", privateValue) + } + } + + // Rebuild the handlers and pool while retaining the session cookie. The + // profile and append-only history remain in PostgreSQL across restarts. + harness.pool.Close() + harness = newCandidateProfileHTTPHarness(ctx, t, env) + restartedRead := candidateProfileHTTPRequest(t, harness, http.MethodGet, "", candidateCookie, "", "192.0.2.110:1234") + var restarted candidateProfileHTTPResponse + if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil || + restarted.Version != 2 || restarted.FullName.Value == nil || *restarted.FullName.Value != "Private Profile Owner Updated" || + len(restarted.ExperienceOverlaps) != 1 || restarted.ExperienceOverlaps[0].Status != "confirmed" { + t.Fatalf("profile after handler restart = %d %s, want version 2 and stored confirmation", restartedRead.Code, restartedRead.Body.String()) + } + assertCandidateProfileRows(t, ctx, harness, candidate.ID, 2, 2) +} + +type candidateProfileHTTPResponse struct { + Version int64 `json:"version"` + FullName struct { + Status string `json:"status"` + Value *string `json:"value"` + } `json:"full_name"` + ExperienceOverlaps []struct { + FirstIndex int `json:"first_index"` + SecondIndex int `json:"second_index"` + Status string `json:"status"` + } `json:"experience_overlaps"` + ConfirmedCategories []json.RawMessage `json:"confirmed_categories"` +} + +func newCandidateProfileHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + profileHandler := v1.NewProfileHandler(profileusecase.NewService(postgresadapter.NewTransactor(pool), clock.Now)) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func loginCandidateProfileHTTP(t *testing.T, harness *sessionHTTPHarness, email string) (string, string) { + t.Helper() + response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.100:1234") + if response.Code != http.StatusCreated { + t.Fatalf("login profile account = %d %s", response.Code, response.Body.String()) + } + cookie := requireSessionCookie(t, response) + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" { + t.Fatalf("decode login CSRF token: %v", err) + } + return cookie.Value, body.CSRFToken +} + +func candidateProfileHTTPRequest( + t *testing.T, + harness *sessionHTTPHarness, + method, body, cookie, csrf, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + return harness.request(t, method, "/api/v1/me/profile", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr) +} + +func candidateProfileUpdateBody(t *testing.T, version int64, name string, confirmOverlap bool) string { + t.Helper() + experience := []map[string]any{ + { + "employer_name": "Example Private Employer", "specialization": "backend", "started_on": "2021-01", + "ended_on": "2022-06", "summary": "Private career history", "status": "confirmed", + }, + { + "employer_name": "Second Private Employer", "specialization": "backend", "started_on": "2022-01", + "ended_on": "2023-04", "summary": "Another private result", "status": "confirmed", + }, + } + acknowledgements := []map[string]any{} + if confirmOverlap { + acknowledgements = append(acknowledgements, map[string]any{ + "first_index": 0, "second_index": 1, + "first_period": map[string]any{"started_on": "2021-01", "ended_on": "2022-06"}, + "second_period": map[string]any{"started_on": "2022-01", "ended_on": "2023-04"}, + }) + } + body, err := json.Marshal(map[string]any{ + "expected_version": version, + "full_name": map[string]any{"value": name, "status": "confirmed"}, + "contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil}, + "stack": []any{}, + "roles": []any{}, + "experience": experience, + "confirmed_parallel_periods": acknowledgements, + "soft_skills": []any{}, + "terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil}, + }) + if err != nil { + t.Fatalf("marshal profile update: %v", err) + } + return string(body) +} + +func candidateProfileUpdateWithExperience( + t *testing.T, + version int64, + name string, + index int, + startedOn string, + endedOn any, +) string { + t.Helper() + var body map[string]any + if err := json.Unmarshal([]byte(candidateProfileUpdateBody(t, version, name, true)), &body); err != nil { + t.Fatalf("decode profile update fixture: %v", err) + } + experience, ok := body["experience"].([]any) + if !ok || index < 0 || index >= len(experience) { + t.Fatalf("profile update fixture has no experience at index %d", index) + } + item, ok := experience[index].(map[string]any) + if !ok { + t.Fatalf("profile update fixture experience at index %d has the wrong type", index) + } + item["started_on"] = startedOn + item["ended_on"] = endedOn + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal profile update fixture: %v", err) + } + return string(encoded) +} + +func candidateProfileUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string { + t.Helper() + var body map[string]any + if err := json.Unmarshal([]byte(requestBody), &body); err != nil { + t.Fatalf("decode profile update fixture: %v", err) + } + body[field] = value + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal profile update with %s: %v", field, err) + } + return string(encoded) +} + +func candidateEmptyProfileUpdateBody(t *testing.T) string { + t.Helper() + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "full_name": nil, + "contacts": map[string]any{"email": nil, "phone": nil, "telegram": nil}, + "stack": []any{}, "roles": []any{}, "experience": []any{}, + "confirmed_parallel_periods": []any{}, "soft_skills": []any{}, + "terms": map[string]any{"location": nil, "relocation": nil, "salary_minimum": nil}, + }) + if err != nil { + t.Fatalf("marshal empty profile update: %v", err) + } + return string(body) +} + +func assertCandidateProfileRows(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, version, history int64) { + t.Helper() + var profileCount, historyCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profiles WHERE user_id = $1", userID).Scan(&profileCount); err != nil { + t.Fatalf("count stored profiles: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_profile_history WHERE user_id = $1", userID).Scan(&historyCount); err != nil { + t.Fatalf("count profile history: %v", err) + } + wantProfileCount := int64(0) + if version > 0 { + wantProfileCount = 1 + } + if profileCount != wantProfileCount || historyCount != history { + t.Fatalf("profile rows = %d, history rows = %d; want %d and %d", profileCount, historyCount, wantProfileCount, history) + } + if version > 0 { + var storedVersion int64 + if err := harness.pool.QueryRow(ctx, "SELECT version FROM candidate_profiles WHERE user_id = $1", userID).Scan(&storedVersion); err != nil { + t.Fatalf("read stored profile version: %v", err) + } + if storedVersion != version { + t.Fatalf("stored profile version = %d, want %d", storedVersion, version) + } + } +} + +func assertCandidateProfileOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) { + t.Helper() + var step string + if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil { + t.Fatalf("read onboarding step: %v", err) + } + if step != want { + t.Fatalf("onboarding step = %q, want %q", step, want) + } +} + +func assertCandidateProfileHistoryCannotBeUpdated(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) { + t.Helper() + if _, err := harness.pool.Exec(ctx, "UPDATE candidate_profile_history SET snapshot = snapshot WHERE user_id = $1", userID); err == nil { + t.Fatal("candidate profile history accepted an UPDATE") + } +} + +func installCandidateProfileHistoryInsertFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() { + t.Helper() + const functionName = "reject_candidate_profile_history_insert_for_http_test" + const triggerName = "candidate_profile_http_reject_history_insert" + if _, err := harness.pool.Exec(ctx, ` + CREATE FUNCTION reject_candidate_profile_history_insert_for_http_test() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + RAISE EXCEPTION 'candidate profile history HTTP test failure'; + END; + $$`); err != nil { + t.Fatalf("create history failure function: %v", err) + } + removed := false + remove := func() { + if removed { + return + } + cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON candidate_profile_history"); err != nil { + t.Errorf("drop history failure trigger: %v", err) + } + if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil { + t.Errorf("drop history failure function: %v", err) + } + removed = true + } + t.Cleanup(remove) + if _, err := harness.pool.Exec(ctx, ` + CREATE TRIGGER candidate_profile_http_reject_history_insert + BEFORE INSERT ON candidate_profile_history + FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_history_insert_for_http_test()`); err != nil { + t.Fatalf("create history failure trigger: %v", err) + } + return remove +} + +func installCandidateProfileOnboardingFailure(t *testing.T, ctx context.Context, harness *sessionHTTPHarness) func() { + t.Helper() + const functionName = "reject_candidate_profile_onboarding_advance_for_http_test" + const triggerName = "candidate_profile_http_reject_onboarding_advance" + if _, err := harness.pool.Exec(ctx, ` + CREATE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + IF OLD.onboarding_step = 'candidate_profile' AND NEW.onboarding_step = 'candidate_questionnaire' THEN + RAISE EXCEPTION 'candidate profile HTTP test failure'; + END IF; + RETURN NEW; + END; + $$`); err != nil { + t.Fatalf("create onboarding failure function: %v", err) + } + removed := false + remove := func() { + if removed { + return + } + cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := harness.pool.Exec(cleanupCtx, "DROP TRIGGER IF EXISTS "+triggerName+" ON users"); err != nil { + t.Errorf("drop onboarding failure trigger: %v", err) + } + if _, err := harness.pool.Exec(cleanupCtx, "DROP FUNCTION IF EXISTS "+functionName+"()"); err != nil { + t.Errorf("drop onboarding failure function: %v", err) + } + removed = true + } + t.Cleanup(remove) + if _, err := harness.pool.Exec(ctx, ` + CREATE TRIGGER candidate_profile_http_reject_onboarding_advance + BEFORE UPDATE ON users + FOR EACH ROW EXECUTE FUNCTION reject_candidate_profile_onboarding_advance_for_http_test()`); err != nil { + t.Fatalf("create onboarding failure trigger: %v", err) + } + return remove +} diff --git a/backend/integration_test/candidate_profile_test.go b/backend/integration_test/candidate_profile_test.go new file mode 100644 index 0000000..bc37c2d --- /dev/null +++ b/backend/integration_test/candidate_profile_test.go @@ -0,0 +1,619 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "slices" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" +) + +const ( + candidateProfileTestTimeout = 3 * time.Minute + // concurrentProfileSaves advance one profile at once from the same + // version, each on its own connection. + concurrentProfileSaves = 8 + // candidateProfileMigrationVersion creates candidateProfileTables. + candidateProfileMigrationVersion = 13 +) + +var ( + candidateProfilesTable = pgx.Identifier{"candidate_profiles"} + candidateProfileClaimsTable = pgx.Identifier{"candidate_profile_claims"} + // candidateProfileTables reference users, so a TRUNCATE of users names + // them through usersDependentTables. + candidateProfileTables = []pgx.Identifier{ + // Repository checks of the projects of a profile. + {"candidate_project_repositories"}, + {"candidate_profile_overlap_confirmations"}, + {"candidate_profile_history"}, + candidateProfileClaimsTable, + candidateProfilesTable, + } +) + +// candidateProfileFixture works on the bootstrap database. The tables are +// truncated between subtests. +type candidateProfileFixture struct { + ctx context.Context + pool *pgxpool.Pool + queries *sqlc.Queries + identity identityFixture + now time.Time +} + +func TestCandidateProfileStorage(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + fixture := candidateProfileFixture{ + ctx: ctx, + pool: pool, + queries: sqlc.New(pool), + identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, + now: now, + } + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("saves a profile without a file, the ML service, or an FSP account", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + + // Only the name: no resume, no import, no link of any kind. + saved := fixture.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision("Anna Sokolova"), + }, 0) + if saved.Version() != 1 { + t.Fatalf("saved version = %d, want 1 for the first save", saved.Version()) + } + read := fixture.load(t, candidate.ID) + name, ok := read.Content().FullName() + if !ok || name.Value() != "Anna Sokolova" || name.Source().Origin() != domain.ProfileOriginManual || name.Source().TrustLevel() != 0 { + t.Fatalf("stored name = %v, want a manual claim of trust level 0", ok) + } + if _, ok := read.Content().Phone(); ok { + t.Fatal("a field that was not sent came back set") + } + + // A profile row with no claim at all is allowed too. + other := fixture.candidate(t, "empty@example.com") + fixture.save(t, other.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Placeholder")}, 0) + fixture.save(t, other.ID, domain.CandidateProfileInput{}, 1) + if empty := fixture.load(t, other.ID); empty.Version() != 2 || !empty.Content().Equal(domain.CandidateProfileContent{}) { + t.Fatalf("empty profile = version %d, want version 2 with no claim", empty.Version()) + } + }) + + t.Run("a complete profile survives the round trip with its provenance", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + input := domain.CandidateProfileInput{ + FullName: confirmedDecision("Анна Соколова"), + Email: confirmedDecision("anna.sokolova@example.com"), + Phone: confirmedDecision("+79000000000"), + Telegram: confirmedDecision("@anna_sokolova"), + Stack: []domain.ProfileClaimInput[string]{{Value: "PostgreSQL", Status: domain.ProfileClaimConfirmed}, {Value: "Kafka", Status: domain.ProfileClaimConfirmed}}, + Roles: []domain.ProfileClaimInput[domain.ProfileRole]{ + {Value: domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeMiddle}, Status: domain.ProfileClaimConfirmed}, + {Value: domain.ProfileRole{Specialization: domain.SpecializationQA}, Status: domain.ProfileClaimConfirmed}, + }, + Experience: []domain.ProfileClaimInput[domain.ProfileExperience]{{ + Value: domain.ProfileExperience{EmployerName: "Example Payments", Specialization: domain.SpecializationBackend, StartedOn: "2022-03", Summary: "Первая строка\nВторая строка"}, + Status: domain.ProfileClaimConfirmed, + }, { + Value: domain.ProfileExperience{Specialization: domain.SpecializationQA, StartedOn: "2020-01", EndedOn: "2022-02"}, + Status: domain.ProfileClaimConfirmed, + }}, + SoftSkills: []domain.ProfileClaimInput[string]{{Value: "Mentoring", Status: domain.ProfileClaimConfirmed}}, + Location: confirmedDecision("Казань"), + Relocation: confirmedDecision(true), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 180000, TaxBasis: domain.ProfileTaxNet}), + } + saved := fixture.save(t, candidate.ID, input, 0) + read := fixture.load(t, candidate.ID) + if !read.Content().Equal(saved.Content()) || read.Version() != 1 || !read.CreatedAt().Equal(fixture.now) || !read.UpdatedAt().Equal(fixture.now) { + t.Fatalf("read profile = version %d, equal %v, want the saved content at version 1", read.Version(), read.Content().Equal(saved.Content())) + } + + // A suggestion stored by an import keeps its provenance, and the + // candidate's confirmation keeps it and adds the time. + fixture.insertSuggestion(t, candidate.ID, "contact_phone", 0, `"+79000001111"`) + withSuggestion := fixture.load(t, candidate.ID) + suggestion, ok := withSuggestion.Content().Phone() + if !ok || suggestion.Status() != domain.ProfileClaimExtracted || suggestion.Source().Quote() != "Tel.: +7 900 000-11-11" || + suggestion.Source().ExtractionVersion() != "resume-rules.2026-10.1" || suggestion.Source().TrustLevel() != 0 { + t.Fatal("the stored suggestion lost its provenance") + } + }) + + t.Run("the tables hold no link to a file, the ML service, or an FSP account", func(t *testing.T) { + reset(t) + rows, err := pool.Query(ctx, ` + SELECT table_name, column_name + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name IN ('candidate_profiles', 'candidate_profile_claims')`) + if err != nil { + t.Fatalf("select columns: %v", err) + } + defer rows.Close() + var columns []string + for rows.Next() { + var table, column string + if err := rows.Scan(&table, &column); err != nil { + t.Fatalf("scan column: %v", err) + } + columns = append(columns, table+"."+column) + } + if err := rows.Err(); err != nil { + t.Fatalf("read columns: %v", err) + } + slices.Sort(columns) + want := []string{ + "candidate_profile_claims.confirmed_at", "candidate_profile_claims.extraction_version", "candidate_profile_claims.kind", + "candidate_profile_claims.ordinal", "candidate_profile_claims.origin", "candidate_profile_claims.quote", + "candidate_profile_claims.status", "candidate_profile_claims.trust_level", "candidate_profile_claims.user_id", + "candidate_profile_claims.value", + "candidate_profiles.created_at", "candidate_profiles.updated_at", "candidate_profiles.user_id", "candidate_profiles.version", + } + if !slices.Equal(columns, want) { + t.Fatalf("columns = %v, want exactly %v: no file, ML, FSP, grade, or category column", columns, want) + } + + // The only foreign keys point at the account and at the profile row. + var references []string + fkRows, err := pool.Query(ctx, ` + SELECT conrelid::regclass::text || ' -> ' || confrelid::regclass::text + FROM pg_constraint + WHERE contype = 'f' AND conrelid IN ('candidate_profiles'::regclass, 'candidate_profile_claims'::regclass)`) + if err != nil { + t.Fatalf("select foreign keys: %v", err) + } + defer fkRows.Close() + for fkRows.Next() { + var reference string + if err := fkRows.Scan(&reference); err != nil { + t.Fatalf("scan foreign key: %v", err) + } + references = append(references, reference) + } + slices.Sort(references) + if !slices.Equal(references, []string{"candidate_profile_claims -> candidate_profiles", "candidate_profiles -> users"}) { + t.Fatalf("foreign keys = %v, want only the account and the profile row", references) + } + }) + + t.Run("constraints refuse a claim that breaks a rule of the contract", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0) + + type claim struct { + kind, value, status, origin string + ordinal int + trust int + quote, extraction *string + confirmed bool + } + good := claim{kind: "stack", value: `"Go"`, status: "confirmed", origin: "manual", ordinal: 5, confirmed: true} + tests := []struct { + name string + mutate func(*claim) + constraint string + }{ + {"trust level above zero", func(c *claim) { c.trust = 1 }, "candidate_profile_claims_trust_level_zero"}, + {"unknown kind", func(c *claim) { c.kind = "confirmed_grade" }, "candidate_profile_claims_kind_ordinal"}, + {"single field at a position", func(c *claim) { c.kind, c.value, c.ordinal = "full_name", `"Anna"`, 1 }, "candidate_profile_claims_kind_ordinal"}, + {"list past its limit", func(c *claim) { c.ordinal = 30 }, "candidate_profile_claims_kind_ordinal"}, + // Also breaks the confirmation rule, which sorts first. + {"unknown status", func(c *claim) { c.status = "verified" }, "candidate_profile_claims_confirmation"}, + {"unknown origin", func(c *claim) { c.origin = "fsp" }, "candidate_profile_claims_origin_known"}, + {"confirmed without a time", func(c *claim) { c.confirmed = false }, "candidate_profile_claims_confirmation"}, + {"manual with a quote", func(c *claim) { q := "quote"; c.quote = &q }, "candidate_profile_claims_origin_provenance"}, + {"import without an extractor version", func(c *claim) { c.origin = "imported" }, "candidate_profile_claims_origin_provenance"}, + {"suggestion that is manual", func(c *claim) { c.status, c.confirmed = "extracted", false }, "candidate_profile_claims_origin_provenance"}, + {"extractor version with a space", func(c *claim) { v := "a b"; c.origin, c.extraction = "imported", &v }, "candidate_profile_claims_extraction_version_format"}, + {"stack tag with surrounding whitespace", func(c *claim) { c.value = `" Go"` }, "candidate_profile_claims_stack_value"}, + {"stack tag that is not a string", func(c *claim) { c.value = `12` }, "candidate_profile_claims_stack_value"}, + {"phone outside E.164", func(c *claim) { c.kind, c.value, c.ordinal = "contact_phone", `"8 900 000"`, 0 }, "candidate_profile_claims_contact_phone_value"}, + {"telegram without the at sign", func(c *claim) { c.kind, c.value, c.ordinal = "contact_telegram", `"anna"`, 0 }, "candidate_profile_claims_contact_telegram_value"}, + {"relocation that is not a boolean", func(c *claim) { c.kind, c.value, c.ordinal = "terms_relocation", `"yes"`, 0 }, "candidate_profile_claims_terms_relocation_value"}, + {"salary that is not a multiple of 1000", func(c *claim) { + c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180500,"currency":"RUB","period":"month","tax_basis":"net"}`, 0 + }, "candidate_profile_claims_terms_salary_minimum_value"}, + {"salary in another currency", func(c *claim) { + c.kind, c.value, c.ordinal = "terms_salary_minimum", `{"amount":180000,"currency":"USD","period":"month","tax_basis":"net"}`, 0 + }, "candidate_profile_claims_terms_salary_minimum_value"}, + {"role with a confirmed grade key", func(c *claim) { + c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":null,"confirmed_grade":"senior"}`, 0 + }, "candidate_profile_claims_role_value"}, + {"role with an unknown grade", func(c *claim) { + c.kind, c.value, c.ordinal = "role", `{"specialization":"backend","self_assessed_grade":"lead"}`, 0 + }, "candidate_profile_claims_role_value"}, + {"experience that ends before it starts", func(c *claim) { + c.kind, c.ordinal = "experience", 0 + c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-05","ended_on":"2024-04","summary":null}` + }, "candidate_profile_claims_experience_value"}, + {"experience month out of range", func(c *claim) { + c.kind, c.ordinal = "experience", 0 + c.value = `{"employer_name":null,"specialization":"qa","started_on":"2024-13","ended_on":null,"summary":null}` + }, "candidate_profile_claims_experience_value"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + c := good + test.mutate(&c) + err := fixture.insertRaw(candidate.ID, c.kind, c.ordinal, c.value, c.status, c.origin, c.trust, c.quote, c.extraction, c.confirmed) + assertConstraintViolation(t, err, "23514", test.constraint) + }) + } + + // The same row without the mutation is accepted, so each refusal + // above comes from its own rule. + if err := fixture.insertRaw(candidate.ID, good.kind, good.ordinal, good.value, good.status, good.origin, 0, nil, nil, true); err != nil { + t.Fatalf("insert of the valid claim error = %v", err) + } + }) + + t.Run("a tag, a skill, and a role specialization are stored once", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0) + insert := func(kind string, ordinal int, value string) error { + return fixture.insertRaw(candidate.ID, kind, ordinal, value, "confirmed", "manual", 0, nil, nil, true) + } + if err := insert("stack", 0, `"Go"`); err != nil { + t.Fatalf("insert tag error = %v", err) + } + assertConstraintViolation(t, insert("stack", 1, `"Go"`), "23505", "candidate_profile_claims_stack_key") + if err := insert("soft_skill", 0, `"Mentoring"`); err != nil { + t.Fatalf("insert skill error = %v", err) + } + assertConstraintViolation(t, insert("soft_skill", 1, `"Mentoring"`), "23505", "candidate_profile_claims_soft_skill_key") + if err := insert("role", 0, `{"specialization":"backend","self_assessed_grade":null}`); err != nil { + t.Fatalf("insert role error = %v", err) + } + assertConstraintViolation(t, insert("role", 1, `{"specialization":"backend","self_assessed_grade":"junior"}`), "23505", "candidate_profile_claims_role_specialization_key") + assertConstraintViolation(t, insert("role", 0, `{"specialization":"qa","self_assessed_grade":null}`), "23505", "candidate_profile_claims_pkey") + }) + + t.Run("a profile needs an account and claims need a profile", func(t *testing.T) { + reset(t) + err := fixture.insertRawProfile(uuid.Must(uuid.NewV7()), 1) + assertConstraintViolation(t, err, "23503", "candidate_profiles_user_id_fkey") + + candidate := fixture.candidate(t, "candidate@example.com") + assertConstraintViolation(t, fixture.insertRawProfile(candidate.ID, 0), "23514", "candidate_profiles_version_positive") + err = fixture.insertRaw(candidate.ID, "full_name", 0, `"Anna"`, "confirmed", "manual", 0, nil, nil, true) + assertConstraintViolation(t, err, "23503", "candidate_profile_claims_user_id_fkey") + }) + + t.Run("erasing the account removes the profile and its claims", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + fixture.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision("Anna"), Phone: confirmedDecision("+79000000000"), + }, 0) + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, candidate.ID); err != nil { + t.Fatalf("delete the account: %v", err) + } + for _, table := range candidateProfileTables { + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM `+table.Sanitize()).Scan(&count); err != nil || count != 0 { + t.Fatalf("%s rows after the erasure = %d, %v, want 0", table[0], count, err) + } + } + }) + + t.Run("the version guards against a lost concurrent edit", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0) + + // A second first save loses: the row exists. + if _, err := fixture.queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)}); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("second InsertCandidateProfile() error = %v, want no row", err) + } + // A stale expected version matches no row. + stale := sqlc.AdvanceCandidateProfileVersionParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 7, At: pgTime(now)} + if _, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, stale); !errors.Is(err, pgx.ErrNoRows) { + t.Fatalf("AdvanceCandidateProfileVersion(stale) error = %v, want no row", err) + } + if got := fixture.load(t, candidate.ID).Version(); got != 1 { + t.Fatalf("version after a stale advance = %d, want 1", got) + } + + // Eight savers read version 1 and race: exactly one wins. + pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves) + queries := sqlc.New(pool) + var ( + group sync.WaitGroup + mutex sync.Mutex + winners int + ) + for range concurrentProfileSaves { + group.Go(func() { + _, err := queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{ + UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(time.Minute)), + }) + mutex.Lock() + defer mutex.Unlock() + switch { + case err == nil: + winners++ + case !errors.Is(err, pgx.ErrNoRows): + t.Errorf("AdvanceCandidateProfileVersion() error = %v", err) + } + }) + } + group.Wait() + if winners != 1 { + t.Fatalf("%d concurrent saves advanced version 1, want exactly one", winners) + } + if got := fixture.load(t, candidate.ID).Version(); got != 2 { + t.Fatalf("version after the race = %d, want 2", got) + } + }) + + t.Run("two concurrent first saves: one wins and the other sees a conflict", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + pool := env.newPoolWithMaxConns(ctx, t, concurrentProfileSaves) + queries := sqlc.New(pool) + var ( + group sync.WaitGroup + mutex sync.Mutex + winners int + losers int + ) + for range concurrentProfileSaves { + group.Go(func() { + _, err := queries.InsertCandidateProfile(ctx, sqlc.InsertCandidateProfileParams{UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, At: pgTime(now)}) + mutex.Lock() + defer mutex.Unlock() + switch { + case err == nil: + winners++ + case errors.Is(err, pgx.ErrNoRows): + losers++ // the caller answers version_conflict + default: + t.Errorf("InsertCandidateProfile() error = %v", err) + } + }) + } + group.Wait() + if winners != 1 || losers != concurrentProfileSaves-1 { + t.Fatalf("first saves: %d won and %d lost, want one winner and the rest conflicts", winners, losers) + } + }) + + t.Run("an earlier application clock never violates the update time rule", func(t *testing.T) { + reset(t) + candidate := fixture.candidate(t, "candidate@example.com") + fixture.save(t, candidate.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Anna")}, 0) + advanced, err := fixture.queries.AdvanceCandidateProfileVersion(ctx, sqlc.AdvanceCandidateProfileVersionParams{ + UserID: pgtype.UUID{Bytes: candidate.ID, Valid: true}, ExpectedVersion: 1, At: pgTime(now.Add(-time.Hour)), + }) + if err != nil { + t.Fatalf("AdvanceCandidateProfileVersion(earlier time) error = %v, want no CHECK violation", err) + } + if advanced.Version != 2 || !advanced.UpdatedAt.Time.Equal(now) { + t.Fatalf("advanced = version %d at %v, want version 2 keeping %v", advanced.Version, advanced.UpdatedAt.Time, now) + } + }) + + t.Run("each account keeps its own profile", func(t *testing.T) { + reset(t) + first := fixture.candidate(t, "first@example.com") + second := fixture.candidate(t, "second@example.com") + fixture.save(t, first.ID, domain.CandidateProfileInput{FullName: confirmedDecision("First Person")}, 0) + fixture.save(t, second.ID, domain.CandidateProfileInput{FullName: confirmedDecision("Second Person")}, 0) + name, _ := fixture.load(t, second.ID).Content().FullName() + if name.Value() != "Second Person" { + t.Fatal("an account read the profile of another account") + } + }) +} + +func TestCandidateProfileMigrationRollsBack(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidateProfileTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + assertTablesExist(ctx, t, pool, true, "candidate_profiles", "candidate_profile_claims") + for { + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() error = %v", err) + } + if result.Version == candidateProfileMigrationVersion { + break + } + } + assertTablesExist(ctx, t, pool, false, "candidate_profiles", "candidate_profile_claims") + assertTablesExist(ctx, t, pool, true, "users") +} + +func confirmedDecision[V comparable](value V) *domain.ProfileClaimInput[V] { + return &domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed} +} + +func pgTime(at time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: at, Valid: true} } + +func (fixture candidateProfileFixture) candidate(t *testing.T, email string) domain.User { + t.Helper() + return fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.now.Add(-time.Hour)) +} + +// save applies input to the stored profile with the domain rules and stores +// the result the way a repository does: a first save inserts version 1, and a +// later one advances the version over expectedVersion and replaces the +// claims, in one transaction. +func (fixture candidateProfileFixture) save(t *testing.T, userID uuid.UUID, input domain.CandidateProfileInput, expectedVersion int64) domain.CandidateProfile { + t.Helper() + profile := fixture.loadOrEmpty(t, userID) + if profile.Version() != expectedVersion { + t.Fatalf("stored version = %d, want %d", profile.Version(), expectedVersion) + } + updated, _, err := profile.Replace(input, expectedVersion, fixture.now) + if err != nil { + t.Fatalf("Replace() error = %v", err) + } + rows, err := updated.Content().StoredClaims() + if err != nil { + t.Fatalf("StoredClaims() error = %v", err) + } + + tx, err := fixture.pool.Begin(fixture.ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = tx.Rollback(fixture.ctx) }() + queries := fixture.queries.WithTx(tx) + id := pgtype.UUID{Bytes: userID, Valid: true} + if expectedVersion == 0 { + _, err = queries.InsertCandidateProfile(fixture.ctx, sqlc.InsertCandidateProfileParams{UserID: id, At: pgTime(fixture.now)}) + } else { + _, err = queries.AdvanceCandidateProfileVersion(fixture.ctx, sqlc.AdvanceCandidateProfileVersionParams{UserID: id, ExpectedVersion: expectedVersion, At: pgTime(fixture.now)}) + } + if err != nil { + t.Fatalf("store the profile row: %v", err) + } + if err := queries.DeleteCandidateProfileClaims(fixture.ctx, id); err != nil { + t.Fatalf("delete claims: %v", err) + } + for _, row := range rows { + err := queries.InsertCandidateProfileClaim(fixture.ctx, sqlc.InsertCandidateProfileClaimParams{ + UserID: id, Kind: row.Kind, Ordinal: int16(row.Ordinal), Value: row.Value, Status: row.Status, Origin: row.Origin, + Quote: optionalText(row.Quote), ExtractionVersion: optionalText(row.ExtractionVersion), ConfirmedAt: optionalTime(row.ConfirmedAt), + }) + if err != nil { + t.Fatalf("insert claim %s: %v", row.Kind, err) + } + } + if err := tx.Commit(fixture.ctx); err != nil { + t.Fatalf("commit: %v", err) + } + return fixture.load(t, userID) +} + +func optionalText(value string) pgtype.Text { return pgtype.Text{String: value, Valid: value != ""} } + +func optionalTime(value time.Time) pgtype.Timestamptz { + return pgtype.Timestamptz{Time: value, Valid: !value.IsZero()} +} + +// loadOrEmpty reads the profile with the one statement a repository uses, so +// the version and the claims come from one snapshot. An account without a +// profile gets the empty profile of version 0. +func (fixture candidateProfileFixture) loadOrEmpty(t *testing.T, userID uuid.UUID) domain.CandidateProfile { + t.Helper() + rows, err := fixture.queries.ReadCandidateProfile(fixture.ctx, pgtype.UUID{Bytes: userID, Valid: true}) + if err != nil { + t.Fatalf("ReadCandidateProfile() error = %v", err) + } + if len(rows) == 0 { + empty, err := domain.EmptyCandidateProfile(userID) + if err != nil { + t.Fatalf("EmptyCandidateProfile() error = %v", err) + } + return empty + } + stored := domain.StoredCandidateProfile{UserID: userID, Version: rows[0].Version, CreatedAt: rows[0].CreatedAt.Time, UpdatedAt: rows[0].UpdatedAt.Time} + for _, row := range rows { + if !row.Kind.Valid { + continue // a profile without claims: the LEFT JOIN row has none + } + stored.Claims = append(stored.Claims, domain.StoredProfileClaim{ + Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: row.Value, Status: row.Status.String, Origin: row.Origin.String, + TrustLevel: int(row.TrustLevel.Int16), Quote: row.Quote.String, ExtractionVersion: row.ExtractionVersion.String, + ConfirmedAt: row.ConfirmedAt.Time, + }) + } + profile, err := domain.RestoreCandidateProfile(stored) + if err != nil { + t.Fatalf("RestoreCandidateProfile() error = %v", err) + } + return profile +} + +func (fixture candidateProfileFixture) load(t *testing.T, userID uuid.UUID) domain.CandidateProfile { + t.Helper() + profile := fixture.loadOrEmpty(t, userID) + if profile.Version() == 0 { + t.Fatal("the account has no stored profile") + } + return profile +} + +// insertSuggestion stores an unconfirmed claim of an import, which no +// operation produces yet, over the stored one of the same kind and position. +func (fixture candidateProfileFixture) insertSuggestion(t *testing.T, userID uuid.UUID, kind string, ordinal int, value string) { + t.Helper() + quote, version := "Tel.: +7 900 000-11-11", "resume-rules.2026-10.1" + if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM candidate_profile_claims WHERE user_id = $1 AND kind = $2 AND ordinal = $3`, userID, kind, ordinal); err != nil { + t.Fatalf("remove the stored claim: %v", err) + } + if err := fixture.insertRaw(userID, kind, ordinal, value, "extracted", "extracted_from_resume", 0, "e, &version, false); err != nil { + t.Fatalf("insert the suggestion: %v", err) + } +} + +func (fixture candidateProfileFixture) insertRaw( + userID uuid.UUID, kind string, ordinal int, value, status, origin string, trust int, quote, extraction *string, confirmed bool, +) error { + var confirmedAt any + if confirmed { + confirmedAt = fixture.now + } + _, err := fixture.pool.Exec(fixture.ctx, ` + INSERT INTO candidate_profile_claims + (user_id, kind, ordinal, value, status, origin, trust_level, quote, extraction_version, confirmed_at) + VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, $10)`, + userID, kind, ordinal, value, status, origin, trust, quote, extraction, confirmedAt) + return err +} + +func (fixture candidateProfileFixture) insertRawProfile(userID uuid.UUID, version int64) error { + _, err := fixture.pool.Exec(fixture.ctx, + `INSERT INTO candidate_profiles (user_id, version, created_at, updated_at) VALUES ($1, $2, $3, $3)`, + userID, version, fixture.now) + return err +} + +// assertConstraintViolation checks the SQLSTATE and the constraint name, never +// the message: a failing row can quote the personal data it held. PostgreSQL +// reports the first failing CHECK in name order, so a row that breaks two +// rules names the one that sorts first; a caller lists the acceptable ones. +func assertConstraintViolation(t *testing.T, err error, code string, constraints ...string) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) { + t.Fatalf("error = %v, want a PostgreSQL error %s on %v", err, code, constraints) + } + if pgError.Code != code || !slices.Contains(constraints, pgError.ConstraintName) { + t.Fatalf("error = %s on %q, want %s on one of %v", pgError.Code, pgError.ConstraintName, code, constraints) + } +} diff --git a/backend/integration_test/company_context_test.go b/backend/integration_test/company_context_test.go new file mode 100644 index 0000000..cb12239 --- /dev/null +++ b/backend/integration_test/company_context_test.go @@ -0,0 +1,265 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "lincodex/backend/internal/domain" +) + +func TestCompanyContextChecksLiveOwnerMembershipAndListsOwnOrganizations(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout) + defer cancel() + harness := newOrganizationHTTPHarness(ctx, t, env) + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + owner := createOrganizationHTTPUser(ctx, t, harness, "company-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreignOwner := createOrganizationHTTPUser(ctx, t, harness, "company-foreign-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + recruiter := createOrganizationHTTPUser(ctx, t, harness, "company-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidate := createOrganizationHTTPUser(ctx, t, harness, "company-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreignOwner.Email.Address()) + recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + + organizationA := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a") + organizationA2 := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "company-context-a2") + organizationB := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, foreignSession, "company-context-b") + insertOrganizationHTTPMembership(ctx, t, harness, organizationA, recruiter.ID, "recruiter", "active", now) + insertOrganizationHTTPMembership(ctx, t, harness, organizationA, candidate.ID, "owner", "active", now) + + ownerRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "") + if ownerRead.Code != http.StatusOK { + t.Fatalf("owner read = %d %s, want 200", ownerRead.Code, ownerRead.Body.String()) + } + for _, test := range []struct { + name string + session organizationHTTPSession + want int + }{ + {name: "foreign company", session: foreignSession, want: http.StatusNotFound}, + {name: "recruiter membership", session: recruiterSession, want: http.StatusForbidden}, + {name: "candidate with manually inserted owner membership", session: candidateSession, want: http.StatusForbidden}, + } { + t.Run(test.name, func(t *testing.T) { + response := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", test.session, "") + if response.Code != test.want { + t.Fatalf("company read = %d %s, want %d", response.Code, response.Body.String(), test.want) + } + assertNoCompanyDetails(t, response) + }) + } + childForeign := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", foreignSession, "") + if childForeign.Code != http.StatusNotFound { + t.Fatalf("foreign owner on tenant needs route = %d %s, want 404 before fallback", childForeign.Code, childForeign.Body.String()) + } + assertNoCompanyDetails(t, childForeign) + childOwner := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "") + if childOwner.Code != http.StatusNotImplemented { + t.Fatalf("owner on currently unimplemented needs route = %d %s, want guarded 501 fallback", childOwner.Code, childOwner.Body.String()) + } + candidateHide := organizationHTTPRequest(t, harness, http.MethodPut, + "/api/v1/me/privacy/hidden-organizations/"+organizationA.String(), "", env.Config.AppPublicURL, candidateSession, "") + if candidateHide.Code != http.StatusNotImplemented { + t.Fatalf("candidate-owned hiding route = %d %s, want its own 501 fallback", candidateHide.Code, candidateHide.Body.String()) + } + assertNoCompanyDetails(t, candidateHide) + + firstPage := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations?limit=1", http.StatusOK) + if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" { + t.Fatalf("first organization page = %+v, want one item and a next cursor", firstPage) + } + if firstPage.Items[0].Membership.Role != "owner" || firstPage.Items[0].Membership.State != "active" { + t.Fatalf("owner directory membership = %+v, want active owner", firstPage.Items[0].Membership) + } + secondPage := readOrganizationDirectory(t, harness, ownerSession, + "/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), http.StatusOK) + if len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil { + t.Fatalf("second organization page = %+v, want one last item", secondPage) + } + if firstPage.Items[0].Organization.ID == secondPage.Items[0].Organization.ID { + t.Fatal("organization directory repeated an item across pages") + } + for _, item := range []organizationDirectoryItem{firstPage.Items[0], secondPage.Items[0]} { + if item.Organization.ID != organizationA.String() && item.Organization.ID != organizationA2.String() { + t.Fatalf("owner directory exposed another account's organization %s", item.Organization.ID) + } + } + foreignCursor := organizationHTTPRequest(t, harness, http.MethodGet, + "/api/v1/me/organizations?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", "", foreignSession, "") + requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed") + foreignDirectory := readOrganizationDirectory(t, harness, foreignSession, "/api/v1/me/organizations", http.StatusOK) + if len(foreignDirectory.Items) != 1 || foreignDirectory.Items[0].Organization.ID != organizationB.String() { + t.Fatalf("foreign owner's directory = %+v, want only %s", foreignDirectory.Items, organizationB) + } + recruiterDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK) + if len(recruiterDirectory.Items) != 1 || recruiterDirectory.Items[0].Membership.Role != "recruiter" { + t.Fatalf("recruiter's directory = %+v, want its active recruiter membership", recruiterDirectory.Items) + } + candidateDirectory := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/me/organizations", "", "", candidateSession, "") + requireSessionProblem(t, candidateDirectory, http.StatusForbidden, "forbidden") + assertNoCompanyDetails(t, candidateDirectory) + + if _, err := harness.pool.Exec(ctx, + "UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3", + now.Add(time.Second), organizationA, recruiter.ID, + ); err != nil { + t.Fatalf("revoke recruiter membership: %v", err) + } + revokedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationA.String(), "", "", recruiterSession, "") + requireSessionProblem(t, revokedRead, http.StatusNotFound, "not_found") + revokedDirectory := readOrganizationDirectory(t, harness, recruiterSession, "/api/v1/me/organizations", http.StatusOK) + if len(revokedDirectory.Items) != 0 { + t.Fatalf("directory with the same cookie after revocation = %+v, want empty", revokedDirectory.Items) + } + + if _, err := harness.pool.Exec(ctx, + "UPDATE memberships SET state = 'removed', updated_at = $1 WHERE organization_id = $2 AND user_id = $3", + now.Add(2*time.Second), organizationA, owner.ID, + ); err != nil { + t.Fatalf("revoke owner membership: %v", err) + } + revokedOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet, + "/api/v1/organizations/"+organizationA.String(), "", "", ownerSession, "") + requireSessionProblem(t, revokedOwnerRead, http.StatusNotFound, "not_found") + assertNoCompanyDetails(t, revokedOwnerRead) + revokedOwnerChild := organizationHTTPRequest(t, harness, http.MethodGet, + "/api/v1/organizations/"+organizationA.String()+"/needs", "", "", ownerSession, "") + if revokedOwnerChild.Code != http.StatusNotFound { + t.Fatalf("same owner cookie after revocation on tenant route = %d %s, want 404", revokedOwnerChild.Code, revokedOwnerChild.Body.String()) + } + assertNoCompanyDetails(t, revokedOwnerChild) + remainingOwnerRead := organizationHTTPRequest(t, harness, http.MethodGet, + "/api/v1/organizations/"+organizationA2.String(), "", "", ownerSession, "") + if remainingOwnerRead.Code != http.StatusOK { + t.Fatalf("same owner cookie for its remaining organization = %d %s, want 200", remainingOwnerRead.Code, remainingOwnerRead.Body.String()) + } + remainingOwnerDirectory := readOrganizationDirectory(t, harness, ownerSession, "/api/v1/me/organizations", http.StatusOK) + if len(remainingOwnerDirectory.Items) != 1 || remainingOwnerDirectory.Items[0].Organization.ID != organizationA2.String() { + t.Fatalf("owner directory after membership revocation = %+v, want only %s", remainingOwnerDirectory.Items, organizationA2) + } + for _, marker := range []string{ + owner.Email.Address(), foreignOwner.Email.Address(), recruiter.Email.Address(), candidate.Email.Address(), + "ООО Тестовая компания", + } { + if strings.Contains(harness.logs.String(), marker) { + t.Fatalf("company context logs contain account or profile data %q", marker) + } + } +} + +func createCompanyForContextTest( + t *testing.T, + harness *sessionHTTPHarness, + origin string, + session organizationHTTPSession, + idempotencyKey string, +) uuid.UUID { + t.Helper() + response := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", + "{\"name\":\"ООО Тестовая компания\",\"contacts\":{\"website\":\"https://company-context.example.test\",\"email\":\"careers@company-context.example.test\",\"phone\":\"+12025550123\",\"telegram\":\"@companycontext\"}}", + origin, session, idempotencyKey) + if response.Code != http.StatusCreated { + t.Fatalf("create test company = %d %s, want 201", response.Code, response.Body.String()) + } + var company struct { + ID uuid.UUID `json:"id"` + } + if err := json.Unmarshal(response.Body.Bytes(), &company); err != nil { + t.Fatalf("decode test company: %v", err) + } + return company.ID +} + +func assertNoCompanyDetails(t *testing.T, response *httptest.ResponseRecorder) { + t.Helper() + body := response.Body.String() + for _, marker := range []string{ + "ООО Тестовая компания", + "company-context.example.test", + "careers@company-context.example.test", + "+12025550123", + "@companycontext", + } { + if strings.Contains(body, marker) { + t.Fatalf("denied company response contains company profile data %q", marker) + } + } +} + +func insertOrganizationHTTPMembership( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + organizationID uuid.UUID, + userID uuid.UUID, + role, state string, + at time.Time, +) { + t.Helper() + membershipID, err := uuid.NewV7() + if err != nil { + t.Fatalf("NewV7 membership ID: %v", err) + } + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $6) + `, membershipID, organizationID, userID, role, state, at); err != nil { + t.Fatalf("insert test company membership: %v", err) + } +} + +type organizationDirectoryResponse struct { + Items []organizationDirectoryItem `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +type organizationDirectoryItem struct { + Organization struct { + ID string `json:"id"` + } `json:"organization"` + Membership struct { + Role string `json:"role"` + State string `json:"state"` + } `json:"membership"` +} + +func readOrganizationDirectory( + t *testing.T, + harness *sessionHTTPHarness, + session organizationHTTPSession, + path string, + wantStatus int, +) organizationDirectoryResponse { + t.Helper() + response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "") + if response.Code != wantStatus { + t.Fatalf("organization directory = %d %s, want %d", response.Code, response.Body.String(), wantStatus) + } + var directory organizationDirectoryResponse + if err := json.Unmarshal(response.Body.Bytes(), &directory); err != nil { + t.Fatalf("decode organization directory: %v", err) + } + return directory +} diff --git a/backend/integration_test/company_isolation_http_test.go b/backend/integration_test/company_isolation_http_test.go new file mode 100644 index 0000000..8fa196c --- /dev/null +++ b/backend/integration_test/company_isolation_http_test.go @@ -0,0 +1,831 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + apiadapter "lincodex/backend/internal/adapter/primary/http/api" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/evidence" + invitationusecase "lincodex/backend/internal/usecase/invitation" + "lincodex/backend/internal/usecase/matching" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/organization" + profileusecase "lincodex/backend/internal/usecase/profile" +) + +const companyIsolationTimeout = 20 * time.Minute + +// companyIsolationCohort is the number of candidates with identical cards. A +// card is shown only in a group of at least five, and the scenarios take one +// candidate out of the group at a time, so six keep every card visible. +const companyIsolationCohort = 6 + +// companyIsolationHarness serves every operation of the minimal path that an +// organization or a candidate reads: the session, the consents, the profile, +// the assessment, the company and its needs, the search, the anonymous card +// and its evidence, the invitations with the contact read, the visibility +// settings, and both notification inboxes. The router mounts the company +// context middleware of the production wiring. +type companyIsolationHarness struct { + *assessmentAttemptHTTPHarness + + key domain.CandidateViewPseudonymKey +} + +func newCompanyIsolationHarness(ctx context.Context, t *testing.T, env *testEnvironment) *companyIsolationHarness { + t.Helper() + var key domain.CandidateViewPseudonymKey + var organizationHandler *v1.OrganizationHandler + harness := newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, + func(parts assessmentHarnessParts) []v1.HandlerOption { + var err error + if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + quota := companyquota.NewService(parts.clock.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: parts.transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now), + PseudonymKey: key, Clock: parts.clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needusecase.Dependencies{ + Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now, + }) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + search, err := matching.NewService(matching.Dependencies{ + Transactor: parts.transactor, Cards: views.ListVisibleCards, Clock: parts.clock.Now, + Views: func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) { + session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID) + if err != nil { + return nil, err + } + return session, nil + }, + }) + if err != nil { + t.Fatalf("matching.NewService() error = %v", err) + } + evidenceService, err := evidence.NewService(evidence.Dependencies{ + Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection, + }) + if err != nil { + t.Fatalf("evidence.NewService() error = %v", err) + } + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(templates), parts.clock.Now)) + if err != nil { + t.Fatalf("NewInvitationNotifier() error = %v", err) + } + invitations, err := invitationusecase.NewService(invitationusecase.Dependencies{ + Transactor: parts.transactor, Keyring: parts.keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveInvitation(ctx, unit, organization, invitationID) + }, + Notifier: notifier, Consents: consent.NewService(parts.transactor, parts.clock.Now), Clock: parts.clock.Now, + }) + if err != nil { + t.Fatalf("invitation.NewService() error = %v", err) + } + // The synthetic notice is the only producer of an employer's inbox + // item today, so its resolver is on. + inbox, err := notification.NewInboxService(parts.transactor, + notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(true)), parts.clock.Now) + if err != nil { + t.Fatalf("notification.NewInboxService() error = %v", err) + } + organizationHandler = v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + return []v1.HandlerOption{ + v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)), + v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)), + v1.WithProfile(v1.NewProfileHandler(profileusecase.NewService(parts.transactor, parts.clock.Now))), + v1.WithOrganization(organizationHandler), + v1.WithNeed(v1.NewNeedHandler(needService)), + v1.WithMatches(v1.NewMatchHandler(search)), + v1.WithInvitation(v1.NewInvitationHandler(invitations)), + v1.WithNotifications(v1.NewNotificationHandler(inbox)), + } + }, + func() []apiadapter.Middleware { + return []apiadapter.Middleware{httpadapter.NewCompanyContextMiddleware(organizationHandler)} + }) + return &companyIsolationHarness{assessmentAttemptHTTPHarness: harness, key: key} +} + +// isolationCandidate is a candidate of the scenario with the private values +// that no organization may read before an accepted grant, and no log, event, +// or notification may carry. +type isolationCandidate struct { + categoryHTTPCandidate + + phone, fullName, employer, location string +} + +func (candidate isolationCandidate) privateValues() []string { + return []string{candidate.email, candidate.phone, candidate.fullName, candidate.employer, candidate.location} +} + +// isolationCall is one request of a walk with the status that the contract +// gives it. +type isolationCall struct { + name string + method, path string + body string + status int + code string +} + +// TestCompanyIsolationAndRevocationOverHTTP is the acceptance walk of the +// company isolation, the revocation, and the projections of the minimal path. +// +// Company A runs the whole path: a need, a search, a card and its evidence, +// an invitation accepted with C4, the contact read, and an inbox item. Company +// B then calls every organization-scoped operation of the contract with its +// own valid session, once on the path of A and once on its own path with the +// identifiers that A's responses named, and each call answers the documented +// refusal, the same as for an identifier that does not exist. Candidates call +// the candidate-scoped operations with the identifiers of another candidate. +// The revocation scenarios check that hiding the organization, revoking C4, +// and withdrawing C2 close the next read at once through the handles of an +// earlier search, the invitation page, and the contact read, and that neither +// a new publication nor a new C2 revives a grant that C4 revocation closed. +// Finally the server log, the outbox, the inbox rows, and the stored email +// requests are scanned for the private values of the candidates. +func TestCompanyIsolationAndRevocationOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), companyIsolationTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newCompanyIsolationHarness(ctx, t, &isolatedEnv) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV4(), true) + threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) + // The policy takes effect when it is stored, which is after the clock of + // the harness was read. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) + client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} + transactor := postgresadapter.NewTransactor(harness.pool) + consumers := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL) + + do := func(who categoryHTTPCandidate, method, path, body string) *httptest.ResponseRecorder { + t.Helper() + key := "" + if method != http.MethodGet { + key = uuid.NewString() + } + return assessmentAttemptHTTPRequest(t, harness.assessmentAttemptHTTPHarness, method, path, body, sessionHTTPTestOrigin, + who.cookie, who.csrf, key, client.remote()) + } + must := func(who categoryHTTPCandidate, method, path, body string, want int) *httptest.ResponseRecorder { + t.Helper() + response := do(who, method, path, body) + if response.Code != want { + t.Fatalf("%s %s = %d %s, want %d", method, path, response.Code, response.Body.String(), want) + } + return response + } + decode := func(response *httptest.ResponseRecorder, target any) { + t.Helper() + if err := json.Unmarshal(response.Body.Bytes(), target); err != nil { + t.Fatalf("decode %s: %v", response.Body.String(), err) + } + } + requireNoStore := func(label string, response *httptest.ResponseRecorder) { + t.Helper() + if cache := response.Header().Get("Cache-Control"); cache != "no-store" { + t.Fatalf("%s Cache-Control = %q, want no-store", label, cache) + } + } + + // --- Candidates: a confirmed category, a profile with private values, C2, + // and the same published card. + publishedFields := `["categories","stack","experience","self_assessment","work_formats"]` + candidates := make([]isolationCandidate, 0, companyIsolationCohort) + for index := range companyIsolationCohort { + base := client.candidate(t, fmt.Sprintf("isolation-candidate-%d@example.test", index)) + run := client.run(t, base, "backend", "intern", func(int) int { return threshold }) + if run.result["outcome"] != "confirmed" { + t.Fatalf("assessment of candidate %d = %v, want confirmed", index, run.result["outcome"]) + } + candidate := isolationCandidate{ + categoryHTTPCandidate: base, + phone: fmt.Sprintf("+7999000%04d", index), + fullName: fmt.Sprintf("Isolation Secret Name %d", index), + employer: fmt.Sprintf("Isolation Secret Employer %d", index), + location: fmt.Sprintf("Isolation Secret Location %d", index), + } + profile, err := json.Marshal(map[string]any{ + "expected_version": 0, + "full_name": map[string]any{"value": candidate.fullName, "status": "confirmed"}, + "contacts": map[string]any{ + "email": map[string]any{"value": candidate.email, "status": "confirmed"}, + "phone": map[string]any{"value": candidate.phone, "status": "confirmed"}, + "telegram": nil, + }, + "stack": []any{map[string]any{"tag": "go", "status": "confirmed"}}, + "roles": []any{map[string]any{"specialization": "backend", "self_assessed_grade": "junior", "status": "confirmed"}}, + "experience": []any{map[string]any{ + "employer_name": candidate.employer, "specialization": "backend", "started_on": "2020-01", + "ended_on": "2023-12", "summary": "Isolation Secret Summary", "status": "confirmed", + }}, + "confirmed_parallel_periods": []any{}, "soft_skills": []any{}, + "terms": map[string]any{ + "location": map[string]any{"value": candidate.location, "status": "confirmed"}, "relocation": nil, + "salary_minimum": map[string]any{"value": map[string]any{ + "amount": 120000, "currency": "RUB", "period": "month", "tax_basis": "net", + }, "status": "confirmed"}, + }, + }) + if err != nil { + t.Fatalf("marshal profile: %v", err) + } + must(base, http.MethodPut, "/api/v1/me/profile", string(profile), http.StatusOK) + must(base, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK) + must(base, http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":0,"state":"published","fields":%s}`, publishedFields), http.StatusOK) + candidates = append(candidates, candidate) + } + subject, neighbour, drafted := candidates[0], candidates[1], candidates[2] + + // Every private value and internal identifier of the candidates. The + // organization side, the logs, and the events must carry none of them. + privateValues := make([]string, 0, len(candidates)*5+1) + candidateIDs := make([]string, 0, len(candidates)) + for _, candidate := range candidates { + privateValues = append(privateValues, candidate.privateValues()...) + candidateIDs = append(candidateIDs, candidate.id.String()) + } + privateValues = append(privateValues, "Isolation Secret Summary") + requireNoCandidateValues := func(label, text string, withIDs bool) { + t.Helper() + values := privateValues + if withIDs { + values = append(slices.Clone(values), candidateIDs...) + } + for _, value := range values { + if strings.Contains(text, value) { + t.Fatalf("%s carries the private value %q: %s", label, value, text) + } + } + } + + // --- Two companies, each with its own owner. + ownerA := client.employer(t, "isolation-owner-a@example.test") + ownerB := client.employer(t, "isolation-owner-b@example.test") + const nameA = "Isolation Company Alpha" + createOrganization := func(owner categoryHTTPCandidate, name string) uuid.UUID { + t.Helper() + response := must(owner, http.MethodPost, "/api/v1/organizations", + fmt.Sprintf(`{"name":%q,"contacts":{"website":"https://isolation.example.test","email":"careers@isolation.example.test","phone":"+12025550123","telegram":"@isolationcompany"}}`, name), + http.StatusCreated) + var created struct { + ID uuid.UUID `json:"id"` + } + decode(response, &created) + return created.ID + } + orgA := createOrganization(ownerA, nameA) + orgB := createOrganization(ownerB, "Isolation Company Beta") + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) + orgPath := func(organizationID uuid.UUID, suffix string) string { + return fmt.Sprintf("/api/v1/organizations/%s%s", organizationID, suffix) + } + + // --- Company A runs the path and collects the identifiers of its objects. + const needTitle = "Isolation payments backend need" + var need struct { + ID uuid.UUID `json:"id"` + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + decode(must(ownerA, http.MethodPost, orgPath(orgA, "/needs"), + fmt.Sprintf(`{"title":%q,"specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Go","status":"confirmed"}]}`, needTitle), + http.StatusCreated), &need) + needSearch := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d}`, need.ID, need.RequirementsVersion) + bankSearch := `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}` + search := func(owner categoryHTTPCandidate, organizationID uuid.UUID, body string) matchSearchBody { + t.Helper() + response := must(owner, http.MethodPost, orgPath(organizationID, "/matches"), body, http.StatusOK) + requireNoStore("search", response) + requireNoCandidateValues("search result", response.Body.String(), true) + var result matchSearchBody + decode(response, &result) + return result + } + // The handles of this first result are the stored search result that the + // later scenarios reuse after the visibility changes. + firstSearch := search(ownerA, orgA, needSearch) + aliasA := func(candidate isolationCandidate) string { + t.Helper() + alias, err := harness.key.ForOrganization(orgA, candidate.id) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return alias + } + subjectHandle := aliasA(subject) + if _, found := firstSearch.handles()[subjectHandle+"/backend"]; !found { + t.Fatalf("first search of A = %v, want the subject among the results", firstSearch.handles()) + } + cardPath := orgPath(orgA, "/candidate-cards/"+subjectHandle) + card := must(ownerA, http.MethodGet, cardPath, "", http.StatusOK) + requireNoStore("card", card) + requireNoCandidateValues("anonymous card", card.Body.String(), true) + evidenceRead := must(ownerA, http.MethodGet, cardPath+"/evidence", "", http.StatusOK) + requireNoStore("evidence", evidenceRead) + requireNoCandidateValues("card evidence", evidenceRead.Body.String(), true) + + createDraft := func(owner categoryHTTPCandidate, organizationID uuid.UUID, handle string) invitationHTTPBody { + t.Helper() + return decodeInvitationHTTP(t, do(owner, http.MethodPost, orgPath(organizationID, "/invitations"), invitationCreateJSON(t, handle, nil)), http.StatusCreated) + } + sendDraft := func(owner categoryHTTPCandidate, organizationID uuid.UUID, draft invitationHTTPBody) invitationHTTPBody { + t.Helper() + return decodeInvitationHTTP(t, do(owner, http.MethodPost, orgPath(organizationID, "/invitations/"+draft.ID.String()+"/send"), + fmt.Sprintf(`{"expected_version":%d}`, draft.Version)), http.StatusOK) + } + accept := func(candidate isolationCandidate, invitation invitationHTTPBody, fields ...string) candidateContactGrantHTTP { + t.Helper() + encoded, err := json.Marshal(map[string]any{ + "expected_version": invitation.Version, "terms_version": invitation.TermsVersion, + "consent_c4": map[string]any{"text_version": acceptTextVersion, "accepted": true, "fields": fields}, + }) + if err != nil { + t.Fatalf("marshal acceptance: %v", err) + } + accepted := decodeCandidateInvitationHTTP(t, do(candidate.categoryHTTPCandidate, http.MethodPost, + "/api/v1/me/invitations/"+invitation.ID.String()+"/accept", string(encoded)), http.StatusOK) + return decodeContactGrantHTTP(t, accepted) + } + contactsPath := func(organizationID, invitationID uuid.UUID) string { + return orgPath(organizationID, "/invitations/"+invitationID.String()+"/contacts") + } + accepted := sendDraft(ownerA, orgA, createDraft(ownerA, orgA, subjectHandle)) + firstGrant := accept(subject, accepted, "email", "phone") + contacts := must(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), "", http.StatusOK) + requireNoStore("contacts", contacts) + if !strings.Contains(contacts.Body.String(), subject.email) || !strings.Contains(contacts.Body.String(), subject.phone) { + t.Fatalf("contact read of A = %s, want the granted email and phone", contacts.Body.String()) + } + // A second invitation stays a draft, so B's changes would be visible on it. + draft := createDraft(ownerA, orgA, aliasA(drafted)) + + // The candidate's inbox item comes from the outbox event of the send, and + // the owner of A receives a synthetic notice: the only employer item today. + deliverEvent := func(where string, args ...any) { + t.Helper() + var event outbound.ConsumedEvent + var payload string + if err := harness.pool.QueryRow(ctx, ` + SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at + FROM outbox_events WHERE `+where, args...).Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, + &event.AggregateID, &event.AggregateVersion, &payload, &event.OccurredAt); err != nil { + t.Fatalf("read the outbox event: %v", err) + } + event.Payload = []byte(payload) + event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond) + if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) { + t.Fatalf("the inbox consumer did not apply %s", event.EventType) + } + } + deliverEvent(`event_type = 'invitation.delivered' AND aggregate_id = $1`, accepted.ID) + syntheticEvent := appendSyntheticNotice(ctx, t, transactor, ownerA.id, orgA, harness.clock.Now()) + if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, syntheticEvent) { + t.Fatal("the inbox consumer did not apply the synthetic notice") + } + onlyNotification := func(who categoryHTTPCandidate, path string) notificationBody { + t.Helper() + page := decodeNotificationPage(t, do(who, http.MethodGet, path, "")) + if len(page.Items) != 1 { + t.Fatalf("%s lists %d items, want one", path, len(page.Items)) + } + return page.Items[0] + } + ownerNotice := onlyNotification(ownerA, orgPath(orgA, "/notifications")) + subjectNotice := onlyNotification(subject.categoryHTTPCandidate, "/api/v1/me/notifications") + requireNoCandidateValues("candidate notification", do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/notifications", "").Body.String(), true) + + // readStateOfA is everything that a change by B would show up in. + type stateOfA struct { + organization, need, draft, accepted, contacts, notifications string + } + readStateOfA := func() stateOfA { + t.Helper() + read := func(path string) string { + t.Helper() + return must(ownerA, http.MethodGet, path, "", http.StatusOK).Body.String() + } + return stateOfA{ + organization: read(orgPath(orgA, "")), need: read(orgPath(orgA, "/needs/"+need.ID.String())), + draft: read(orgPath(orgA, "/invitations/"+draft.ID.String())), accepted: read(orgPath(orgA, "/invitations/"+accepted.ID.String())), + contacts: read(contactsPath(orgA, accepted.ID)), notifications: read(orgPath(orgA, "/notifications")), + } + } + before := readStateOfA() + + // withoutTrace drops the request-specific trace identifier of a problem, so + // two refusals can be compared byte for byte. + withoutTrace := func(response *httptest.ResponseRecorder) string { + t.Helper() + var body map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode problem %d %s: %v", response.Code, response.Body.String(), err) + } + delete(body, "trace_id") + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("encode problem: %v", err) + } + return string(encoded) + } + // walk runs every call as who and, for each call that names an object of + // another owner, the same call with a random identifier in its place: an + // existing object of someone else and a missing one answer the same. + walk := func(t *testing.T, who categoryHTTPCandidate, calls []isolationCall, hidden ...uuid.UUID) { + t.Helper() + for _, call := range calls { + response := do(who, call.method, call.path, call.body) + if response.Code != call.status { + t.Errorf("%s: %s %s = %d %s, want %d", call.name, call.method, call.path, response.Code, response.Body.String(), call.status) + continue + } + if call.code != "" { + requireSessionProblem(t, response, call.status, call.code) + } + text := response.Body.String() + requireNoCandidateValues(call.name, text, true) + for _, marker := range []string{nameA, needTitle, "isolation.example.test", "Middle Go developer in the payments team"} { + if strings.Contains(text, marker) { + t.Errorf("%s: the answer names %q of company A: %s", call.name, marker, text) + } + } + for _, id := range hidden { + if !strings.Contains(call.path, id.String()) && !strings.Contains(call.body, id.String()) { + continue + } + missing := do(who, call.method, + strings.ReplaceAll(call.path, id.String(), uuid.NewString()), + strings.ReplaceAll(call.body, id.String(), uuid.NewString())) + if missing.Code != response.Code || withoutTrace(missing) != withoutTrace(response) { + t.Errorf("%s: the object of A answers %d %s, a missing one %d %s; want the same refusal", + call.name, response.Code, withoutTrace(response), missing.Code, withoutTrace(missing)) + } + } + } + } + + t.Run("company B refuses every organization operation on the objects of A, as for objects that do not exist", func(t *testing.T) { + invitationBody := fmt.Sprintf(`{"expected_version":%d}`, draft.Version) + raiseBody := fmt.Sprintf(`{"expected_version":%d,"salary_to":150000}`, accepted.Version+1) + notFound := func(name, method, path, body string) isolationCall { + return isolationCall{name: name, method: method, path: path, body: body, status: http.StatusNotFound, code: "not_found"} + } + // On the path of A, B has no membership: the documented answer of every + // operation is 404 not_found, before the object is looked up. + onPathOfA := []isolationCall{ + notFound("read A", http.MethodGet, orgPath(orgA, ""), ""), + notFound("change A", http.MethodPatch, orgPath(orgA, ""), `{"expected_version":1,"name":"Hijacked by B"}`), + notFound("list needs of A", http.MethodGet, orgPath(orgA, "/needs"), ""), + notFound("create a need in A", http.MethodPost, orgPath(orgA, "/needs"), `{"title":"Need by B"}`), + notFound("read a need of A", http.MethodGet, orgPath(orgA, "/needs/"+need.ID.String()), ""), + notFound("change a need of A", http.MethodPatch, orgPath(orgA, "/needs/"+need.ID.String()), fmt.Sprintf(`{"expected_version":%d,"title":"Hijacked"}`, need.Version)), + notFound("search of A", http.MethodPost, orgPath(orgA, "/matches"), needSearch), + notFound("card of A", http.MethodGet, cardPath, ""), + notFound("evidence of A", http.MethodGet, cardPath+"/evidence", ""), + notFound("list invitations of A", http.MethodGet, orgPath(orgA, "/invitations"), ""), + notFound("draft in A", http.MethodPost, orgPath(orgA, "/invitations"), invitationCreateJSON(t, subjectHandle, nil)), + notFound("read an invitation of A", http.MethodGet, orgPath(orgA, "/invitations/"+accepted.ID.String()), ""), + notFound("change a draft of A", http.MethodPatch, orgPath(orgA, "/invitations/"+draft.ID.String()), invitationBody), + notFound("send a draft of A", http.MethodPost, orgPath(orgA, "/invitations/"+draft.ID.String()+"/send"), invitationBody), + notFound("withdraw an invitation of A", http.MethodPost, orgPath(orgA, "/invitations/"+draft.ID.String()+"/withdraw"), invitationBody), + notFound("raise the salary of A", http.MethodPost, orgPath(orgA, "/invitations/"+accepted.ID.String()+"/salary-raise"), raiseBody), + notFound("contacts of A", http.MethodGet, contactsPath(orgA, accepted.ID), ""), + notFound("notifications of A", http.MethodGet, orgPath(orgA, "/notifications"), ""), + notFound("mark a notification of A", http.MethodPost, orgPath(orgA, "/notifications/"+ownerNotice.ID.String()+"/read"), ""), + } + walk(t, ownerB, onPathOfA, orgA) + + // On its own path the caller is the owner, so each operation reaches + // the lookup of the object, which belongs to A: not found, as for a + // missing one. The candidate handle of A is no handle of another + // company, so a draft refuses it as a field, and a search refuses the + // need of A. Withdrawal and the salary raise are not implemented yet + // and answer 501 for any object. The same holds for B and for a second + // company of A's own owner in the same holding: the holding shares + // quotas, never objects. + orgA2 := createOrganization(ownerA, "Isolation Company Alpha Two") + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) + for _, foreign := range []struct { + label string + owner categoryHTTPCandidate + organization uuid.UUID + directory bool + }{ + {label: "B", owner: ownerB, organization: orgB, directory: true}, + {label: "a second company of the owner of A", owner: ownerA, organization: orgA2}, + } { + under := func(name string) string { return name + " under " + foreign.label } + path := func(suffix string) string { return orgPath(foreign.organization, suffix) } + calls := []isolationCall{ + notFound(under("a need of A"), http.MethodGet, path("/needs/"+need.ID.String()), ""), + notFound(under("change a need of A"), http.MethodPatch, path("/needs/"+need.ID.String()), fmt.Sprintf(`{"expected_version":%d,"title":"Hijacked"}`, need.Version)), + notFound(under("search by the need of A"), http.MethodPost, path("/matches"), needSearch), + notFound(under("card by a handle of A"), http.MethodGet, path("/candidate-cards/"+subjectHandle), ""), + notFound(under("evidence by a handle of A"), http.MethodGet, path("/candidate-cards/"+subjectHandle+"/evidence"), ""), + {name: under("draft for a handle of A"), method: http.MethodPost, path: path("/invitations"), + body: invitationCreateJSON(t, subjectHandle, nil), status: http.StatusBadRequest, code: "validation_failed"}, + notFound(under("an invitation of A"), http.MethodGet, path("/invitations/"+accepted.ID.String()), ""), + notFound(under("change a draft of A"), http.MethodPatch, path("/invitations/"+draft.ID.String()), invitationBody), + notFound(under("send a draft of A"), http.MethodPost, path("/invitations/"+draft.ID.String()+"/send"), invitationBody), + {name: under("withdraw an invitation of A"), method: http.MethodPost, path: path("/invitations/" + draft.ID.String() + "/withdraw"), + body: invitationBody, status: http.StatusNotImplemented, code: "not_implemented"}, + {name: under("raise the salary of A"), method: http.MethodPost, path: path("/invitations/" + accepted.ID.String() + "/salary-raise"), + body: raiseBody, status: http.StatusNotImplemented, code: "not_implemented"}, + notFound(under("contacts of A"), http.MethodGet, contactsPath(foreign.organization, accepted.ID), ""), + notFound(under("mark a notification of A"), http.MethodPost, path("/notifications/"+ownerNotice.ID.String()+"/read"), ""), + notFound(under("mark the candidate's notification"), http.MethodPost, path("/notifications/"+subjectNotice.ID.String()+"/read"), ""), + } + walk(t, foreign.owner, calls, need.ID, accepted.ID, draft.ID, ownerNotice.ID, subjectNotice.ID) + + // A draft cannot be linked to the need of A either. + linked := do(foreign.owner, http.MethodPost, path("/invitations"), invitationCreateJSON(t, aliasA(neighbour), func(body, _ map[string]any) { + body["need"] = map[string]any{"need_id": need.ID, "requirements_version": need.RequirementsVersion} + })) + if linked.Code != http.StatusBadRequest { + t.Errorf("draft %s linked to the need of A = %d %s, want 400", under(""), linked.Code, linked.Body.String()) + } + requireNoCandidateValues("linked draft", linked.Body.String(), true) + + // The lists show nothing of A. + lists := []string{path("/needs"), path("/invitations"), path("/notifications")} + if foreign.directory { + lists = append(lists, "/api/v1/me/organizations") + } + for _, list := range lists { + response := must(foreign.owner, http.MethodGet, list, "", http.StatusOK) + requireNoStore(list, response) + text := response.Body.String() + markers := []string{need.ID.String(), accepted.ID.String(), draft.ID.String(), ownerNotice.ID.String(), needTitle} + if foreign.directory { + markers = append(markers, orgA.String(), nameA) + } + for _, marker := range markers { + if strings.Contains(text, marker) { + t.Errorf("%s %s names %q of A: %s", list, under(""), marker, text) + } + } + requireNoCandidateValues(list, text, true) + } + // The company's own search reveals the cohort under its own handles. + for handle := range search(foreign.owner, foreign.organization, bankSearch).handles() { + if strings.HasPrefix(handle, subjectHandle) { + t.Errorf("the search %s returns the handle of A %s", under(""), subjectHandle) + } + } + } + // Nothing of A changed, the draft is still a draft, and the owner's + // notification is still unread. + if after := readStateOfA(); after != before { + t.Errorf("the calls of B changed the state of A:\nbefore %+v\nafter %+v", before, after) + } + }) + + t.Run("a candidate refuses every candidate operation on the objects of another candidate", func(t *testing.T) { + other := neighbour.categoryHTTPCandidate + command := fmt.Sprintf(`{"expected_version":%d}`, accepted.Version+1) + calls := []isolationCall{ + {name: "read the invitation of another candidate", method: http.MethodGet, path: "/api/v1/me/invitations/" + accepted.ID.String(), + status: http.StatusNotFound, code: "not_found"}, + {name: "open the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/view", + status: http.StatusNotFound, code: "not_found"}, + {name: "decline the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/decline", + body: fmt.Sprintf(`{"expected_version":%d,"reason":"other"}`, accepted.Version+1), status: http.StatusNotFound, code: "not_found"}, + {name: "accept the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/accept", + body: fmt.Sprintf(`{"expected_version":%d,"terms_version":%d,"consent_c4":{"text_version":%q,"accepted":true,"fields":["email"]}}`, + accepted.Version+1, accepted.TermsVersion, acceptTextVersion), status: http.StatusNotFound, code: "not_found"}, + {name: "cancel the invitation of another candidate", method: http.MethodPost, path: "/api/v1/me/invitations/" + accepted.ID.String() + "/cancel", + body: command, status: http.StatusNotImplemented, code: "not_implemented"}, + {name: "mark the notification of another candidate", method: http.MethodPost, path: "/api/v1/me/notifications/" + subjectNotice.ID.String() + "/read", + status: http.StatusNotFound, code: "not_found"}, + } + walk(t, other, calls, accepted.ID, subjectNotice.ID) + for _, path := range []string{"/api/v1/me/invitations", "/api/v1/me/notifications", "/api/v1/me/privacy/access-history"} { + text := must(other, http.MethodGet, path, "", http.StatusOK).Body.String() + if strings.Contains(text, accepted.ID.String()) || strings.Contains(text, subjectNotice.ID.String()) { + t.Errorf("%s of another candidate names the subject's objects: %s", path, text) + } + } + // Revoking C4 for A without a consent of one's own changes nothing of + // the subject's grant. + if response := do(other, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), ""); response.Code >= http.StatusInternalServerError { + t.Errorf("C4 revocation without a consent = %d %s", response.Code, response.Body.String()) + } + must(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), "", http.StatusOK) + // An employer is no candidate. + requireSessionProblem(t, do(ownerB, http.MethodGet, "/api/v1/me/invitations/"+accepted.ID.String(), ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, do(ownerB, http.MethodGet, "/api/v1/me/notifications", ""), http.StatusForbidden, "forbidden") + // A candidate is no member of a company. + requireSessionProblem(t, do(other, http.MethodGet, orgPath(orgA, "/invitations/"+accepted.ID.String()), ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, do(other, http.MethodGet, contactsPath(orgA, accepted.ID), ""), http.StatusForbidden, "forbidden") + if after := readStateOfA(); after != before { + t.Errorf("the calls of another candidate changed the state of A:\nbefore %+v\nafter %+v", before, after) + } + }) + + t.Run("no PDF, snapshot, or stored search result is served", func(t *testing.T) { + // The contract has no PDF, selection snapshot, or stored search + // operation in the MVP. Such a path is an unknown route, not data and + // not a server error, for the owner as well as for anyone else. + for _, path := range []string{ + cardPath + "/pdf", + orgPath(orgA, "/matches/"+need.ID.String()), + orgPath(orgA, "/needs/"+need.ID.String()+"/snapshots"), + orgPath(orgA, "/invitations/"+accepted.ID.String()+"/pdf"), + "/api/v1/me/profile/pdf", + } { + for _, who := range []categoryHTTPCandidate{ownerA, ownerB, subject.categoryHTTPCandidate} { + response := do(who, http.MethodGet, path, "") + requireSessionProblem(t, response, http.StatusNotFound, "not_found") + requireNoCandidateValues(path, response.Body.String(), true) + } + } + // A search result is computed for each request and never stored: a GET + // of the search path is no read of an earlier result. + requireSessionProblem(t, do(ownerA, http.MethodGet, orgPath(orgA, "/matches"), ""), http.StatusMethodNotAllowed, "method_not_allowed") + }) + + hiddenGrant := firstGrant + t.Run("hiding A closes the next read through the old search, the card, the evidence, a draft, and the contacts", func(t *testing.T) { + must(subject.categoryHTTPCandidate, http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", http.StatusOK) + // The very next requests, with the handle of the earlier result. + requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath+"/evidence", ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), ""), http.StatusNotFound, "not_found") + requireInvitationValidation(t, do(ownerA, http.MethodPost, orgPath(orgA, "/invitations"), invitationCreateJSON(t, subjectHandle, nil)), "/candidate_handle", "") + if _, found := search(ownerA, orgA, needSearch).handles()[subjectHandle+"/backend"]; found { + t.Fatal("a new search of A still returns the hidden candidate") + } + // The old invitation page shows the access as closed and no value. + page := do(ownerA, http.MethodGet, orgPath(orgA, "/invitations/"+accepted.ID.String()), "") + if invitation := decodeInvitationHTTP(t, page, http.StatusOK); invitation.ContactAccess.Status != "closed" || len(invitation.ContactAccess.Fields) != 0 { + t.Fatalf("invitation page while hidden = %+v, want closed access", invitation.ContactAccess) + } + requireNoCandidateValues("invitation page while hidden", page.Body.String(), true) + // Unhiding reopens the card for new reads but never the closed grant. + must(subject.categoryHTTPCandidate, http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", http.StatusNoContent) + must(ownerA, http.MethodGet, cardPath, "", http.StatusOK) + requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, accepted.ID), ""), http.StatusNotFound, "not_found") + grant := decodeContactGrantHTTP(t, decodeCandidateInvitationHTTP(t, + do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/invitations/"+accepted.ID.String(), ""), http.StatusOK)) + if grant.ID != hiddenGrant.ID || grant.Status != "revoked" || grant.Readable || grant.RevocationReason == nil || *grant.RevocationReason != "visibility_closed" { + t.Fatalf("grant after hiding and unhiding = %+v, want the same grant revoked for visibility", grant) + } + }) + + t.Run("revoking C4 closes the next read, and neither C2 again nor a new publication revives the grant", func(t *testing.T) { + invitation := sendDraft(ownerA, orgA, createDraft(ownerA, orgA, subjectHandle)) + grant := accept(subject, invitation, "email") + must(ownerA, http.MethodGet, contactsPath(orgA, invitation.ID), "", http.StatusOK) + + must(subject.categoryHTTPCandidate, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), "", http.StatusNoContent) + requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, invitation.ID), ""), http.StatusNotFound, "not_found") + // C4 does not hide the card: the anonymous card stays readable. + must(ownerA, http.MethodGet, cardPath, "", http.StatusOK) + + // The candidate withdraws C2, grants it again, and publishes the card + // again. The card reopens for new reads; the grant that C4 closed does not. + must(subject.categoryHTTPCandidate, http.MethodDelete, "/api/v1/me/consents/c2", "", http.StatusNoContent) + requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, do(ownerA, http.MethodGet, cardPath+"/evidence", ""), http.StatusNotFound, "not_found") + must(subject.categoryHTTPCandidate, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK) + var publication struct { + Version int64 `json:"version"` + } + var privacy struct { + Publication json.RawMessage `json:"publication"` + } + decode(must(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/privacy", "", http.StatusOK), &privacy) + if err := json.Unmarshal(privacy.Publication, &publication); err != nil { + t.Fatalf("decode publication %s: %v", privacy.Publication, err) + } + must(subject.categoryHTTPCandidate, http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":%s}`, publication.Version, publishedFields), http.StatusOK) + must(ownerA, http.MethodGet, cardPath, "", http.StatusOK) + for _, closed := range []uuid.UUID{invitation.ID, accepted.ID} { + requireSessionProblem(t, do(ownerA, http.MethodGet, contactsPath(orgA, closed), ""), http.StatusNotFound, "not_found") + page := do(ownerA, http.MethodGet, orgPath(orgA, "/invitations/"+closed.String()), "") + if read := decodeInvitationHTTP(t, page, http.StatusOK); read.ContactAccess.Status != "closed" { + t.Fatalf("invitation %s after the new publication = %+v, want closed access", closed, read.ContactAccess) + } + requireNoCandidateValues("invitation page after the new publication", page.Body.String(), true) + } + reread := decodeContactGrantHTTP(t, decodeCandidateInvitationHTTP(t, + do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/invitations/"+invitation.ID.String(), ""), http.StatusOK)) + if reread.ID != grant.ID || reread.Status != "revoked" || reread.Readable || reread.RevocationReason == nil || *reread.RevocationReason != "consent_revoked" { + t.Fatalf("grant after C2 again and a new publication = %+v, want it still revoked by the C4 revocation", reread) + } + var active int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM contact_grants + WHERE candidate_id = $1 AND organization_id = $2 AND revoked_at IS NULL`, subject.id, orgA).Scan(&active); err != nil { + t.Fatalf("count active grants: %v", err) + } + if active != 0 { + t.Fatalf("active grants of the subject for A = %d, want none without a new acceptance", active) + } + }) + + t.Run("the log, the events, the inbox, and the stored email requests carry no private value", func(t *testing.T) { + // The request log, problem log, and every other server log line. + if harness.logs.Len() == 0 { + t.Fatal("the scenario wrote no server log to scan") + } + requireNoCandidateValues("server log", harness.logs.String(), true) + // Event payloads name internal identifiers only where the inbox and + // privacy contracts require them, and never a contact, a name, or a + // profile value. + rows, err := harness.pool.Query(ctx, `SELECT event_type, payload::text FROM outbox_events ORDER BY event_id`) + if err != nil { + t.Fatalf("read outbox: %v", err) + } + events := 0 + for rows.Next() { + var eventType, payload string + if err := rows.Scan(&eventType, &payload); err != nil { + t.Fatalf("scan outbox: %v", err) + } + events++ + requireNoCandidateValues("outbox event "+eventType, payload, false) + } + rows.Close() + if err := rows.Err(); err != nil { + t.Fatalf("read outbox rows: %v", err) + } + if events == 0 { + t.Fatal("the scenario wrote no outbox event to scan") + } + var inboxRows, mailRequests string + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(string_agg(row_to_json(entry)::text, ' '), '') FROM notification_inbox_events AS entry`).Scan(&inboxRows); err != nil { + t.Fatalf("read inbox rows: %v", err) + } + requireNoCandidateValues("inbox rows", inboxRows, false) + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(string_agg(subject || ' ' || body || ' ' || link_path, ' '), '') FROM mail_requests`).Scan(&mailRequests); err != nil { + t.Fatalf("read email requests: %v", err) + } + if mailRequests == "" { + t.Fatal("the scenario stored no email request to scan") + } + requireNoCandidateValues("stored email requests", mailRequests, true) + // The notification as each recipient reads it. + requireNoCandidateValues("candidate notifications", do(subject.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/notifications", "").Body.String(), true) + requireNoCandidateValues("organization notifications", do(ownerA, http.MethodGet, orgPath(orgA, "/notifications"), "").Body.String(), true) + // The candidate's own preview of the anonymous card. + preview := must(neighbour.categoryHTTPCandidate, http.MethodGet, "/api/v1/me/privacy/preview", "", http.StatusOK) + requireNoCandidateValues("card preview", preview.Body.String(), true) + }) +} diff --git a/backend/integration_test/company_quota_test.go b/backend/integration_test/company_quota_test.go new file mode 100644 index 0000000..0339f83 --- /dev/null +++ b/backend/integration_test/company_quota_test.go @@ -0,0 +1,587 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/policy" +) + +const companyQuotaTestTimeout = 5 * time.Minute + +type companyQuotaFixture struct { + ctx context.Context + pool *pgxpool.Pool + clock *testClock + transactor *postgresadapter.Transactor + service *companyquota.Service + organizations organizationFixture + policies outbound.PolicyRepository + version domain.PolicyVersion + // invitationAuthor and invitationCandidate are the accounts of the drafts + // that invitation usage names: a charge refers to a stored invitation of + // the same organization. + invitationAuthor uuid.UUID + invitationCandidate uuid.UUID +} + +// newCompanyQuotaFixture migrates the isolated database, publishes the demo +// product policy, and returns the fixture the quota tests share. +func newCompanyQuotaFixture(ctx context.Context, t *testing.T, databaseURL string) companyQuotaFixture { + t.Helper() + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + + clock := &testClock{now: time.Now().UTC().Add(5 * time.Minute).Truncate(time.Microsecond)} + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()} + transactor := postgresadapter.NewTransactor(pool) + organizationFixture := organizationFixture{ + ctx: ctx, pool: pool, identity: identity, transactor: transactor, now: clock.Now(), + } + policyStore := postgresadapter.NewPolicyStore(pool) + if _, err := policy.NewPublisher(policyStore.Policies(), clock.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + version, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, clock.Now()) + if err != nil { + t.Fatalf("GetEffective(product) error = %v", err) + } + return companyQuotaFixture{ + ctx: ctx, pool: pool, clock: clock, transactor: transactor, + service: companyquota.NewService(clock.Now), organizations: organizationFixture, + policies: policyStore.Policies(), version: version, + invitationAuthor: organizationFixture.employer(t, "quota-invitation-author@example.test").ID, + invitationCandidate: identity.createUser(t, "quota-invitation-candidate@example.test", domain.ScenarioCandidate, clock.Now().Add(-time.Hour)).ID, + } +} + +func TestCompanyQuota(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout) + defer cancel() + fixture := newCompanyQuotaFixture(ctx, t, env.createIsolatedDatabase(ctx, t)) + + t.Run("E0 shares limits across requests and concurrent final reservations", func(t *testing.T) { + organization, _ := fixture.newOrganization(t, "e0-boundary", domain.OrganizationVerificationE0) + var firstCandidate uuid.UUID + var boundaryCandidate uuid.UUID + for range 9 { + fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization)) + } + for index := range 49 { + candidateID := fixture.newCandidateID(t) + if index == 0 { + firstCandidate = candidateID + } else if index == 1 { + boundaryCandidate = candidateID + } + fixture.reserveCardViewAllowed(t, organization, candidateID) + } + + type result struct { + decision outbound.CompanyQuotaDecision + err error + kind string + } + start := make(chan struct{}) + results := make(chan result, 4) + var workers sync.WaitGroup + for range 2 { + invitationID := fixture.newInvitationID(t, organization) + workers.Add(1) + go func() { + defer workers.Done() + <-start + decision, err := fixture.reserveInvitation(organization, invitationID) + results <- result{decision: decision, err: err, kind: "invitation"} + }() + } + for range 2 { + candidateID := fixture.newCandidateID(t) + workers.Add(1) + go func() { + defer workers.Done() + <-start + decision, err := fixture.reserveCardView(organization, candidateID) + results <- result{decision: decision, err: err, kind: "view"} + }() + } + close(start) + workers.Wait() + close(results) + + allowedInvitations, deniedInvitations := 0, 0 + allowedViews, deniedViews := 0, 0 + for result := range results { + if result.err != nil { + t.Fatalf("concurrent quota reservation error = %v", result.err) + } + switch result.kind { + case "invitation": + if result.decision.Allowed && result.decision.RetryAt.IsZero() { + allowedInvitations++ + } else if !result.decision.Allowed && result.decision.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) { + deniedInvitations++ + } else { + t.Fatalf("unexpected invitation decision: %+v", result.decision) + } + case "view": + if result.decision.Allowed && result.decision.RetryAt.IsZero() { + allowedViews++ + } else if !result.decision.Allowed && result.decision.RetryAt.Equal(fixture.clock.Now().Add(24*time.Hour)) { + deniedViews++ + } else { + t.Fatalf("unexpected card-view decision: %+v", result.decision) + } + default: + t.Fatalf("unexpected reservation kind %q", result.kind) + } + } + if allowedInvitations != 1 || deniedInvitations != 1 || allowedViews != 1 || deniedViews != 1 { + t.Fatalf("concurrent invitation/view results: allowed=%d/%d denied=%d/%d", allowedInvitations, allowedViews, deniedInvitations, deniedViews) + } + fixture.assertQuotaRowCounts(t, organization.ID(), 10, 50) + fixture.assertStoredEvidence(t, organization.ID(), domain.OrganizationVerificationE0, domain.OrganizationBasisConfirmedEmail) + + // A repeated card in the active window is shared by the organization. + fixture.clock.Advance(23 * time.Hour) + repeated, err := fixture.reserveCardView(organization, firstCandidate) + if err != nil || !repeated.Allowed || !repeated.Reused { + t.Fatalf("ReserveCardView(repeat) = %+v, %v; want an organization-level reuse", repeated, err) + } + fixture.clock.Set(fixture.clock.Now().Add(time.Hour)) + atDay := fixture.clock.Now() + for _, step := range []struct { + name string + id uuid.UUID + call func(domain.Organization, uuid.UUID) (outbound.CompanyQuotaDecision, error) + }{ + {name: "card view at the 24-hour boundary", id: boundaryCandidate, call: fixture.reserveCardView}, + {name: "invitation remains charged during the first day", id: fixture.newInvitationID(t, organization), call: fixture.reserveInvitation}, + } { + decision, err := step.call(organization, step.id) + if err != nil { + t.Fatalf("%s error = %v", step.name, err) + } + if step.name == "card view at the 24-hour boundary" { + if !decision.Allowed || decision.Reused { + t.Fatalf("%s decision = %+v, want a new allowed view", step.name, decision) + } + } else if decision.Allowed || !decision.RetryAt.Equal(atDay.Add(6*24*time.Hour)) { + t.Fatalf("%s decision = %+v, want retry at the 7-day boundary", step.name, decision) + } + } + fixture.assertActiveQuotaCounts(t, organization.ID(), atDay, 10, 2) + fixture.assertQuotaRowCounts(t, organization.ID(), 10, 2) + + fixture.clock.Set(atDay.Add(6 * 24 * time.Hour)) + newInvitation := fixture.newInvitationID(t, organization) + decision, err := fixture.reserveInvitation(organization, newInvitation) + if err != nil || !decision.Allowed || decision.Reused { + t.Fatalf("ReserveInvitation(at 7 days) = %+v, %v; want a new allowed invitation", decision, err) + } + fixture.assertActiveQuotaCounts(t, organization.ID(), fixture.clock.Now(), 1, 0) + + // The same invitation ID stays idempotent beyond the rolling window, + // independently of any request idempotency key used by its caller. + oldInvitationID := fixture.newInvitationID(t, organization) + fixture.reserveInvitationAllowed(t, organization, oldInvitationID) + fixture.clock.Advance(8 * 24 * time.Hour) + reused, err := fixture.reserveInvitation(organization, oldInvitationID) + if err != nil || !reused.Allowed || !reused.Reused { + t.Fatalf("ReserveInvitation(old ID after 8 days) = %+v, %v; want retained idempotent usage", reused, err) + } + }) + + t.Run("E1 enforces the stored 40 and 150 limits", func(t *testing.T) { + organization, _ := fixture.newOrganization(t, "e1-boundary", domain.OrganizationVerificationE1) + for range 40 { + fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization)) + } + deniedInvitation, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) + if err != nil || deniedInvitation.Allowed || !deniedInvitation.RetryAt.Equal(fixture.clock.Now().Add(7*24*time.Hour)) { + t.Fatalf("E1 invitation 41 = %+v, %v; want denial for one week", deniedInvitation, err) + } + for range 150 { + fixture.reserveCardViewAllowed(t, organization, fixture.newCandidateID(t)) + } + deniedView, err := fixture.reserveCardView(organization, fixture.newCandidateID(t)) + if err != nil || deniedView.Allowed || !deniedView.RetryAt.Equal(fixture.clock.Now().Add(24*time.Hour)) { + t.Fatalf("E1 card view 151 = %+v, %v; want denial for 24 hours", deniedView, err) + } + fixture.assertQuotaRowCounts(t, organization.ID(), 40, 150) + fixture.assertStoredEvidence(t, organization.ID(), domain.OrganizationVerificationE1, domain.OrganizationBasisCorporateDomain) + }) + + t.Run("active E2 policy permits verified organizations and rejects a forged tier snapshot", func(t *testing.T) { + policyDocument := domain.DemoProductPolicyV1() + policyDocument.OrganizationQuotas.TierE2.Active = true + activePolicy, err := policy.NewPublisher(fixture.policies, fixture.clock.Now).Publish(fixture.ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "system:quota-test", + EffectiveAt: fixture.clock.Now(), Policy: policyDocument, + }) + if err != nil { + t.Fatalf("publish active E2 policy: %v", err) + } + if quota := activePolicy.Policy().OrganizationQuotas.TierE2; !quota.Active || + quota.InvitationsPerWindow != 100 || quota.DistinctCardViewsPerWindow != 400 { + t.Fatalf("active E2 policy limits = %+v, want 100 invitations and 400 views", quota) + } + fixture.version = activePolicy + + verified, _ := fixture.newOrganization(t, "active-e2", domain.OrganizationVerificationE2) + invitation, err := fixture.reserveInvitation(verified, fixture.newInvitationID(t, verified)) + if err != nil || !invitation.Allowed || invitation.Reused { + t.Fatalf("ReserveInvitation(verified E2) = %+v, %v; want an allowed new reservation", invitation, err) + } + view, err := fixture.reserveCardView(verified, fixture.newCandidateID(t)) + if err != nil || !view.Allowed || view.Reused { + t.Fatalf("ReserveCardView(verified E2) = %+v, %v; want an allowed new reservation", view, err) + } + fixture.assertQuotaRowCounts(t, verified.ID(), 1, 1) + fixture.assertStoredEvidence(t, verified.ID(), domain.OrganizationVerificationE2, domain.OrganizationBasisRequisitesAndAuthority) + + e0Organization, _ := fixture.newOrganization(t, "forged-e2", domain.OrganizationVerificationE0) + forgedE2, err := domain.RestoreOrganization(domain.StoredOrganization{ + ID: e0Organization.ID(), Name: e0Organization.Profile().Name(), + VerificationLevel: string(domain.OrganizationVerificationE2), + VerificationBasis: string(domain.OrganizationBasisRequisitesAndAuthority), + VerificationChangedAt: fixture.clock.Now().Add(-time.Minute), + Version: e0Organization.Version(), CreatedAt: e0Organization.CreatedAt(), UpdatedAt: e0Organization.UpdatedAt(), + }) + if err != nil { + t.Fatalf("restore forged E2 snapshot for E0 organization: %v", err) + } + forgedQuota, err := domain.NewCompanyQuota(forgedE2, activePolicy, fixture.clock.Now()) + if err != nil { + t.Fatalf("build forged E2 snapshot: %v", err) + } + if err := fixture.reserveWithSnapshot(e0Organization, forgedQuota, fixture.newInvitationID(t, e0Organization)); !errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { + t.Fatalf("reserve with forged E2 snapshot against stored E0 organization error = %v, want snapshot mismatch", err) + } + fixture.assertQuotaRowCounts(t, e0Organization.ID(), 0, 0) + }) + + t.Run("a repeated view refreshes monotonically when application time moves backward", func(t *testing.T) { + organization, _ := fixture.newOrganization(t, "view-clock", domain.OrganizationVerificationE0) + candidateID := fixture.newCandidateID(t) + fixture.reserveCardViewAllowed(t, organization, candidateID) + firstSeen := fixture.clock.Now() + fixture.clock.Advance(time.Hour) + fixture.reserveCardViewReused(t, organization, candidateID) + fixture.clock.Set(firstSeen.Add(30 * time.Minute)) + fixture.reserveCardViewReused(t, organization, candidateID) + + var lastSeen time.Time + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT last_seen_at FROM company_card_view_quota_usage + WHERE organization_id = $1 AND candidate_id = $2`, organization.ID(), candidateID).Scan(&lastSeen); err != nil { + t.Fatalf("read repeated view timestamp: %v", err) + } + if !lastSeen.Equal(firstSeen.Add(time.Hour)) { + t.Fatalf("last_seen_at = %s, want monotonic time %s", lastSeen, firstSeen.Add(time.Hour)) + } + }) + + t.Run("candidate deletion clears card-view data but leaves invitation quota evidence", func(t *testing.T) { + organization, _ := fixture.newOrganization(t, "candidate-delete", domain.OrganizationVerificationE0) + candidateID := fixture.newCandidateID(t) + // The charged invitation names another candidate: a candidate with an + // invitation cannot be deleted until a deletion procedure settles it. + fixture.reserveInvitationAllowed(t, organization, fixture.newInvitationID(t, organization)) + fixture.reserveCardViewAllowed(t, organization, candidateID) + + if _, err := fixture.pool.Exec(fixture.ctx, `DELETE FROM users WHERE id = $1`, candidateID); err != nil { + t.Fatalf("delete candidate: %v", err) + } + fixture.assertQuotaRowCounts(t, organization.ID(), 1, 0) + }) + + t.Run("rollback and stale trust or policy snapshots write no usage", func(t *testing.T) { + organization, _ := fixture.newOrganization(t, "snapshot-check", domain.OrganizationVerificationE0) + quota := fixture.quota(t, organization, fixture.version) + rollbackMarker := errors.New("test transaction rollback") + rolledBackInvitation := fixture.newInvitationID(t, organization) + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + decision, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, rolledBackInvitation) + if err != nil { + return err + } + if !decision.Allowed { + return errors.New("test invitation was unexpectedly denied") + } + return rollbackMarker + }) + if !errors.Is(err, rollbackMarker) { + t.Fatalf("transaction rollback error = %v, want marker", err) + } + fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0) + + if _, err := fixture.pool.Exec(fixture.ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, organization.ID(), fixture.clock.Now().Add(-time.Minute)); err != nil { + t.Fatalf("change stored organization verification: %v", err) + } + staleTrustErr := fixture.reserveWithSnapshot(organization, quota, fixture.newInvitationID(t, organization)) + if !errors.Is(staleTrustErr, outbound.ErrCompanyQuotaSnapshotChanged) { + t.Fatalf("reserve with stale organization trust error = %v, want snapshot mismatch", staleTrustErr) + } + fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0) + + policyOrganization, _ := fixture.newOrganization(t, "policy-check", domain.OrganizationVerificationE0) + stalePolicyQuota := fixture.quota(t, policyOrganization, fixture.version) + publisher := policy.NewPublisher(fixture.policies, fixture.clock.Now) + _, err = publisher.Publish(fixture.ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: "system:quota-test", + EffectiveAt: fixture.clock.Now(), Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + t.Fatalf("publish next effective product policy: %v", err) + } + stalePolicyErr := fixture.reserveWithSnapshot(policyOrganization, stalePolicyQuota, fixture.newInvitationID(t, policyOrganization)) + if !errors.Is(stalePolicyErr, outbound.ErrCompanyQuotaSnapshotChanged) { + t.Fatalf("reserve with stale policy error = %v, want snapshot mismatch", stalePolicyErr) + } + fixture.assertQuotaRowCounts(t, policyOrganization.ID(), 0, 0) + }) + + t.Run("inactive E2 and E3 fail closed before recording usage", func(t *testing.T) { + for _, test := range []struct { + name string + level domain.OrganizationVerificationLevel + basis domain.OrganizationVerificationBasis + }{ + {name: "inactive E2", level: domain.OrganizationVerificationE2, basis: domain.OrganizationBasisRequisitesAndAuthority}, + {name: "E3", level: domain.OrganizationVerificationE3, basis: domain.OrganizationBasisManualReview}, + } { + t.Run(test.name, func(t *testing.T) { + organization, _ := fixture.newOrganization(t, "denied-"+string(test.level), test.level) + _, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) + if !errors.Is(err, domain.ErrCompanyQuotaDenied) { + t.Fatalf("ReserveInvitation(%s) error = %v, want fail-closed denial", test.level, err) + } + fixture.assertQuotaRowCounts(t, organization.ID(), 0, 0) + }) + } + }) +} + +func (fixture companyQuotaFixture) newOrganization( + t *testing.T, + name string, + level domain.OrganizationVerificationLevel, +) (domain.Organization, domain.User) { + t.Helper() + owner := fixture.organizations.employer(t, fmt.Sprintf("quota-%s-%s@example.test", name, uuid.NewString())) + return fixture.organizationOf(t, owner, name, level), owner +} + +// organizationOf stores an organization of owner at the given verification +// level and returns it as read back from storage. Several organizations of one +// owner belong to one holding. +func (fixture companyQuotaFixture) organizationOf( + t *testing.T, + owner domain.User, + name string, + level domain.OrganizationVerificationLevel, +) domain.Organization { + t.Helper() + organization := fixture.organizations.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Quota " + name}), fixture.clock.Now().Add(-time.Minute)) + if level != domain.OrganizationVerificationE0 { + basis := domain.OrganizationBasisCorporateDomain + switch level { + case domain.OrganizationVerificationE2: + basis = domain.OrganizationBasisRequisitesAndAuthority + case domain.OrganizationVerificationE3: + basis = domain.OrganizationBasisManualReview + } + if _, err := fixture.pool.Exec(fixture.ctx, ` + UPDATE organizations + SET verification_level = $2, verification_basis = $3, verification_changed_at = $4 + WHERE id = $1`, organization.ID(), string(level), string(basis), fixture.clock.Now().Add(-time.Minute)); err != nil { + t.Fatalf("set %s verification fixture: %v", level, err) + } + } + stored, _, err := fixture.organizations.read(owner.ID, organization.ID()) + if err != nil { + t.Fatalf("read %s organization: %v", level, err) + } + return stored +} + +// newInvitationID stores a draft of the organization and returns its +// identifier, so the usage that names it satisfies the foreign key. +func (fixture companyQuotaFixture) newInvitationID(t *testing.T, organization domain.Organization) uuid.UUID { + t.Helper() + invitationID, err := uuid.NewV7() + if err != nil { + t.Fatalf("NewV7() error = %v", err) + } + draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: invitationID, OrganizationID: organization.ID(), CandidateID: fixture.invitationCandidate, ActorID: fixture.invitationAuthor, + PolicyVersionID: fixture.version.ID(), At: fixture.clock.Now().Add(-time.Minute), + Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationStorageTerms()}, + }) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + event, err := draft.DraftEvent(fixture.invitationAuthor, nil) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Create(ctx, draft, event) + }); err != nil { + t.Fatalf("store the draft of the charge: %v", err) + } + return invitationID +} + +func (fixture companyQuotaFixture) newCandidateID(t *testing.T) uuid.UUID { + t.Helper() + candidate := fixture.organizations.identity.createUser( + t, + fmt.Sprintf("quota-candidate-%s@example.test", uuid.NewString()), + domain.ScenarioCandidate, + fixture.clock.Now().Add(-time.Hour), + ) + return candidate.ID +} + +func (fixture companyQuotaFixture) quota(t *testing.T, organization domain.Organization, version domain.PolicyVersion) domain.CompanyQuota { + t.Helper() + quota, err := domain.NewCompanyQuota(organization, version, fixture.clock.Now()) + if err != nil { + t.Fatalf("NewCompanyQuota() error = %v", err) + } + return quota +} + +func (fixture companyQuotaFixture) reserveInvitation(organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + var decision outbound.CompanyQuotaDecision + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID) + return err + }) + return decision, err +} + +func (fixture companyQuotaFixture) reserveCardView(organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + var decision outbound.CompanyQuotaDecision + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID) + return err + }) + return decision, err +} + +func (fixture companyQuotaFixture) reserveWithSnapshot(organization domain.Organization, quota domain.CompanyQuota, invitationID uuid.UUID) error { + return fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.CompanyQuotas().ReserveInvitation(ctx, quota, invitationID) + return err + }) +} + +func (fixture companyQuotaFixture) reserveInvitationAllowed(t *testing.T, organization domain.Organization, invitationID uuid.UUID) { + t.Helper() + decision, err := fixture.reserveInvitation(organization, invitationID) + if err != nil || !decision.Allowed || decision.Reused || !decision.RetryAt.IsZero() { + t.Fatalf("ReserveInvitation() = %+v, %v; want a new allowed reservation", decision, err) + } +} + +func (fixture companyQuotaFixture) reserveCardViewAllowed(t *testing.T, organization domain.Organization, candidateID uuid.UUID) { + t.Helper() + decision, err := fixture.reserveCardView(organization, candidateID) + if err != nil || !decision.Allowed || decision.Reused || !decision.RetryAt.IsZero() { + t.Fatalf("ReserveCardView() = %+v, %v; want a new allowed reservation", decision, err) + } +} + +func (fixture companyQuotaFixture) reserveCardViewReused(t *testing.T, organization domain.Organization, candidateID uuid.UUID) { + t.Helper() + decision, err := fixture.reserveCardView(organization, candidateID) + if err != nil || !decision.Allowed || !decision.Reused || !decision.RetryAt.IsZero() { + t.Fatalf("ReserveCardView(repeat) = %+v, %v; want an allowed reuse", decision, err) + } +} + +func (fixture companyQuotaFixture) assertQuotaRowCounts(t *testing.T, organizationID uuid.UUID, invitations, views int64) { + t.Helper() + var gotInvitations, gotViews int64 + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, organizationID).Scan(&gotInvitations); err != nil { + t.Fatalf("count invitation quota rows: %v", err) + } + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, organizationID).Scan(&gotViews); err != nil { + t.Fatalf("count card-view quota rows: %v", err) + } + if gotInvitations != invitations || gotViews != views { + t.Fatalf("quota rows for organization = invitations %d, views %d; want %d/%d", gotInvitations, gotViews, invitations, views) + } +} + +func (fixture companyQuotaFixture) assertActiveQuotaCounts(t *testing.T, organizationID uuid.UUID, at time.Time, invitations, views int64) { + t.Helper() + var gotInvitations, gotViews int64 + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_invitation_quota_usage + WHERE organization_id = $1 AND reserved_at > $2`, organizationID, at.Add(-7*24*time.Hour)).Scan(&gotInvitations); err != nil { + t.Fatalf("count active invitation quota rows: %v", err) + } + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_card_view_quota_usage + WHERE organization_id = $1 AND last_seen_at > $2`, organizationID, at.Add(-24*time.Hour)).Scan(&gotViews); err != nil { + t.Fatalf("count active card-view quota rows: %v", err) + } + if gotInvitations != invitations || gotViews != views { + t.Fatalf("active quota rows at %s = invitations %d, views %d; want %d/%d", at, gotInvitations, gotViews, invitations, views) + } +} + +func (fixture companyQuotaFixture) assertStoredEvidence( + t *testing.T, + organizationID uuid.UUID, + level domain.OrganizationVerificationLevel, + basis domain.OrganizationVerificationBasis, +) { + t.Helper() + var invitationPolicy, viewPolicy uuid.UUID + var invitationLevel, viewLevel string + var invitationBasis, viewBasis string + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT policy_version_id, verification_level, verification_basis + FROM company_invitation_quota_usage WHERE organization_id = $1 + ORDER BY reserved_at LIMIT 1`, organizationID).Scan(&invitationPolicy, &invitationLevel, &invitationBasis); err != nil { + t.Fatalf("read invitation quota evidence: %v", err) + } + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT policy_version_id, verification_level, verification_basis + FROM company_card_view_quota_usage WHERE organization_id = $1 + ORDER BY last_seen_at LIMIT 1`, organizationID).Scan(&viewPolicy, &viewLevel, &viewBasis); err != nil { + t.Fatalf("read card-view quota evidence: %v", err) + } + if invitationPolicy != fixture.version.ID().UUID() || viewPolicy != fixture.version.ID().UUID() || + invitationLevel != string(level) || viewLevel != string(level) || + invitationBasis != string(basis) || viewBasis != string(basis) { + t.Fatalf("stored quota evidence = invitation %s/%s/%s view %s/%s/%s, want policy %s and %s/%s", + invitationPolicy, invitationLevel, invitationBasis, viewPolicy, viewLevel, viewBasis, fixture.version.ID(), level, basis) + } +} diff --git a/backend/integration_test/consent_http_test.go b/backend/integration_test/consent_http_test.go new file mode 100644 index 0000000..2b86108 --- /dev/null +++ b/backend/integration_test/consent_http_test.go @@ -0,0 +1,500 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" +) + +const consentHTTPTestTimeout = 5 * time.Minute + +func TestConsentSettingsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), consentHTTPTestTimeout) + defer cancel() + harness := newConsentHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, usersDependentTables...) + + now := harness.clock.Now() + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + candidate := createSessionHTTPUser(ctx, t, harness, "consent-candidate@example.test", passwordHash, true) + createConsentHTTPEmployer(ctx, t, harness, "consent-employer@example.test", passwordHash) + candidateCookie, candidateCSRF := loginConsentHTTP(t, harness, "consent-candidate@example.test", "192.0.2.50:1234") + employerCookie, employerCSRF := loginConsentHTTP(t, harness, "consent-employer@example.test", "192.0.2.51:1234") + store := postgresadapter.NewConsentStore(harness.pool) + reader := consent.NewQueryService(store, time.Now) + + guestList := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", "", "", "192.0.2.52:1234") + requireSessionProblem(t, guestList, http.StatusUnauthorized, "unauthenticated") + guestDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", "", "", "", "192.0.2.53:1234") + requireSessionProblem(t, guestDeletion, http.StatusUnauthorized, "unauthenticated") + assertRowCount(ctx, t, harness.pool, consentTables[0], 0) + assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 0) + + publicText := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c1", "", "", "", "", "192.0.2.54:1234") + if publicText.Code != http.StatusOK { + t.Fatalf("public C1 text = %d %s", publicText.Code, publicText.Body.String()) + } + myC2Text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c2", "", "", candidateCookie.Value, "", "192.0.2.55:1234") + if myC2Text.Code != http.StatusOK || myC2Text.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("current C2 text = %d, Cache-Control=%q, body=%s", myC2Text.Code, myC2Text.Header().Get("Cache-Control"), myC2Text.Body.String()) + } + var c2Text struct { + Purpose string `json:"purpose"` + TextVersion string `json:"text_version"` + Text string `json:"text"` + } + if err := json.Unmarshal(myC2Text.Body.Bytes(), &c2Text); err != nil || c2Text.Purpose != "c2" || c2Text.TextVersion == "" || c2Text.Text == "" { + t.Fatalf("decode current C2 text = %+v, %v", c2Text, err) + } + publicC2 := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c2", "", "", "", "", "192.0.2.56:1234") + requireSessionProblem(t, publicC2, http.StatusBadRequest, "validation_failed") + + // A newer publication makes the version already shown to the candidate stale. + newC2Body := "I consent to publication of my candidate card, consent HTTP test revision." + newC2Version := "c2-consent-http-revision" + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + VALUES ('c2', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`, + newC2Version, newC2Body, now.Add(-time.Second)); err != nil { + t.Fatalf("publish a newer C2 text: %v", err) + } + staleGrant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", c2Text.TextVersion, sessionHTTPTestOrigin) + requireSessionProblem(t, staleGrant, http.StatusBadRequest, "validation_failed") + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0) + + missingOriginGrant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, "") + requireSessionProblem(t, missingOriginGrant, http.StatusForbidden, "csrf_check_failed") + wrongCSRFGrant := consentGrantHTTP(t, harness, candidateCookie, "wrong-token", "c2", newC2Version, sessionHTTPTestOrigin) + requireSessionProblem(t, wrongCSRFGrant, http.StatusForbidden, "csrf_check_failed") + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0) + + employerGrant := consentGrantHTTP(t, harness, employerCookie, employerCSRF, "c2", newC2Version, sessionHTTPTestOrigin) + requireSessionProblem(t, employerGrant, http.StatusForbidden, "forbidden") + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 0) + + c2Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, sessionHTTPTestOrigin) + if c2Grant.Code != http.StatusOK || c2Grant.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("C2 grant = %d, Cache-Control=%q, body=%s", c2Grant.Code, c2Grant.Header().Get("Cache-Control"), c2Grant.Body.String()) + } + c2Record, err := store.ConsentLedger().Current(ctx, candidate.ID, domain.ConsentPurposePublication) + if err != nil || c2Record.TextVersion() != domain.ConsentTextVersion(newC2Version) { + t.Fatalf("current C2 record = %s, %v", c2Record, err) + } + + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), + identity: identityFixture{ctx: ctx, pool: harness.pool, store: postgresadapter.NewIdentityStore(harness.pool), now: now}, + ledger: store, now: now, + } + privacy.publish(t, candidate.ID, c2Record.ID(), 0, domain.CardFieldStack) + var privacyEventsBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsBefore); err != nil { + t.Fatalf("count candidate privacy events before C2 revoke: %v", err) + } + var c2EventsBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsBefore); err != nil { + t.Fatalf("count C2 revocation events before revoke: %v", err) + } + wrongOriginRevoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", "https://attacker.example", candidateCookie.Value, candidateCSRF, "192.0.2.57:1234") + requireSessionProblem(t, wrongOriginRevoke, http.StatusForbidden, "csrf_check_failed") + if publication := privacy.loadPublication(t, candidate.ID); publication.State() != domain.PublicationPublished { + t.Fatalf("bad-Origin revoke changed publication to %s", publication.State()) + } + current, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposePublication) + if err != nil || !current { + t.Fatalf("bad-Origin revoke changed the C2 gate: %v, %v", current, err) + } + + revokedC2 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.58:1234") + if revokedC2.Code != http.StatusNoContent { + t.Fatalf("C2 revoke = %d %s", revokedC2.Code, revokedC2.Body.String()) + } + current, err = reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposePublication) + if err != nil || current { + t.Fatalf("revoked C2 gate = %v, %v; want fail closed", current, err) + } + if publication := privacy.loadPublication(t, candidate.ID); publication.State() != domain.PublicationClosed || + publication.ClosedReason() != domain.ClosedConsentRevoked || !publication.Fields().IsEmpty() { + t.Fatalf("revoked C2 publication = %s/%s, want closed and empty", publication.State(), publication.ClosedReason()) + } + var storedPublicationState string + var storedPublicationFields []string + var storedPublicationConsentID uuid.UUID + if err := harness.pool.QueryRow(ctx, ` + SELECT state, fields, consent_record_id + FROM candidate_publications + WHERE user_id = $1`, candidate.ID).Scan(&storedPublicationState, &storedPublicationFields, &storedPublicationConsentID); err != nil { + t.Fatalf("read stored publication after C2 revoke: %v", err) + } + if storedPublicationState != "published" || len(storedPublicationFields) != 1 || storedPublicationFields[0] != string(domain.CardFieldStack) || storedPublicationConsentID != c2Record.ID() { + t.Fatalf("revocation rewrote publication source row: state=%s fields=%v consent=%s", storedPublicationState, storedPublicationFields, storedPublicationConsentID) + } + var privacyEventsAfter, c2EventsAfter int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsAfter); err != nil { + t.Fatalf("count candidate privacy events after C2 revoke: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsAfter); err != nil { + t.Fatalf("count C2 revocation events after revoke: %v", err) + } + if privacyEventsAfter != privacyEventsBefore+1 || c2EventsAfter != c2EventsBefore+1 { + t.Fatalf("C2 revoke effects changed by privacy=%d and outbox=%d, want one each", privacyEventsAfter-privacyEventsBefore, c2EventsAfter-c2EventsBefore) + } + repeatedC2 := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.59:1234") + if repeatedC2.Code != http.StatusNoContent { + t.Fatalf("repeat C2 revoke = %d %s", repeatedC2.Code, repeatedC2.Body.String()) + } + var c2EventsRepeated int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c2' AND payload->>'subject_id' = $1`, candidate.ID.String()).Scan(&c2EventsRepeated); err != nil { + t.Fatalf("count C2 revocation events after repeat: %v", err) + } + if c2EventsRepeated != c2EventsAfter { + t.Fatalf("repeat C2 revoke duplicated an outbox event: %d -> %d", c2EventsAfter, c2EventsRepeated) + } + newC2Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c2", newC2Version, sessionHTTPTestOrigin) + revokedPublication := privacy.loadPublication(t, candidate.ID) + if newC2Grant.Code != http.StatusOK || revokedPublication.State() != domain.PublicationClosed || + revokedPublication.ClosedReason() != domain.ClosedConsentRevoked || !revokedPublication.Fields().IsEmpty() { + t.Fatalf("new C2 grant reopened the old publication: status=%d publication=%s", newC2Grant.Code, privacy.loadPublication(t, candidate.ID).State()) + } + newerC2Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c2", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.74:1234") + if newerC2Revoke.Code != http.StatusNoContent { + t.Fatalf("revoke newer C2 record = %d %s", newerC2Revoke.Code, newerC2Revoke.Body.String()) + } + var privacyEventsAfterNewerRevoke int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM candidate_privacy_events WHERE user_id = $1`, candidate.ID).Scan(&privacyEventsAfterNewerRevoke); err != nil { + t.Fatalf("count privacy events after newer C2 revoke: %v", err) + } + if privacyEventsAfterNewerRevoke != privacyEventsAfter { + t.Fatalf("revoking newer C2 record duplicated the old publication event: %d -> %d", privacyEventsAfter, privacyEventsAfterNewerRevoke) + } + + // C5 has a real current-consent reader; after revocation future import work denies. + c5Text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c5", "", "", candidateCookie.Value, "", "192.0.2.60:1234") + var c5Current struct { + TextVersion string `json:"text_version"` + } + if c5Text.Code != http.StatusOK || json.Unmarshal(c5Text.Body.Bytes(), &c5Current) != nil { + t.Fatalf("read C5 text = %d %s", c5Text.Code, c5Text.Body.String()) + } + c5Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c5", c5Current.TextVersion, sessionHTTPTestOrigin) + if c5Grant.Code != http.StatusOK { + t.Fatalf("C5 grant = %d %s", c5Grant.Code, c5Grant.Body.String()) + } + if allowed, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposeFSPImport); err != nil || !allowed { + t.Fatalf("current C5 gate = %v, %v; want allow", allowed, err) + } + c5Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c5", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.61:1234") + if c5Revoke.Code != http.StatusNoContent { + t.Fatalf("C5 revoke = %d %s", c5Revoke.Code, c5Revoke.Body.String()) + } + if allowed, err := reader.HasCurrentConsent(ctx, candidate.ID, domain.ConsentPurposeFSPImport); err != nil || allowed { + t.Fatalf("revoked C5 gate = %v, %v; want deny", allowed, err) + } + + // C4 revocation takes its target from the path and its fields from the stored records. + contactText, err := store.ConsentTexts().Current(ctx, domain.ConsentPurposeContactDisclosure, now) + if err != nil { + t.Fatalf("read current C4 text: %v", err) + } + organizationA, organizationB := uuid.New(), uuid.New() + for _, organizationID := range []uuid.UUID{organizationA, organizationB} { + invitationID := uuid.New() + fieldSet, err := domain.NewContactFieldSet(domain.ContactFieldPhone, domain.ContactFieldEmail) + if err != nil { + t.Fatal(err) + } + grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ + SubjectID: candidate.ID, OrganizationID: organizationID, OrganizationName: consentOrganizationName, + Fields: fieldSet, InvitationID: invitationID, InvitationTermsVersion: 2, Text: contactText, GrantedAt: now, + }) + if err != nil { + t.Fatalf("build C4 grant: %v", err) + } + if _, created, err := store.ConsentLedger().GrantContact(ctx, grant); err != nil || !created { + t.Fatalf("store C4 grant = %v, %v", created, err) + } + } + c4Revoke := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+organizationA.String(), "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.62:1234") + if c4Revoke.Code != http.StatusNoContent { + t.Fatalf("C4 revoke = %d %s", c4Revoke.Code, c4Revoke.Body.String()) + } + remainingC4, err := store.ConsentLedger().CurrentContact(ctx, candidate.ID, organizationB) + if err != nil || len(remainingC4) != 1 || remainingC4[0].State() != domain.ConsentStateActive { + t.Fatalf("C4 for another organization = %v, %v; want one unchanged active record", remainingC4, err) + } + var c4Payload struct { + OrganizationID string `json:"organization_id"` + Fields []string `json:"fields"` + } + var c4PayloadJSON []byte + if err := harness.pool.QueryRow(ctx, ` + SELECT payload FROM outbox_events + WHERE event_type = 'consent.revoked' AND payload->>'purpose' = 'c4' AND payload->>'subject_id' = $1 + ORDER BY position DESC LIMIT 1`, candidate.ID.String()).Scan(&c4PayloadJSON); err != nil { + t.Fatalf("read C4 revocation intent: %v", err) + } + if err := json.Unmarshal(c4PayloadJSON, &c4Payload); err != nil { + t.Fatalf("decode C4 revocation intent: %v", err) + } + if c4Payload.OrganizationID != organizationA.String() || len(c4Payload.Fields) != 2 || + c4Payload.Fields[0] != string(domain.ContactFieldEmail) || c4Payload.Fields[1] != string(domain.ContactFieldPhone) { + t.Fatalf("C4 revocation intent = %+v; want stored organization and field scope", c4Payload) + } + + // The history cursor is opaque and tied to the current subject and state filter. + firstPage := harness.request(t, http.MethodGet, "/api/v1/me/consents?limit=1", "", "", candidateCookie.Value, "", "192.0.2.63:1234") + if firstPage.Code != http.StatusOK || firstPage.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("first consent page = %d, Cache-Control=%q, body=%s", firstPage.Code, firstPage.Header().Get("Cache-Control"), firstPage.Body.String()) + } + var page struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor string `json:"next_cursor"` + } `json:"page"` + } + if err := json.Unmarshal(firstPage.Body.Bytes(), &page); err != nil || len(page.Items) != 1 || !page.Page.HasMore || page.Page.NextCursor == "" { + t.Fatalf("first consent page = %+v, %v", page, err) + } + secondPage := harness.request(t, http.MethodGet, "/api/v1/me/consents?limit=1&cursor="+page.Page.NextCursor, "", "", candidateCookie.Value, "", "192.0.2.64:1234") + var next struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + } + if secondPage.Code != http.StatusOK || json.Unmarshal(secondPage.Body.Bytes(), &next) != nil || len(next.Items) != 1 || next.Items[0].ID == page.Items[0].ID { + t.Fatalf("second consent page = %d %s", secondPage.Code, secondPage.Body.String()) + } + foreignCursor := harness.request(t, http.MethodGet, "/api/v1/me/consents?cursor="+page.Page.NextCursor, "", "", employerCookie.Value, "", "192.0.2.65:1234") + requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed") + employerList := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", employerCookie.Value, "", "192.0.2.66:1234") + var employerHistory struct { + Items []json.RawMessage `json:"items"` + } + if employerList.Code != http.StatusOK || json.Unmarshal(employerList.Body.Bytes(), &employerHistory) != nil || len(employerHistory.Items) != 0 { + t.Fatalf("employer consent history = %d %s", employerList.Code, employerList.Body.String()) + } + + // C1 deletion is durable, idempotent, and independent of a later consent grant. + c1Text := harness.request(t, http.MethodGet, "/api/v1/identity/consent-texts/c1", "", "", "", "", "192.0.2.67:1234") + var c1Current struct { + TextVersion string `json:"text_version"` + } + if c1Text.Code != http.StatusOK || json.Unmarshal(c1Text.Body.Bytes(), &c1Current) != nil { + t.Fatalf("read C1 text = %d %s", c1Text.Code, c1Text.Body.String()) + } + c1Grant := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c1", c1Current.TextVersion, sessionHTTPTestOrigin) + if c1Grant.Code != http.StatusOK { + t.Fatalf("C1 grant = %d %s", c1Grant.Code, c1Grant.Body.String()) + } + var deletionEventsBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsBefore); err != nil { + t.Fatalf("count deletion events before request: %v", err) + } + badDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, "wrong-token", "192.0.2.68:1234") + requireSessionProblem(t, badDeletion, http.StatusForbidden, "csrf_check_failed") + assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 0) + requestDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.69:1234") + if requestDeletion.Code != http.StatusAccepted || requestDeletion.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("account deletion request = %d %s", requestDeletion.Code, requestDeletion.Body.String()) + } + var firstDeletion struct { + ID string `json:"id"` + Status string `json:"status"` + } + if err := json.Unmarshal(requestDeletion.Body.Bytes(), &firstDeletion); err != nil || firstDeletion.ID == "" || firstDeletion.Status != "requested" { + t.Fatalf("decode deletion request = %+v, %v", firstDeletion, err) + } + repeatedDeletion := harness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.70:1234") + var repeatedBody struct { + ID string `json:"id"` + } + if repeatedDeletion.Code != http.StatusAccepted || json.Unmarshal(repeatedDeletion.Body.Bytes(), &repeatedBody) != nil || repeatedBody.ID != firstDeletion.ID { + t.Fatalf("repeated deletion request = %d %s", repeatedDeletion.Code, repeatedDeletion.Body.String()) + } + assertRowCount(ctx, t, harness.pool, accountDeletionRequestsTable, 1) + var deletionEventsAfter int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsAfter); err != nil { + t.Fatalf("count deletion events after request: %v", err) + } + if deletionEventsAfter != deletionEventsBefore+1 { + t.Fatalf("deletion event count changed by %d, want one", deletionEventsAfter-deletionEventsBefore) + } + if _, err := store.ConsentLedger().Current(ctx, candidate.ID, domain.ConsentPurposePersonalData); err == nil { + t.Fatal("C1 remained active after its deletion request") + } + laterC1 := consentGrantHTTP(t, harness, candidateCookie, candidateCSRF, "c1", c1Current.TextVersion, sessionHTTPTestOrigin) + if laterC1.Code != http.StatusOK { + t.Fatalf("later C1 grant = %d %s", laterC1.Code, laterC1.Body.String()) + } + var activeDeletionID string + if err := harness.pool.QueryRow(ctx, `SELECT id FROM account_deletion_requests WHERE subject_id = $1 AND status IN ('requested','processing')`, candidate.ID).Scan(&activeDeletionID); err != nil || activeDeletionID != firstDeletion.ID { + t.Fatalf("active deletion request after later C1 grant = %q, %v", activeDeletionID, err) + } + listBeforeRestart := harness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", candidateCookie.Value, "", "192.0.2.71:1234") + if listBeforeRestart.Code != http.StatusOK { + t.Fatalf("consent history before API restart = %d %s", listBeforeRestart.Code, listBeforeRestart.Body.String()) + } + var deletionRowsBeforeRestart, deletionEventsBeforeRestart int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM account_deletion_requests WHERE subject_id = $1`, candidate.ID).Scan(&deletionRowsBeforeRestart); err != nil { + t.Fatalf("count deletion requests before API restart: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsBeforeRestart); err != nil { + t.Fatalf("count deletion events before API restart: %v", err) + } + + // Reconstruct the API and session services over the same database and reuse + // the existing cookie. History and the durable deletion request survive. + restartedHarness := newConsentHTTPHarness(ctx, t, env) + listAfterRestart := restartedHarness.request(t, http.MethodGet, "/api/v1/me/consents", "", "", candidateCookie.Value, "", "192.0.2.72:1234") + if listAfterRestart.Code != http.StatusOK || listAfterRestart.Body.String() != listBeforeRestart.Body.String() { + t.Fatalf("consent history after API restart = %d %s; before=%s", listAfterRestart.Code, listAfterRestart.Body.String(), listBeforeRestart.Body.String()) + } + deletionAfterRestart := restartedHarness.request(t, http.MethodPost, "/api/v1/me/account-deletion-requests", "", sessionHTTPTestOrigin, candidateCookie.Value, candidateCSRF, "192.0.2.73:1234") + var deletionAfterRestartBody struct { + ID string `json:"id"` + } + if deletionAfterRestart.Code != http.StatusAccepted || json.Unmarshal(deletionAfterRestart.Body.Bytes(), &deletionAfterRestartBody) != nil || deletionAfterRestartBody.ID != firstDeletion.ID { + t.Fatalf("deletion request after API restart = %d %s, want durable request %s", deletionAfterRestart.Code, deletionAfterRestart.Body.String(), firstDeletion.ID) + } + var deletionRowsAfterRestart, deletionEventsAfterRestart int64 + if err := restartedHarness.pool.QueryRow(ctx, `SELECT count(*) FROM account_deletion_requests WHERE subject_id = $1`, candidate.ID).Scan(&deletionRowsAfterRestart); err != nil { + t.Fatalf("count deletion requests after API restart: %v", err) + } + if err := restartedHarness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE event_type = 'privacy.account_deletion_requested'`).Scan(&deletionEventsAfterRestart); err != nil { + t.Fatalf("count deletion events after API restart: %v", err) + } + if deletionRowsAfterRestart != deletionRowsBeforeRestart || deletionEventsAfterRestart != deletionEventsBeforeRestart { + t.Fatalf("API reconstruction duplicated deletion state: rows %d->%d, events %d->%d", deletionRowsBeforeRestart, deletionRowsAfterRestart, deletionEventsBeforeRestart, deletionEventsAfterRestart) + } + + if strings.Contains(harness.logs.String(), candidateCookie.Value) || strings.Contains(harness.logs.String(), employerCookie.Value) || + strings.Contains(restartedHarness.logs.String(), candidateCookie.Value) { + t.Fatal("a session token reached request logs") + } +} + +func createConsentHTTPEmployer( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + now := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", email, err) + } + verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(%s) error = %v", email, err) + } + return verified +} + +func newConsentHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + consentStore := postgresadapter.NewConsentStore(pool) + consentReader := consent.NewQueryService(consentStore, time.Now) + consentCommands := consent.NewService(postgresadapter.NewTransactor(pool), time.Now) + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + consentHandler := v1.NewConsentHandler(consentReader, consentCommands) + handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler), v1.WithConsent(consentHandler)) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func loginConsentHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) (*http.Cookie, string) { + t.Helper() + response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr) + if response.Code != http.StatusCreated { + t.Fatalf("login %s = %d %s", email, response.Code, response.Body.String()) + } + cookie := requireSessionCookie(t, response) + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" { + t.Fatalf("decode login CSRF token: %v", err) + } + return cookie, body.CSRFToken +} + +func consentGrantHTTP(t *testing.T, harness *sessionHTTPHarness, cookie *http.Cookie, csrf, purpose, version, origin string) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(struct { + TextVersion string `json:"text_version"` + Accepted bool `json:"accepted"` + }{TextVersion: version, Accepted: true}) + if err != nil { + t.Fatalf("marshal consent grant: %v", err) + } + return harness.request(t, http.MethodPut, "/api/v1/me/consents/"+purpose, string(body), origin, cookie.Value, csrf, "192.0.2.80:1234") +} diff --git a/backend/integration_test/consent_ledger_test.go b/backend/integration_test/consent_ledger_test.go new file mode 100644 index 0000000..c878644 --- /dev/null +++ b/backend/integration_test/consent_ledger_test.go @@ -0,0 +1,1004 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "slices" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + consentTestTimeout = 3 * time.Minute + // consentDemoVersionSuffix completes the version of every demo text that + // migration 00009 publishes, such as "c1-2026-10-01". + consentDemoVersionSuffix = "-2026-10-01" + // consentSecondC1Body is a later C1 text that the test publishes the + // way a migration would, as consentSecondC1Version. + consentSecondC1Body = "I consent to the processing of my personal data, version two." + consentOrganizationName = "Acme Synthetic LLC" + consentPageSize = 10 + // concurrentConsentGrants grants one version at once, each on its own + // connection. + concurrentConsentGrants = 8 + consentRaceRounds = 20 + consentCheckViolation = "23514" + consentForeignKeyViolation = "23503" + consentIntegrityViolation = "23000" + // consentRestrictViolation is raised by ON DELETE RESTRICT. + consentRestrictViolation = "23001" +) + +const consentSecondC1Version domain.ConsentTextVersion = "c1-2026-10-05" + +var ( + consentRecordsTable = pgx.Identifier{"consent_records"} + accountDeletionRequestsTable = pgx.Identifier{"account_deletion_requests"} + // consentTables reference users, so every TRUNCATE of users names them. + consentTables = []pgx.Identifier{consentRecordsTable, accountDeletionRequestsTable} +) + +// consentFixture works on the bootstrap database. The ledger rows are +// truncated between subtests; the published texts are immutable and shared. +type consentFixture struct { + ctx context.Context + pool *pgxpool.Pool + identity identityFixture + store *postgresadapter.ConsentStore + transactor *postgresadapter.Transactor + // now is a fixed application time after every published text, truncated + // to microseconds like the stored times. + now time.Time +} + +func TestConsentLedger(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), consentTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + fixture := consentFixture{ + ctx: ctx, + pool: pool, + identity: identityFixture{ + ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now, + }, + store: postgresadapter.NewConsentStore(pool), + transactor: postgresadapter.NewTransactor(pool), + now: now, + } + // A second C1 text, published as a migration would publish it. + if _, err := pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + VALUES ('c1', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`, + string(consentSecondC1Version), consentSecondC1Body, now.Add(-24*time.Hour)); err != nil { + t.Fatalf("publish the second C1 text: %v", err) + } + reset := func(t *testing.T) { + t.Helper() + // Every table that references users must be truncated with it. + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("migration publishes one demo text per purpose bound to its hash", func(t *testing.T) { + texts := fixture.store.ConsentTexts() + for _, purpose := range []domain.ConsentPurpose{"c2", "c3", "c4", "c5"} { + text, err := texts.Current(ctx, purpose, now) + if err != nil { + t.Fatalf("Current(%s) error = %v", purpose, err) + } + if string(text.Version()) != string(purpose)+consentDemoVersionSuffix || text.Kind() != domain.ConsentTextKindDemo || + text.Hash() != domain.HashConsentText(text.Body()) { + t.Fatalf("Current(%s) = %s %s %x, want the demo text with its hash", purpose, text.Version(), text.Kind(), text.Hash()) + } + } + current, err := texts.Current(ctx, domain.ConsentPurposePersonalData, now) + if err != nil || current.Version() != consentSecondC1Version { + t.Fatalf("Current(c1) = %s, %v, want the later publication", current.Version(), err) + } + first, err := texts.Current(ctx, domain.ConsentPurposePersonalData, now.Add(-48*time.Hour)) + if err != nil || first.Version() != "c1-2026-10-01" { + t.Fatalf("Current(c1, before the second text) = %s, %v, want c1-2026-10-01", first.Version(), err) + } + if _, err := texts.Current(ctx, domain.ConsentPurposePersonalData, time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC)); !errors.Is(err, outbound.ErrConsentTextNotFound) { + t.Fatalf("Current(before every text) error = %v, want ErrConsentTextNotFound", err) + } + if _, err := texts.Get(ctx, domain.ConsentPurposePublication, "c2-1999-01-01"); !errors.Is(err, outbound.ErrConsentTextNotFound) { + t.Fatalf("Get(unknown version) error = %v, want ErrConsentTextNotFound", err) + } + // A version belongs to its purpose. + if _, err := texts.Get(ctx, domain.ConsentPurposePublication, "c1-2026-10-01"); !errors.Is(err, outbound.ErrConsentTextNotFound) { + t.Fatalf("Get(version of another purpose) error = %v, want ErrConsentTextNotFound", err) + } + }) + + t.Run("versions and purposes keep their own history", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "history@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + firstC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-72*time.Hour)) + publication := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(-2*time.Hour)) + before := fixture.rawRecord(t, firstC1.ID()) + secondC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, consentSecondC1Version, domain.ConsentSourceConsentSettings, now.Add(-time.Hour)) + + if before != fixture.rawRecord(t, firstC1.ID()) { + t.Fatal("a newer version changed the stored record of the earlier version") + } + current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePersonalData) + if err != nil || current.ID() != secondC1.ID() { + t.Fatalf("Current(c1) = %s, %v, want the newer version", current, err) + } + page := fixture.list(t, subject.ID, "") + assertConsentIDs(t, page.Records, secondC1.ID(), publication.ID(), firstC1.ID()) + assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateSuperseded) + + // Repeating a grant of a version that is still unrevoked stores nothing. + grant := fixture.newGrant(t, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceConsentSettings, now) + repeated, created, err := ledger.Grant(ctx, grant) + if err != nil || created || repeated.ID() != firstC1.ID() || repeated.State() != domain.ConsentStateSuperseded { + t.Fatalf("Grant(repeat) = %s, %v, %v, want the existing superseded record", repeated, created, err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 3) + + // Purposes are independent: revoking C2 leaves C1 as it was. + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now) + assertConsentIDs(t, revoked, publication.ID()) + if current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePersonalData); err != nil || current.ID() != secondC1.ID() { + t.Fatalf("Current(c1) after revoking C2 = %s, %v, want it unchanged", current, err) + } + }) + + t.Run("revocation stamps once and a new grant is a new record", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "revoke@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + first := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, "c3-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(-time.Hour)) + + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now) + assertConsentIDs(t, revoked, first.ID()) + if revokedAt, ok := revoked[0].RevokedAt(); !ok || !revokedAt.Equal(now) || revoked[0].RevocationSource() != domain.ConsentRevocationSourceConsentSettings { + t.Fatalf("revocation = %v %v %q, want the stamp", revokedAt, ok, revoked[0].RevocationSource()) + } + // A repeat finds nothing to revoke and keeps the first stamp. + if again := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now.Add(time.Minute)); len(again) != 0 { + t.Fatalf("second Revoke() = %v, want nothing", again) + } + if _, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposeAutoCategorization); !errors.Is(err, outbound.ErrConsentNotFound) { + t.Fatalf("Current(revoked) error = %v, want ErrConsentNotFound", err) + } + + regranted := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeAutoCategorization, "c3-2026-10-01", domain.ConsentSourceConsentSettings, now.Add(2*time.Minute)) + if regranted.ID() == first.ID() { + t.Fatal("a grant after a revocation reused the revoked record") + } + page := fixture.list(t, subject.ID, "") + assertConsentIDs(t, page.Records, regranted.ID(), first.ID()) + assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateRevoked) + if revokedAt, _ := page.Records[1].RevokedAt(); !revokedAt.Equal(now) { + t.Fatalf("revoked record stamp = %v, want the first revocation %v", revokedAt, now) + } + + // Revoking a purpose closes superseded records too. + olderC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-48*time.Hour)) + newerC1 := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePersonalData, consentSecondC1Version, domain.ConsentSourceConsentSettings, now) + closed := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePersonalData, uuid.Nil, now.Add(time.Hour)) + if len(closed) != 2 || !slices.ContainsFunc(closed, func(r domain.ConsentRecord) bool { return r.ID() == olderC1.ID() }) || + !slices.ContainsFunc(closed, func(r domain.ConsentRecord) bool { return r.ID() == newerC1.ID() }) { + t.Fatalf("Revoke(c1) = %v, want both C1 records", closed) + } + }) + + t.Run("C4 requires its scope and records it once per invitation", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "contact@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + other := fixture.identity.createUser(t, "other-contact@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + organization, otherOrganization := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()) + invitation := uuid.Must(uuid.NewV7()) + + // The generic grant refuses C4, and the scoped grant refuses a missing scope. + if _, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subject.ID, Purpose: domain.ConsentPurposeContactDisclosure, TextVersion: "c4-2026-10-01", + TextHash: domain.HashConsentText("x"), Source: domain.ConsentSourceInvitationAcceptance, GrantedAt: now, + }); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("NewConsentGrant(C4) error = %v, want ErrInvalidConsent", err) + } + if _, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ + SubjectID: subject.ID, OrganizationName: consentOrganizationName, InvitationID: invitation, InvitationTermsVersion: 1, + Text: fixture.text(t, domain.ConsentPurposeContactDisclosure), GrantedAt: now, + }); !errors.Is(err, domain.ErrInvalidConsent) { + t.Fatalf("NewContactConsentGrant(no organization, no fields) error = %v, want ErrInvalidConsent", err) + } + + grant := fixture.newContactGrant(t, subject.ID, organization, invitation, now, domain.ContactFieldPhone, domain.ContactFieldEmail) + record, created, err := ledger.GrantContact(ctx, grant) + if err != nil || !created { + t.Fatalf("GrantContact() = %v, %v, want a new record", created, err) + } + if record.Purpose() != domain.ConsentPurposeContactDisclosure || record.OrganizationID() != organization || + record.OrganizationName() != consentOrganizationName || record.InvitationID() != invitation || + record.InvitationTermsVersion() != 2 || record.Source() != domain.ConsentSourceInvitationAcceptance || + fmt.Sprint(record.Fields().Fields()) != "[email phone]" || record.TextHash() != grant.TextHash() { + t.Fatalf("C4 record = %s with scope %s %s %v, want the granted scope", record, record.OrganizationID(), record.InvitationID(), record.Fields().Fields()) + } + // The shown text names the organization, so its hash is not the hash + // of the published template. + template := fixture.text(t, domain.ConsentPurposeContactDisclosure) + if record.TextHash() == template.Hash() { + t.Fatal("the C4 record must keep the hash of the shown text, not of the template") + } + + repeat := fixture.newContactGrant(t, subject.ID, organization, invitation, now.Add(time.Minute), domain.ContactFieldEmail) + again, created, err := ledger.GrantContact(ctx, repeat) + if err != nil || created || again.ID() != record.ID() || !again.Fields().Equal(record.Fields()) { + t.Fatalf("GrantContact(repeat) = %s, %v, %v, want the existing record unchanged", again, created, err) + } + taken := fixture.newContactGrant(t, other.ID, organization, invitation, now, domain.ContactFieldEmail) + if _, _, err := ledger.GrantContact(ctx, taken); !errors.Is(err, outbound.ErrConsentInvitationTaken) { + t.Fatalf("GrantContact(invitation of another subject) error = %v, want ErrConsentInvitationTaken", err) + } + + second := fixture.newContactGrant(t, subject.ID, otherOrganization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldTelegram) + secondRecord, _, err := ledger.GrantContact(ctx, second) + if err != nil { + t.Fatalf("GrantContact(other organization) error = %v", err) + } + currentA, err := ledger.CurrentContact(ctx, subject.ID, organization) + if err != nil { + t.Fatalf("CurrentContact(A) error = %v", err) + } + assertConsentIDs(t, currentA, record.ID()) + + // C4 is revoked per organization; another organization keeps its consent. + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposeContactDisclosure, organization, now.Add(time.Hour)) + assertConsentIDs(t, revoked, record.ID()) + if currentA, err := ledger.CurrentContact(ctx, subject.ID, organization); err != nil || len(currentA) != 0 { + t.Fatalf("CurrentContact(A) after revocation = %v, %v, want none", currentA, err) + } + currentB, err := ledger.CurrentContact(ctx, subject.ID, otherOrganization) + if err != nil { + t.Fatalf("CurrentContact(B) error = %v", err) + } + assertConsentIDs(t, currentB, secondRecord.ID()) + // The revoked invitation consent never comes back as a new grant. + comeback, created, err := ledger.GrantContact(ctx, fixture.newContactGrant(t, subject.ID, organization, invitation, now.Add(2*time.Hour), domain.ContactFieldEmail)) + if err != nil || created || comeback.State() != domain.ConsentStateRevoked { + t.Fatalf("GrantContact(revoked invitation) = %s, %v, %v, want the revoked record", comeback, created, err) + } + }) + + t.Run("the repository refuses a foreign subject and unbound texts", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "owner@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + stranger := fixture.identity.createUser(t, "stranger@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + publicationText := fixture.text(t, domain.ConsentPurposePublication) + grantWith := func(subjectID uuid.UUID, version domain.ConsentTextVersion, hash domain.ConsentTextHash, at time.Time) error { + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subjectID, Purpose: domain.ConsentPurposePublication, TextVersion: version, TextHash: hash, + Source: domain.ConsentSourceConsentSettings, GrantedAt: at, + }) + if err != nil { + return err + } + _, _, err = ledger.Grant(ctx, grant) + return err + } + for _, test := range []struct { + name string + err error + want error + }{ + {"unknown subject", grantWith(uuid.Must(uuid.NewV7()), publicationText.Version(), publicationText.Hash(), now), outbound.ErrUserNotFound}, + {"empty version", grantWith(subject.ID, "", publicationText.Hash(), now), domain.ErrInvalidConsentText}, + {"malformed version", grantWith(subject.ID, "c2 2026", publicationText.Hash(), now), domain.ErrInvalidConsentText}, + {"empty hash", grantWith(subject.ID, publicationText.Version(), domain.ConsentTextHash{}, now), domain.ErrInvalidConsentText}, + {"invented version", grantWith(subject.ID, "c2-2099-01-01", publicationText.Hash(), now), outbound.ErrConsentTextNotFound}, + {"version of another purpose", grantWith(subject.ID, "c3-2026-10-01", publicationText.Hash(), now), outbound.ErrConsentTextNotFound}, + {"hash of another text", grantWith(subject.ID, publicationText.Version(), domain.HashConsentText("edited text"), now), outbound.ErrConsentTextMismatch}, + {"grant before publication", grantWith(subject.ID, publicationText.Version(), publicationText.Hash(), publicationText.PublishedAt().Add(-time.Second)), outbound.ErrConsentTextNotPublished}, + } { + if !errors.Is(test.err, test.want) { + t.Fatalf("Grant(%s) error = %v, want %v", test.name, test.err, test.want) + } + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + // Reads and revocations are scoped by the subject: the stranger + // neither sees nor revokes the owner's consent. + owned := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, publicationText.Version(), domain.ConsentSourceConsentSettings, now) + if revoked := fixture.revoke(t, ledger, stranger.ID, domain.ConsentPurposePublication, uuid.Nil, now.Add(time.Minute)); len(revoked) != 0 { + t.Fatalf("Revoke(stranger) = %v, want nothing", revoked) + } + if _, err := ledger.Current(ctx, stranger.ID, domain.ConsentPurposePublication); !errors.Is(err, outbound.ErrConsentNotFound) { + t.Fatalf("Current(stranger) error = %v, want ErrConsentNotFound", err) + } + if current, err := ledger.Current(ctx, subject.ID, domain.ConsentPurposePublication); err != nil || current.ID() != owned.ID() { + t.Fatalf("Current(owner) = %s, %v, want the owner's record", current, err) + } + }) + + t.Run("the database refuses invalid rows written around the repository", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "raw@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + publicationHash := fixture.text(t, domain.ConsentPurposePublication).Hash() + insert := func(purpose, version string, hash []byte, source string, organization *uuid.UUID, fields []string, revocation *string) error { + var invitation *uuid.UUID + var terms *int64 + if organization != nil { + id, version := uuid.Must(uuid.NewV7()), int64(1) + invitation, terms = &id, &version + } + var revokedAt *time.Time + if revocation != nil { + revokedAt = &now + if *revocation == "" { + revocation = nil + } + } + _, err := pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, organization_id, + field_set, invitation_id, invitation_terms_version, granted_at, revoked_at, revocation_source + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)`, + uuid.Must(uuid.NewV7()), subject.ID, purpose, version, hash, source, organization, + fields, invitation, terms, now, revokedAt, revocation) + return err + } + organization := uuid.Must(uuid.NewV7()) + empty := "" + for _, test := range []struct { + name string + err error + code string + constraint string + }{ + {"empty version", insert("c2", "", publicationHash[:], "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_version_format"}, + {"empty hash", insert("c2", "c2-2026-10-01", []byte{}, "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_hash_sha256"}, + {"short hash", insert("c2", "c2-2026-10-01", publicationHash[:31], "consent_settings", nil, nil, nil), consentCheckViolation, "consent_records_text_hash_sha256"}, + {"C4 without a scope", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C4 with an empty field set", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C4 with a repeated field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"email", "email"}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C4 with an unknown field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"address"}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C2 with a scope", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", &organization, []string{"email"}, nil), consentCheckViolation, "consent_records_c4_scope"}, + {"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_registration_version"}, + {"C2 from an invitation", insert("c2", "c2-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"}, + {"revocation without a source", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", nil, nil, &empty), consentCheckViolation, "consent_records_revocation_stamp"}, + {"hash of another text", insert("c3", "c3-2026-10-01", publicationHash[:], "consent_settings", nil, nil, nil), consentForeignKeyViolation, "consent_records_published_text_fkey"}, + } { + assertSQLError(t, test.name, test.err, test.code, test.constraint) + } + + ledger := fixture.store.ConsentLedger() + record := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) + _, err := pool.Exec(ctx, `UPDATE consent_records SET text_version = 'c2-2026-10-02' WHERE id = $1`, record.ID()) + assertSQLError(t, "update of a granted record", err, consentIntegrityViolation, "consent_records_immutable") + _, err = pool.Exec(ctx, `UPDATE consent_records SET revoked_at = granted_at, revocation_source = 'consent_settings', granted_at = granted_at - interval '1 day' WHERE id = $1`, record.ID()) + assertSQLError(t, "revocation that also moves the grant", err, consentIntegrityViolation, "consent_records_immutable") + fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now) + _, err = pool.Exec(ctx, `UPDATE consent_records SET revoked_at = revoked_at + interval '1 hour' WHERE id = $1`, record.ID()) + assertSQLError(t, "second revocation stamp", err, consentIntegrityViolation, "consent_records_immutable") + _, err = pool.Exec(ctx, `UPDATE consent_texts SET body = body || '.' WHERE purpose = 'c2'`) + assertSQLError(t, "update of a published text", err, consentIntegrityViolation, "consent_texts_immutable") + _, err = pool.Exec(ctx, `DELETE FROM consent_texts WHERE purpose = 'c2'`) + assertSQLError(t, "delete of a published text", err, consentIntegrityViolation, "consent_texts_immutable") + // Consent evidence outlives a careless account delete. + _, err = pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, subject.ID) + assertSQLError(t, "delete of an account with consent history", err, consentRestrictViolation, "consent_records_subject_id_fkey") + }) + + t.Run("the read model returns only the caller's own records page by page", func(t *testing.T) { + reset(t) + owner := fixture.identity.createUser(t, "reader@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + stranger := fixture.identity.createUser(t, "neighbour@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + strangerRecord := fixture.grant(t, ledger, stranger.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-30*time.Minute)) + var owned []uuid.UUID + for index, purpose := range []domain.ConsentPurpose{"c1", "c2", "c3", "c5"} { + record := fixture.grant(t, ledger, owner.ID, purpose, domain.ConsentTextVersion(string(purpose)+consentDemoVersionSuffix), + domain.ConsentSourceConsentSettings, now.Add(time.Duration(index-10)*time.Minute)) + owned = append([]uuid.UUID{record.ID()}, owned...) + } + fixture.revoke(t, ledger, owner.ID, domain.ConsentPurposeAutoCategorization, uuid.Nil, now) + + var seen []uuid.UUID + query := outbound.ConsentListQuery{SubjectID: owner.ID, Limit: 3} + for range 3 { + page, err := ledger.List(ctx, query) + if err != nil { + t.Fatalf("List() error = %v", err) + } + for _, record := range page.Records { + if record.SubjectID() != owner.ID { + t.Fatalf("List(owner) returned %s of another subject", record) + } + seen = append(seen, record.ID()) + } + if !page.HasMore { + break + } + position := outbound.ConsentPositionOf(page.Records[len(page.Records)-1]) + query.After = &position + } + if !slices.Equal(seen, owned) || slices.Contains(seen, strangerRecord.ID()) { + t.Fatalf("pages = %v, want exactly the owner's records newest first %v", seen, owned) + } + active := fixture.list(t, owner.ID, domain.ConsentStateActive) + if len(active.Records) != 3 || slices.ContainsFunc(active.Records, func(r domain.ConsentRecord) bool { return r.Purpose() == domain.ConsentPurposeAutoCategorization }) { + t.Fatalf("List(active) = %v, want the three unrevoked purposes", active.Records) + } + revoked := fixture.list(t, owner.ID, domain.ConsentStateRevoked) + if len(revoked.Records) != 1 || revoked.Records[0].Purpose() != domain.ConsentPurposeAutoCategorization { + t.Fatalf("List(revoked) = %v, want the revoked C3", revoked.Records) + } + if empty := fixture.list(t, uuid.Must(uuid.NewV7()), ""); len(empty.Records) != 0 || empty.HasMore { + t.Fatalf("List(unknown subject) = %v, want an empty page", empty.Records) + } + }) + + t.Run("a C4 grant commits and rolls back with its business transaction", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "accept@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + organization := uuid.Must(uuid.NewV7()) + + rolledBack := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, created, err := unit.ConsentLedger().GrantContact(ctx, rolledBack); err != nil || !created { + return fmt.Errorf("grant inside the acceptance: created %v: %w", created, err) + } + // A later step of the acceptance fails, for example the state + // transition or the contact grant. + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the forced rollback", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + // A failing statement after the grant aborts the whole acceptance. + failing := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) + unknownSubject := fixture.newContactGrant(t, uuid.Must(uuid.NewV7()), organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail) + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if _, _, err := unit.ConsentLedger().GrantContact(ctx, failing); err != nil { + return err + } + _, _, err := unit.ConsentLedger().GrantContact(ctx, unknownSubject) + return err + }) + if !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("WithinTransaction(failing step) error = %v, want ErrUserNotFound", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + committed := fixture.newContactGrant(t, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail, domain.ContactFieldFullName) + var record domain.ConsentRecord + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + record, _, err = unit.ConsentLedger().GrantContact(ctx, committed) + if err != nil { + return err + } + // The same transaction sees its own grant before the commit. + current, err := unit.ConsentLedger().CurrentContact(ctx, subject.ID, organization) + if err != nil || len(current) != 1 { + return fmt.Errorf("read own grant: %d records: %w", len(current), err) + } + return nil + }) + if err != nil { + t.Fatalf("WithinTransaction(commit) error = %v", err) + } + current, err := fixture.store.ConsentLedger().CurrentContact(ctx, subject.ID, organization) + if err != nil { + t.Fatalf("CurrentContact() error = %v", err) + } + assertConsentIDs(t, current, record.ID()) + }) + + t.Run("the unverified account cleanup removes the ledger of the accounts it deletes", func(t *testing.T) { + reset(t) + users := fixture.identity.store.Users() + ledger := fixture.store.ConsentLedger() + cutoff := now.Add(-time.Hour) + stale := fixture.identity.createUser(t, "stale-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-time.Hour)) + fixture.grant(t, ledger, stale.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-time.Hour)) + verified := fixture.identity.createUser(t, "verified-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-2*time.Hour)) + kept := fixture.grant(t, ledger, verified.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-2*time.Hour)) + if _, err := users.MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, cutoff.Add(-90*time.Minute)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + + deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) + } + if _, err := users.GetByID(ctx, stale.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(stale) error = %v, want ErrUserNotFound", err) + } + page := fixture.list(t, verified.ID, "") + assertConsentIDs(t, page.Records, kept.ID()) + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("the database checks the C4 hash against the organization name snapshot", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "snapshot@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + text := fixture.text(t, domain.ConsentPurposeContactDisclosure) + shownFor := func(name string) []byte { + shown, err := text.RenderForOrganization(name) + if err != nil { + t.Fatalf("RenderForOrganization(%q) error = %v", name, err) + } + hash := domain.HashConsentText(shown) + return hash[:] + } + insert := func(purpose, name string, hash []byte) error { + var organization, invitation *uuid.UUID + var fields []string + var terms *int64 + source := "consent_settings" + version := purpose + consentDemoVersionSuffix + if purpose == "c4" { + organizationID, invitationID, termsVersion := uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), int64(1) + organization, invitation, terms, fields, source = &organizationID, &invitationID, &termsVersion, []string{"email"}, "invitation_acceptance" + } + _, err := pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, organization_id, organization_name, + field_set, invitation_id, invitation_terms_version, granted_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, + uuid.Must(uuid.NewV7()), subject.ID, purpose, version, hash, source, organization, name, + fields, invitation, terms, now) + return err + } + personalData := fixture.text(t, domain.ConsentPurposePersonalData) + personalHash := personalData.Hash() + assertSQLError(t, "hash of another organization name", insert("c4", consentOrganizationName, shownFor("Other LLC")), + consentCheckViolation, "consent_records_c4_text_hash") + assertSQLError(t, "name other than the shown one", insert("c4", "Other LLC", shownFor(consentOrganizationName)), + consentCheckViolation, "consent_records_c4_text_hash") + templateHash := text.Hash() + assertSQLError(t, "hash of the template", insert("c4", consentOrganizationName, templateHash[:]), + consentCheckViolation, "consent_records_c4_text_hash") + assertSQLError(t, "C4 without a name", func() error { + _, err := pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, organization_id, field_set, + invitation_id, invitation_terms_version, granted_at + ) VALUES ($1, $2, 'c4', 'c4-2026-10-01', $3, 'invitation_acceptance', $4, '{email}', $5, 1, $6)`, + uuid.Must(uuid.NewV7()), subject.ID, shownFor(consentOrganizationName), uuid.Must(uuid.NewV7()), uuid.Must(uuid.NewV7()), now) + return err + }(), consentCheckViolation, "consent_records_c4_scope") + assertSQLError(t, "C1 with an organization name", insert("c1", consentOrganizationName, personalHash[:]), + consentCheckViolation, "consent_records_c4_scope") + if err := insert("c4", consentOrganizationName, shownFor(consentOrganizationName)); err != nil { + t.Fatalf("insert the hash of the shown text: %v", err) + } + + // The organization is renamed between two acceptances: each record + // keeps the name its own text showed, and its hash still proves that + // text. + ledger := fixture.store.ConsentLedger() + organization := uuid.Must(uuid.NewV7()) + before, _, err := ledger.GrantContact(ctx, fixture.newNamedContactGrant(t, consentOrganizationName, subject.ID, organization, uuid.Must(uuid.NewV7()), now, domain.ContactFieldEmail)) + if err != nil { + t.Fatalf("GrantContact(before the rename) error = %v", err) + } + const renamed = "Acme Renamed LLC" + after, _, err := ledger.GrantContact(ctx, fixture.newNamedContactGrant(t, renamed, subject.ID, organization, uuid.Must(uuid.NewV7()), now.Add(time.Minute), domain.ContactFieldPhone)) + if err != nil { + t.Fatalf("GrantContact(after the rename) error = %v", err) + } + current, err := ledger.CurrentContact(ctx, subject.ID, organization) + if err != nil { + t.Fatalf("CurrentContact() error = %v", err) + } + assertConsentIDs(t, current, after.ID(), before.ID()) + for index, want := range []string{renamed, consentOrganizationName} { + record := current[index] + if record.OrganizationName() != want { + t.Fatalf("record %s name = %q, want the snapshot %q", record, record.OrganizationName(), want) + } + if hash := record.TextHash(); !slices.Equal(shownFor(record.OrganizationName()), hash[:]) { + t.Fatalf("record %s hash does not prove the text shown with its snapshot", record) + } + } + }) + + t.Run("a revocation before the grant time is stamped at the grant time", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "skew@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := fixture.store.ConsentLedger() + record := fixture.grant(t, ledger, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) + revoked := fixture.revoke(t, ledger, subject.ID, domain.ConsentPurposePublication, uuid.Nil, now.Add(-time.Hour)) + assertConsentIDs(t, revoked, record.ID()) + if revokedAt, _ := revoked[0].RevokedAt(); !revokedAt.Equal(now) { + t.Fatalf("revoked_at = %v, want the grant time %v", revokedAt, now) + } + }) + + t.Run("only the consent of an unconfirmed account can be deleted", func(t *testing.T) { + reset(t) + ledger := fixture.store.ConsentLedger() + confirmed := fixture.identity.createUser(t, "confirmed@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + retained := fixture.grant(t, ledger, confirmed.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-72*time.Hour)) + if _, err := fixture.identity.store.Users().MarkEmailVerified(ctx, confirmed.ID, confirmed.RegistrationVersion, now.Add(-71*time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + unconfirmed := fixture.identity.createUser(t, "unconfirmed@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) + discardable := fixture.grant(t, ledger, unconfirmed.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-time.Hour)) + + _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, retained.ID()) + assertSQLError(t, "delete of a confirmed account's consent", err, consentIntegrityViolation, "consent_records_retained") + if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1`, discardable.ID()); err != nil { + t.Fatalf("delete of an unconfirmed account's consent: %v", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("re-registration of an unverified account replaces its registration C1", func(t *testing.T) { + reset(t) + ledger := fixture.store.ConsentLedger() + first := fixture.identity.createUser(t, "reregister@example.com", domain.ScenarioCandidate, now.Add(-2*time.Hour)) + earlier := fixture.grant(t, ledger, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-2*time.Hour)) + + changed, err := first.ReRegister(fixture.identity.registration(t, "reregister@example.com", domain.ScenarioEmployer, now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + var replacement domain.ConsentRecord + var registered domain.User + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + registered, err = unit.Users().UpdateRegistration(ctx, changed) + if err != nil { + return err + } + grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now, registered.RegistrationVersion) + var created bool + replacement, created, err = unit.ConsentLedger().Grant(ctx, grant) + if err == nil && !created { + return errors.New("the new registration reused the earlier registrant's C1") + } + return err + }) + if err != nil { + t.Fatalf("re-registration transaction error = %v", err) + } + page := fixture.list(t, first.ID, "") + assertConsentIDs(t, page.Records, replacement.ID()) + if replacement.ID() == earlier.ID() { + t.Fatal("the earlier registrant's C1 survived the re-registration") + } + if replacement.RegistrationVersion() != registered.RegistrationVersion { + t.Fatalf("replacement C1 registration version = %d, want %d", replacement.RegistrationVersion(), registered.RegistrationVersion) + } + + // A stale re-registration changes nothing and deletes nothing. + if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, changed); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(stale) error = %v, want ErrUserVersionConflict", err) + } + assertConsentIDs(t, fixture.list(t, first.ID, "").Records, replacement.ID()) + + // A verified account is never re-registered, so its C1 stays. + verified := fixture.identity.createUser(t, "verified-reregister@example.com", domain.ScenarioCandidate, now.Add(-2*time.Hour)) + kept := fixture.grant(t, ledger, verified.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now.Add(-2*time.Hour)) + if _, err := fixture.identity.store.Users().MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, now.Add(-time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + stale, err := verified.ReRegister(fixture.identity.registration(t, "verified-reregister@example.com", domain.ScenarioEmployer, now)) + if err != nil { + t.Fatalf("ReRegister(the unverified copy) error = %v", err) + } + if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, stale); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(verified) error = %v, want ErrUserVersionConflict", err) + } + assertConsentIDs(t, fixture.list(t, verified.ID, "").Records, kept.ID()) + }) + + t.Run("concurrent grants of one version store one record", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "concurrent@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := postgresadapter.NewConsentStore(env.newPoolWithMaxConns(ctx, t, concurrentConsentGrants)).ConsentLedger() + grants := make([]domain.ConsentGrant, concurrentConsentGrants) + for index := range grants { + grants[index] = fixture.newGrant(t, subject.ID, domain.ConsentPurposePublication, "c2-2026-10-01", domain.ConsentSourceConsentSettings, now) + } + records := make([]domain.ConsentRecord, len(grants)) + createdFlags := make([]bool, len(grants)) + errs := make([]error, len(grants)) + start := make(chan struct{}) + var group sync.WaitGroup + for index, grant := range grants { + group.Go(func() { + <-start + records[index], createdFlags[index], errs[index] = ledger.Grant(ctx, grant) + }) + } + close(start) + group.Wait() + created := 0 + for index, err := range errs { + if err != nil { + t.Fatalf("Grant %d error = %v", index, err) + } + if createdFlags[index] { + created++ + } + if records[index].ID() != records[0].ID() { + t.Fatalf("Grant %d returned %s, want the one record %s", index, records[index], records[0]) + } + } + if created != 1 { + t.Fatalf("%d grants created a record, want exactly 1", created) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("a grant racing a revocation leaves at most one unrevoked record of the version", func(t *testing.T) { + reset(t) + subject := fixture.identity.createUser(t, "race@example.com", domain.ScenarioCandidate, now.Add(-72*time.Hour)) + ledger := postgresadapter.NewConsentStore(env.newPoolWithMaxConns(ctx, t, 2)).ConsentLedger() + fixture.grant(t, ledger, subject.ID, domain.ConsentPurposeFSPImport, "c5-2026-10-01", domain.ConsentSourceConsentSettings, now) + for round := range consentRaceRounds { + at := now.Add(time.Duration(round+1) * time.Minute) + grant := fixture.newGrant(t, subject.ID, domain.ConsentPurposeFSPImport, "c5-2026-10-01", domain.ConsentSourceConsentSettings, at) + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject.ID, Purpose: domain.ConsentPurposeFSPImport, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + var grantErr, revokeErr error + start := make(chan struct{}) + var group sync.WaitGroup + group.Go(func() { <-start; _, _, grantErr = ledger.Grant(ctx, grant) }) + group.Go(func() { <-start; _, revokeErr = ledger.Revoke(ctx, revocation) }) + close(start) + group.Wait() + // The only documented race outcome is a conflict the caller retries. + if grantErr != nil && !errors.Is(grantErr, outbound.ErrTransactionConflict) { + t.Fatalf("round %d Grant() error = %v", round, grantErr) + } + if revokeErr != nil { + t.Fatalf("round %d Revoke() error = %v", round, revokeErr) + } + var unrevoked int + if err := pool.QueryRow(ctx, ` + SELECT count(*) FROM consent_records + WHERE subject_id = $1 AND purpose = 'c5' AND revoked_at IS NULL`, subject.ID).Scan(&unrevoked); err != nil { + t.Fatalf("count unrevoked records: %v", err) + } + if unrevoked > 1 { + t.Fatalf("round %d left %d unrevoked records of one version", round, unrevoked) + } + } + }) + + t.Run("the cleanup skips an account whose consent row is locked", func(t *testing.T) { + reset(t) + cutoff := now.Add(-time.Hour) + stale := fixture.identity.createUser(t, "locked-consent@example.com", domain.ScenarioCandidate, cutoff.Add(-time.Hour)) + fixture.grant(t, fixture.store.ConsentLedger(), stale.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, cutoff.Add(-time.Hour)) + // Only the consent row is locked: a revocation in a transaction that + // stays open and rolls back. + holder := startHeldTransaction(ctx, t, postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, 2)), func(ctx context.Context, unit outbound.UnitOfWork) error { + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: stale.ID, Purpose: domain.ConsentPurposePersonalData, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: cutoff, + }) + if err != nil { + return err + } + revoked, err := unit.ConsentLedger().Revoke(ctx, revocation) + if err == nil && len(revoked) != 1 { + return fmt.Errorf("revoked %d records, want 1", len(revoked)) + } + return err + }, false) + holder.awaitHeld(ctx, t) + + impatient := postgresadapter.NewIdentityStore(env.newPoolWithLockTimeout(ctx, t, cleanupLockTimeout)).Users() + deleted, err := impatient.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 0 { + t.Fatalf("DeleteUnverifiedRegisteredBefore(consent locked) = %d, %v, want 0 without waiting", deleted, err) + } + if err := holder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("holder error = %v, want the forced rollback", err) + } + deleted, err = impatient.DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore(unlocked) = %d, %v, want 1", deleted, err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + }) +} + +func (fixture consentFixture) text(t *testing.T, purpose domain.ConsentPurpose) domain.ConsentText { + t.Helper() + text, err := fixture.store.ConsentTexts().Current(fixture.ctx, purpose, fixture.now) + if err != nil { + t.Fatalf("ConsentTexts().Current(%s) error = %v", purpose, err) + } + return text +} + +func (fixture consentFixture) newGrant( + t *testing.T, + subject uuid.UUID, + purpose domain.ConsentPurpose, + version domain.ConsentTextVersion, + source domain.ConsentSource, + at time.Time, + registrationVersions ...int64, +) domain.ConsentGrant { + t.Helper() + registrationVersion := int64(0) + if source == domain.ConsentSourceRegistration { + registrationVersion = 1 + } + if len(registrationVersions) > 1 { + t.Fatal("newGrant received more than one registration version") + } + if len(registrationVersions) == 1 { + registrationVersion = registrationVersions[0] + } + text, err := fixture.store.ConsentTexts().Get(fixture.ctx, purpose, version) + if err != nil { + t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err) + } + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), + Source: source, RegistrationVersion: registrationVersion, GrantedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + return grant +} + +func (fixture consentFixture) grant( + t *testing.T, + ledger outbound.ConsentLedger, + subject uuid.UUID, + purpose domain.ConsentPurpose, + version domain.ConsentTextVersion, + source domain.ConsentSource, + at time.Time, +) domain.ConsentRecord { + t.Helper() + record, created, err := ledger.Grant(fixture.ctx, fixture.newGrant(t, subject, purpose, version, source, at)) + if err != nil || !created { + t.Fatalf("Grant(%s %s) = %v, %v, want a new record", purpose, version, created, err) + } + return record +} + +// newContactGrant builds the C4 grant of an acceptance of terms version 2 +// for the organization named consentOrganizationName. +func (fixture consentFixture) newContactGrant( + t *testing.T, + subject, organization, invitation uuid.UUID, + at time.Time, + fields ...domain.ContactField, +) domain.ContactConsentGrant { + t.Helper() + return fixture.newNamedContactGrant(t, consentOrganizationName, subject, organization, invitation, at, fields...) +} + +// newNamedContactGrant builds the C4 grant of an acceptance of terms version +// 2 for the organization shown under name; the domain hashes the text as +// shown. +func (fixture consentFixture) newNamedContactGrant( + t *testing.T, + name string, + subject, organization, invitation uuid.UUID, + at time.Time, + fields ...domain.ContactField, +) domain.ContactConsentGrant { + t.Helper() + set, err := domain.NewContactFieldSet(fields...) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + grant, err := domain.NewContactConsentGrant(domain.ContactConsentGrantInput{ + SubjectID: subject, OrganizationID: organization, OrganizationName: name, Fields: set, InvitationID: invitation, + InvitationTermsVersion: 2, Text: fixture.text(t, domain.ConsentPurposeContactDisclosure), GrantedAt: at, + }) + if err != nil { + t.Fatalf("NewContactConsentGrant() error = %v", err) + } + return grant +} + +func (fixture consentFixture) revoke( + t *testing.T, + ledger outbound.ConsentLedger, + subject uuid.UUID, + purpose domain.ConsentPurpose, + organization uuid.UUID, + at time.Time, +) []domain.ConsentRecord { + t.Helper() + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject, Purpose: purpose, OrganizationID: organization, + Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: at, + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + revoked, err := ledger.Revoke(fixture.ctx, revocation) + if err != nil { + t.Fatalf("Revoke(%s) error = %v", purpose, err) + } + for _, record := range revoked { + if record.State() != domain.ConsentStateRevoked { + t.Fatalf("Revoke(%s) returned %s, want revoked records", purpose, record) + } + } + return revoked +} + +func (fixture consentFixture) list(t *testing.T, subject uuid.UUID, state domain.ConsentState) outbound.ConsentPage { + t.Helper() + page, err := fixture.store.ConsentLedger().List(fixture.ctx, outbound.ConsentListQuery{SubjectID: subject, State: state, Limit: consentPageSize}) + if err != nil { + t.Fatalf("List() error = %v", err) + } + return page +} + +// rawRecord returns the whole stored row as JSON, so a test can prove that +// a row stayed byte-for-byte the same. +func (fixture consentFixture) rawRecord(t *testing.T, id uuid.UUID) string { + t.Helper() + var row string + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT row_to_json(stored)::text FROM consent_records AS stored WHERE stored.id = $1`, id).Scan(&row); err != nil { + t.Fatalf("read consent record: %v", err) + } + return row +} + +func assertConsentIDs(t *testing.T, records []domain.ConsentRecord, want ...uuid.UUID) { + t.Helper() + got := make([]uuid.UUID, 0, len(records)) + for _, record := range records { + got = append(got, record.ID()) + } + if !slices.Equal(got, want) { + t.Fatalf("record IDs = %v, want %v", got, want) + } +} + +func assertConsentStates(t *testing.T, page outbound.ConsentPage, want ...domain.ConsentState) { + t.Helper() + got := make([]domain.ConsentState, 0, len(page.Records)) + for _, record := range page.Records { + got = append(got, record.State()) + } + if !slices.Equal(got, want) { + t.Fatalf("record states = %v, want %v", got, want) + } +} + +func assertSQLError(t *testing.T, name string, err error, code, constraint string) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != code || pgError.ConstraintName != constraint { + t.Fatalf("%s: error = %v, want SQLSTATE %s on %s", name, err, code, constraint) + } +} diff --git a/backend/integration_test/consent_usecase_test.go b/backend/integration_test/consent_usecase_test.go new file mode 100644 index 0000000..4ae09d4 --- /dev/null +++ b/backend/integration_test/consent_usecase_test.go @@ -0,0 +1,557 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" +) + +const ( + consentGrantsTestTimeout = 3 * time.Minute + // concurrentConsentRepeats repeats one grant at once, each on its own + // connection. + concurrentConsentRepeats = 8 + // consentScheduledC5Version is a text that is published after the test + // clock, so it is scheduled and not yet current. + consentScheduledC5Version domain.ConsentTextVersion = "c5-2027-01-01" +) + +// consentGrantsFixture runs the consent usecase on the bootstrap database. +type consentGrantsFixture struct { + ctx context.Context + pool *pgxpool.Pool + identity identityFixture + transactor *postgresadapter.Transactor + service *consent.Service + store *postgresadapter.ConsentStore + // nowNanos is the application clock, as Unix nanoseconds. + nowNanos *atomic.Int64 +} + +func (fixture consentGrantsFixture) now() time.Time { + return time.Unix(0, fixture.nowNanos.Load()).UTC() +} + +func (fixture consentGrantsFixture) advance(by time.Duration) { + fixture.nowNanos.Store(fixture.now().Add(by).UnixNano()) +} + +// currentVersion returns the version of the text that is current at the +// application time. +func (fixture consentGrantsFixture) currentVersion(t *testing.T, purpose domain.ConsentPurpose) domain.ConsentTextVersion { + t.Helper() + text, err := fixture.store.ConsentTexts().Current(fixture.ctx, purpose, fixture.now()) + if err != nil { + t.Fatalf("ConsentTexts().Current(%s) error = %v", purpose, err) + } + return text.Version() +} + +func (fixture consentGrantsFixture) grantInput(t *testing.T, subject uuid.UUID, purpose domain.ConsentPurpose) consent.SettingsGrantInput { + t.Helper() + return consent.SettingsGrantInput{SubjectID: subject, Purpose: purpose, TextVersion: fixture.currentVersion(t, purpose)} +} + +// registerC1 records the registration C1 of an existing account in its own +// transaction. +func (fixture consentGrantsFixture) registerC1(t *testing.T, user domain.User) domain.ConsentRecord { + t.Helper() + var result consent.GrantResult + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + result, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, fixture.currentVersion(t, domain.ConsentPurposePersonalData)) + return err + }) + if err != nil || !result.Created { + t.Fatalf("GrantAtRegistration() = %v, %v, want a new record", result.Created, err) + } + return result.Record +} + +// grant records a new consent in its own transaction. +func (fixture consentGrantsFixture) grant(t *testing.T, input consent.SettingsGrantInput) domain.ConsentRecord { + t.Helper() + result, err := fixture.service.GrantInSettingsInNewTransaction(fixture.ctx, input) + if err != nil || !result.Created { + t.Fatalf("GrantInSettingsInNewTransaction(%s %s) = %v, %v, want a new record", input.Purpose, input.TextVersion, result.Created, err) + } + return result.Record +} + +func (fixture consentGrantsFixture) list(t *testing.T, subject uuid.UUID) outbound.ConsentPage { + t.Helper() + page, err := fixture.store.ConsentLedger().List(fixture.ctx, outbound.ConsentListQuery{SubjectID: subject, Limit: consentPageSize}) + if err != nil { + t.Fatalf("List() error = %v", err) + } + return page +} + +func (fixture consentGrantsFixture) revoke(t *testing.T, ledger outbound.ConsentLedger, subject uuid.UUID, purpose domain.ConsentPurpose) []domain.ConsentRecord { + t.Helper() + revocation, err := domain.NewConsentRevocation(domain.ConsentRevocationInput{ + SubjectID: subject, Purpose: purpose, Source: domain.ConsentRevocationSourceConsentSettings, RevokedAt: fixture.now(), + }) + if err != nil { + t.Fatalf("NewConsentRevocation() error = %v", err) + } + revoked, err := ledger.Revoke(fixture.ctx, revocation) + if err != nil { + t.Fatalf("Revoke(%s) error = %v", purpose, err) + } + return revoked +} + +func TestConsentGrants(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), consentGrantsTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + nowNanos := &atomic.Int64{} + nowNanos.Store(start.UnixNano()) + transactor := postgresadapter.NewTransactor(pool) + fixture := consentGrantsFixture{ + ctx: ctx, + pool: pool, + identity: identityFixture{ + ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: start, + }, + transactor: transactor, + store: postgresadapter.NewConsentStore(pool), + nowNanos: nowNanos, + } + fixture.service = consent.NewService(transactor, fixture.now) + // A second C1 text, so that the first one is outdated, and a C5 text + // that is scheduled after the test clock. Both are published the way a + // migration would publish them. + for _, text := range []struct { + purpose, version, body string + publishedAt time.Time + }{ + {"c1", string(consentSecondC1Version), consentSecondC1Body, start.Add(-24 * time.Hour)}, + {"c5", string(consentScheduledC5Version), "I consent to the import of my FSP results, version two.", start.Add(72 * time.Hour)}, + } { + if _, err := pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + VALUES ($1, $2, $3, sha256(convert_to($3, 'UTF8')), 'demo', $4)`, + text.purpose, text.version, text.body, text.publishedAt); err != nil { + t.Fatalf("publish the %s text %s: %v", text.purpose, text.version, err) + } + } + reset := func(t *testing.T) { + t.Helper() + fixture.nowNanos.Store(start.UnixNano()) + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("C1 is written in the registration transaction and the other purposes separately", func(t *testing.T) { + reset(t) + user := fixture.identity.newUser(t, "register@example.com", domain.ScenarioCandidate, start) + c1 := fixture.currentVersion(t, domain.ConsentPurposePersonalData) + + // The registration has no session: the account and its C1 commit + // together on the subject ID alone. + var registered consent.GrantResult + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + var err error + registered, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, c1) + return err + }) + if err != nil || !registered.Created { + t.Fatalf("registration transaction = %v, %v, want an account with a new C1", registered.Created, err) + } + assertRowCount(ctx, t, pool, usersTable, 1) + assertRowCount(ctx, t, pool, sessionsTable, 0) + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + if record := registered.Record; record.SubjectID() != user.ID || record.Source() != domain.ConsentSourceRegistration || + record.RegistrationVersion() != user.RegistrationVersion || + record.TextVersion() != consentSecondC1Version || !record.GrantedAt().Equal(start) { + t.Fatalf("registration C1 = %s %s %v, want the current text at the application time", record.Source(), record.TextVersion(), record.GrantedAt()) + } + + // The user withholds C3 and grants C2 and C5 one by one. + fixture.advance(time.Minute) + publication := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication)) + fixture.advance(time.Minute) + fsp := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposeFSPImport)) + ledger := fixture.store.ConsentLedger() + for purpose, want := range map[domain.ConsentPurpose]uuid.UUID{ + domain.ConsentPurposePersonalData: registered.Record.ID(), + domain.ConsentPurposePublication: publication.ID(), + domain.ConsentPurposeFSPImport: fsp.ID(), + } { + if current, err := ledger.Current(ctx, user.ID, purpose); err != nil || current.ID() != want || current.State() != domain.ConsentStateActive { + t.Fatalf("Current(%s) = %s, %v, want its own active record", purpose, current, err) + } + } + // C3 was not given: no record, and the other purposes did not need it. + if _, err := ledger.Current(ctx, user.ID, domain.ConsentPurposeAutoCategorization); !errors.Is(err, outbound.ErrConsentNotFound) { + t.Fatalf("Current(c3) error = %v, want ErrConsentNotFound", err) + } + + // Granting C3 later, then revoking it, changes no other purpose. + fixture.advance(time.Minute) + categorization := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposeAutoCategorization)) + fixture.advance(time.Minute) + if revoked := fixture.revoke(t, ledger, user.ID, domain.ConsentPurposeAutoCategorization); len(revoked) != 1 || revoked[0].ID() != categorization.ID() { + t.Fatalf("Revoke(c3) = %v, want the C3 record only", revoked) + } + page, err := ledger.List(ctx, outbound.ConsentListQuery{SubjectID: user.ID, Limit: consentPageSize}) + if err != nil { + t.Fatalf("List() error = %v", err) + } + assertConsentIDs(t, page.Records, categorization.ID(), fsp.ID(), publication.ID(), registered.Record.ID()) + assertConsentStates(t, page, domain.ConsentStateRevoked, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateActive) + }) + + t.Run("a failed registration takes its C1 with it", func(t *testing.T) { + reset(t) + user := fixture.identity.newUser(t, "rollback@example.com", domain.ScenarioCandidate, start) + c1 := fixture.currentVersion(t, domain.ConsentPurposePersonalData) + + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + if _, err := fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, c1); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("registration transaction error = %v, want the forced rollback", err) + } + assertRowCount(ctx, t, pool, usersTable, 0) + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + // A grant for a subject that has no account is refused by the ledger + // and stores nothing. + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := fixture.service.GrantAtRegistration(ctx, unit, uuid.New(), 1, c1) + return err + }) + if !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GrantAtRegistration(unknown subject) error = %v, want ErrUserNotFound", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + }) + + t.Run("a repeat stores nothing and an outdated version is rejected", func(t *testing.T) { + reset(t) + user := fixture.identity.createUser(t, "repeat@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour)) + input := fixture.grantInput(t, user.ID, domain.ConsentPurposePublication) + first := fixture.grant(t, input) + + fixture.advance(time.Hour) + repeat, err := fixture.service.GrantInSettingsInNewTransaction(ctx, input) + if err != nil || repeat.Created || repeat.Record.ID() != first.ID() || !repeat.Record.GrantedAt().Equal(start) { + t.Fatalf("GrantInSettingsInNewTransaction(repeat) = %s, %v, %v, want the first record at %v", repeat.Record, repeat.Created, err, start) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + + // The repeat inside a business transaction does not abort it. + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + again, err := fixture.service.GrantInSettings(ctx, unit, input) + if err != nil || again.Created { + return errors.Join(err, errors.New("repeat in a transaction created a record")) + } + _, err = unit.ConsentLedger().Current(ctx, user.ID, domain.ConsentPurposePublication) + return err + }) + if err != nil { + t.Fatalf("repeat in a transaction error = %v", err) + } + + // C1 has a newer text: the first one is outdated. An unknown version + // and a scheduled one are not current either. + outdated := fixture.grantInput(t, user.ID, domain.ConsentPurposePersonalData) + outdated.TextVersion = "c1-2026-10-01" + scheduled := fixture.grantInput(t, user.ID, domain.ConsentPurposeFSPImport) + scheduled.TextVersion = consentScheduledC5Version + unknown := fixture.grantInput(t, user.ID, domain.ConsentPurposeAutoCategorization) + unknown.TextVersion = "c3-1999-01-01" + for name, stale := range map[string]struct { + input consent.SettingsGrantInput + current domain.ConsentTextVersion + }{ + "outdated": {outdated, consentSecondC1Version}, + "scheduled": {scheduled, "c5-2026-10-01"}, + "unknown": {unknown, "c3-2026-10-01"}, + } { + _, err := fixture.service.GrantInSettingsInNewTransaction(ctx, stale.input) + var staleError *consent.StaleConsentTextError + if !errors.Is(err, consent.ErrStaleConsentText) || !errors.As(err, &staleError) || staleError.Current != stale.current { + t.Fatalf("GrantInSettingsInNewTransaction(%s) error = %v, want a stale error naming %s", name, err, stale.current) + } + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + + // The current version of the same purpose goes through; the outdated + // text of C1 stays refused after it. + fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePersonalData)) + if _, err := fixture.service.GrantInSettingsInNewTransaction(ctx, outdated); !errors.Is(err, consent.ErrStaleConsentText) { + t.Fatalf("GrantInSettingsInNewTransaction(outdated after a current grant) error = %v, want ErrStaleConsentText", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 2) + + // A grant after a revocation is a new record, not a repeat. + fixture.advance(time.Minute) + fixture.revoke(t, fixture.store.ConsentLedger(), user.ID, domain.ConsentPurposePublication) + fixture.advance(time.Minute) + regranted := fixture.grant(t, input) + if regranted.ID() == first.ID() { + t.Fatal("a grant after a revocation reused the revoked record") + } + assertRowCount(ctx, t, pool, consentRecordsTable, 3) + }) + + t.Run("concurrent repeats create one record", func(t *testing.T) { + reset(t) + user := fixture.identity.createUser(t, "concurrent@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour)) + input := fixture.grantInput(t, user.ID, domain.ConsentPurposePublication) + + var created atomic.Int32 + functions := make([]func() error, concurrentConsentRepeats) + for index := range functions { + functions[index] = func() error { + result, err := fixture.service.GrantInSettingsInNewTransaction(ctx, input) + if err == nil && result.Created { + created.Add(1) + } + return err + } + } + for index, err := range runAtOnce(functions...) { + if err != nil { + t.Fatalf("concurrent grant %d error = %v", index, err) + } + } + if created.Load() != 1 { + t.Fatalf("%d concurrent grants created a record, want 1", created.Load()) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + }) + + t.Run("a repeat of an outdated version after a new publication is stale", func(t *testing.T) { + reset(t) + user := fixture.identity.createUser(t, "republished@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour)) + input := fixture.grantInput(t, user.ID, domain.ConsentPurposeAutoCategorization) + first := fixture.grant(t, input) + + // Version two of C3 is published the way a migration would, after + // version one was granted and before the repeat. + const secondC3Version = "c3-2026-10-05" + if _, err := pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + VALUES ('c3', $1, $2, sha256(convert_to($2, 'UTF8')), 'demo', $3)`, + secondC3Version, "I consent to the automatic categorization, version two.", start.Add(-time.Hour)); err != nil { + t.Fatalf("publish the second C3 text: %v", err) + } + + _, err := fixture.service.GrantInSettingsInNewTransaction(ctx, input) + var stale *consent.StaleConsentTextError + if !errors.Is(err, consent.ErrStaleConsentText) || !errors.As(err, &stale) || stale.Current != secondC3Version { + t.Fatalf("repeat of version one error = %v, want a stale error naming %s", err, secondC3Version) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + if current, err := fixture.store.ConsentLedger().Current(ctx, user.ID, domain.ConsentPurposeAutoCategorization); err != nil || current.ID() != first.ID() { + t.Fatalf("Current(c3) = %s, %v, want the first record", current, err) + } + }) + + t.Run("a re-registration records its C1 after UpdateRegistration", func(t *testing.T) { + reset(t) + reregister := func(t *testing.T, rawEmail string, grantFirst bool) (granted consent.GrantResult, earlier domain.ConsentRecord) { + t.Helper() + first := fixture.identity.createUser(t, rawEmail, domain.ScenarioCandidate, start.Add(-72*time.Hour)) + earlier = fixture.registerC1(t, first) + changed, err := first.ReRegister(fixture.identity.registration(t, rawEmail, domain.ScenarioEmployer, start)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + version := fixture.currentVersion(t, domain.ConsentPurposePersonalData) + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + grant := func(registrationVersion int64) error { + var err error + granted, err = fixture.service.GrantAtRegistration(ctx, unit, first.ID, registrationVersion, version) + return err + } + if grantFirst { + if err := grant(first.RegistrationVersion); err != nil { + return err + } + } + registered, err := unit.Users().UpdateRegistration(ctx, changed) + if err != nil { + return err + } + if grantFirst { + return nil + } + return grant(registered.RegistrationVersion) + }) + if err != nil { + t.Fatalf("re-registration transaction error = %v", err) + } + return granted, earlier + } + + // Correct order: UpdateRegistration deletes the earlier registrant's + // C1, then the grant creates the new one. + granted, earlier := reregister(t, "after@example.com", false) + if !granted.Created || granted.Record.ID() == earlier.ID() { + t.Fatalf("GrantAtRegistration after UpdateRegistration = %s, created %v, want a new record", granted.Record, granted.Created) + } + assertConsentIDs(t, fixture.list(t, granted.Record.SubjectID()).Records, granted.Record.ID()) + + // The hazard: a grant before UpdateRegistration finds the earlier + // C1 and reports Created false, and the update then deletes it, so + // the account is left without any C1. + before, earlierBefore := reregister(t, "before@example.com", true) + if before.Created || before.Record.ID() != earlierBefore.ID() { + t.Fatalf("GrantAtRegistration before UpdateRegistration = %s, created %v, want the earlier record", before.Record, before.Created) + } + if page := fixture.list(t, before.Record.SubjectID()); len(page.Records) != 0 { + t.Fatalf("a grant before UpdateRegistration left %d records, want none: the earlier C1 is deleted", len(page.Records)) + } + }) + + t.Run("C4 is granted only through its scoped operation", func(t *testing.T) { + reset(t) + user := fixture.identity.createUser(t, "contact@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour)) + generic := fixture.grantInput(t, user.ID, domain.ConsentPurposeContactDisclosure) + _, err := fixture.service.GrantInSettingsInNewTransaction(ctx, generic) + if !errors.Is(err, consent.ErrScopedConsentRequired) { + t.Fatalf("GrantInSettingsInNewTransaction(C4) error = %v, want ErrScopedConsentRequired", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 0) + + fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + organization, invitation := uuid.New(), uuid.New() + contact := consent.ContactGrantInput{ + SubjectID: user.ID, OrganizationID: organization, OrganizationName: consentOrganizationName, Fields: fields, + InvitationID: invitation, InvitationTermsVersion: 2, TextVersion: generic.TextVersion, + } + var granted consent.GrantResult + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + granted, err = fixture.service.GrantContact(ctx, unit, contact) + return err + }) + if err != nil || !granted.Created { + t.Fatalf("GrantContact() = %v, %v, want a new record", granted.Created, err) + } + record := granted.Record + if record.Purpose() != domain.ConsentPurposeContactDisclosure || record.Source() != domain.ConsentSourceInvitationAcceptance || + record.OrganizationID() != organization || record.OrganizationName() != consentOrganizationName || + !record.Fields().Equal(fields) || record.InvitationID() != invitation || !record.GrantedAt().Equal(start) { + t.Fatalf("GrantContact() record = %s, want the scope of its input at the application time", record) + } + + // A repeat returns the record; an outdated C4 text is refused. + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + repeat, err := fixture.service.GrantContact(ctx, unit, contact) + if err == nil && (repeat.Created || repeat.Record.ID() != record.ID()) { + err = errors.New("repeat did not return the existing record") + } + return err + }) + if err != nil { + t.Fatalf("GrantContact(repeat) error = %v", err) + } + outdated := contact + outdated.InvitationID, outdated.TextVersion = uuid.New(), "c4-1999-01-01" + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := fixture.service.GrantContact(ctx, unit, outdated) + return err + }) + if !errors.Is(err, consent.ErrStaleConsentText) { + t.Fatalf("GrantContact(outdated) error = %v, want ErrStaleConsentText", err) + } + assertRowCount(ctx, t, pool, consentRecordsTable, 1) + // C4 gives no other purpose. + if _, err := fixture.store.ConsentLedger().Current(ctx, user.ID, domain.ConsentPurposePublication); !errors.Is(err, outbound.ErrConsentNotFound) { + t.Fatalf("Current(c2) after C4 error = %v, want ErrConsentNotFound", err) + } + }) + + // This subtest must stay last: it closes the shared pool to simulate a + // restart, so no later subtest could use the fixture. + t.Run("a new repository instance reads the history with its revocations", func(t *testing.T) { + reset(t) + user := fixture.identity.createUser(t, "restart@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour)) + grantedAt := map[uuid.UUID]time.Time{} + c1 := fixture.registerC1(t, user) + grantedAt[c1.ID()] = fixture.now() + fixture.advance(time.Minute) + c2 := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication)) + grantedAt[c2.ID()] = fixture.now() + fixture.advance(time.Minute) + c5 := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposeFSPImport)) + grantedAt[c5.ID()] = fixture.now() + fixture.advance(time.Minute) + revokedAt := fixture.now() + if revoked := fixture.revoke(t, fixture.store.ConsentLedger(), user.ID, domain.ConsentPurposePublication); len(revoked) != 1 { + t.Fatalf("Revoke(c2) = %v, want one record", revoked) + } + fixture.advance(time.Minute) + c2Again := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication)) + grantedAt[c2Again.ID()] = fixture.now() + + // Restart: close the pool and build every repository and the usecase + // again from a new one. + pool.Close() + restartedPool := env.newPool(ctx, t) + restartedStore := postgresadapter.NewConsentStore(restartedPool) + restartedService := consent.NewService(postgresadapter.NewTransactor(restartedPool), fixture.now) + + page, err := restartedStore.ConsentLedger().List(ctx, outbound.ConsentListQuery{SubjectID: user.ID, Limit: consentPageSize}) + if err != nil { + t.Fatalf("List() after restart error = %v", err) + } + assertConsentIDs(t, page.Records, c2Again.ID(), c5.ID(), c2.ID(), c1.ID()) + assertConsentStates(t, page, domain.ConsentStateActive, domain.ConsentStateActive, domain.ConsentStateRevoked, domain.ConsentStateActive) + revokedRecord := page.Records[2] + if stamped, ok := revokedRecord.RevokedAt(); !ok || !stamped.Equal(revokedAt) || + revokedRecord.RevocationSource() != domain.ConsentRevocationSourceConsentSettings { + t.Fatalf("revoked record = %v %v %q, want the stamp %v", stamped, ok, revokedRecord.RevocationSource(), revokedAt) + } + for _, record := range page.Records { + if want := grantedAt[record.ID()]; !record.GrantedAt().Equal(want) { + t.Fatalf("record %s granted at %v, want the application time %v", record, record.GrantedAt(), want) + } + } + + // The restarted instance sees the same state: a repeat stores nothing. + current, err := restartedStore.ConsentTexts().Current(ctx, domain.ConsentPurposePublication, fixture.now()) + if err != nil { + t.Fatalf("ConsentTexts().Current(c2) after restart error = %v", err) + } + repeat, err := restartedService.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{ + SubjectID: user.ID, Purpose: domain.ConsentPurposePublication, TextVersion: current.Version(), + }) + if err != nil || repeat.Created || repeat.Record.ID() != c2Again.ID() { + t.Fatalf("GrantInSettingsInNewTransaction(repeat after restart) = %s, %v, %v, want the existing record", repeat.Record, repeat.Created, err) + } + assertRowCount(ctx, t, restartedPool, consentRecordsTable, 4) + }) +} diff --git a/backend/integration_test/contact_read_http_test.go b/backend/integration_test/contact_read_http_test.go new file mode 100644 index 0000000..6805649 --- /dev/null +++ b/backend/integration_test/contact_read_http_test.go @@ -0,0 +1,518 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/policy" +) + +const contactReadTimeout = 10 * time.Minute + +// contactDisclosureHTTP is the contact disclosure as the owner reads it. A +// null value is a nil pointer, so a value that leaks shows up as non-nil. +type contactDisclosureHTTP struct { + InvitationID uuid.UUID `json:"invitation_id"` + GrantID uuid.UUID `json:"grant_id"` + Fields []string `json:"fields"` + GrantedAt time.Time `json:"granted_at"` + FullName *string `json:"full_name"` + Email *string `json:"email"` + Phone *string `json:"phone"` + Telegram *string `json:"telegram"` +} + +// TestOrganizationContactReadsAndRevocationOverHTTP covers the contact read +// through an accepted invitation and the independent closing of its grant: the +// consent C4, the consent C2 and the publication, and the hiding of the +// organization. Each subtest uses its own candidates, so the cases do not share +// the state of a grant. +func TestOrganizationContactReadsAndRevocationOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), contactReadTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA := account("contact-owner-a@example.test", domain.ScenarioEmployer) + ownerB := account("contact-owner-b@example.test", domain.ScenarioEmployer) + ownerD := account("contact-owner-d@example.test", domain.ScenarioEmployer) + recruiterA := account("contact-recruiter-a@example.test", domain.ScenarioEmployer) + sessionOwnerA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) + sessionOwnerB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + sessionOwnerD := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerD.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerA, "contact-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerB, "contact-company-b") + orgD := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwnerD, "contact-company-d") + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiterA.ID, "recruiter", "active", now) + sessionRecruiterA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiterA.Email.Address()) + + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, now: now} + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("contact-read-key-%d", keySequence) + } + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + // Each candidate signs in once: the login limit of one client is shared by + // the whole subtest, and every request of a candidate reuses its session. + sessions := map[uuid.UUID]organizationHTTPSession{} + login := func(candidate domain.User) organizationHTTPSession { + t.Helper() + if session, ok := sessions[candidate.ID]; ok { + return session + } + session := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + sessions[candidate.ID] = session + return session + } + // newCandidate creates a candidate who holds an email and a phone number, + // grants C2, and publishes the card, through the routes the candidate uses. + newCandidate := func(email string) domain.User { + t.Helper() + candidate := account(email, domain.ScenarioCandidate) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision("Contact Candidate"), Email: confirmedDecision(email), Phone: confirmedDecision("+70000000000"), + }, 0) + session := login(candidate) + if response := request(http.MethodPut, "/api/v1/me/consents/c2", + fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), session, ""); response.Code != http.StatusOK { + t.Fatalf("C2 grant = %d %s, want 200", response.Code, response.Body.String()) + } + if response := request(http.MethodPut, "/api/v1/me/privacy/publication", + `{"expected_version":0,"state":"published","fields":["stack"]}`, session, ""); response.Code != http.StatusOK { + t.Fatalf("publication = %d %s, want 200", response.Code, response.Body.String()) + } + return candidate + } + // deliver creates a draft for the candidate and sends it from the organization. + deliver := func(organizationID uuid.UUID, owner organizationHTTPSession, candidate domain.User) invitationHTTPBody { + t.Helper() + handle, err := harness.key.ForOrganization(organizationID, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID), + invitationCreateJSON(t, handle, nil), owner, nextKey()), http.StatusCreated) + return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", organizationID, draft.ID), + fmt.Sprintf(`{"expected_version":%d}`, draft.Version), owner, nextKey()), http.StatusOK) + } + acceptResponse := func(candidate domain.User, invitation invitationHTTPBody, key string, fields ...string) *httptest.ResponseRecorder { + t.Helper() + encoded, err := json.Marshal(map[string]any{ + "expected_version": invitation.Version, "terms_version": invitation.TermsVersion, + "consent_c4": map[string]any{"text_version": acceptTextVersion, "accepted": true, "fields": fields}, + }) + if err != nil { + t.Fatalf("marshal acceptance: %v", err) + } + return request(http.MethodPost, "/api/v1/me/invitations/"+invitation.ID.String()+"/accept", string(encoded), login(candidate), key) + } + acceptFields := func(candidate domain.User, invitation invitationHTTPBody, fields ...string) candidateInvitationHTTPBody { + t.Helper() + return decodeCandidateInvitationHTTP(t, acceptResponse(candidate, invitation, nextKey(), fields...), http.StatusOK) + } + readContacts := func(organizationID, invitationID uuid.UUID, session organizationHTTPSession) *httptest.ResponseRecorder { + t.Helper() + return request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/contacts", organizationID, invitationID), "", session, "") + } + requireDisclosure := func(response *httptest.ResponseRecorder, invitationID, grantID uuid.UUID) contactDisclosureHTTP { + t.Helper() + if response.Code != http.StatusOK { + t.Fatalf("contact read = %d %s, want 200", response.Code, response.Body.String()) + } + if cache := response.Header().Get("Cache-Control"); cache != "no-store" { + t.Fatalf("contact read Cache-Control = %q, want no-store", cache) + } + var disclosure contactDisclosureHTTP + if err := json.Unmarshal(response.Body.Bytes(), &disclosure); err != nil { + t.Fatalf("decode contact read %s: %v", response.Body.String(), err) + } + if disclosure.InvitationID != invitationID || disclosure.GrantID != grantID { + t.Fatalf("contact read names invitation %s and grant %s, want %s and %s", disclosure.InvitationID, disclosure.GrantID, invitationID, grantID) + } + return disclosure + } + requireNotFound := func(label string, response *httptest.ResponseRecorder) { + t.Helper() + if response.Code != http.StatusNotFound { + t.Fatalf("%s = %d %s, want 404", label, response.Code, response.Body.String()) + } + requireSessionProblem(t, response, http.StatusNotFound, "not_found") + } + grantRow := func(invitationID uuid.UUID) (revoked bool, reason string) { + t.Helper() + var reasonValue *string + if err := harness.pool.QueryRow(ctx, `SELECT revoked_at IS NOT NULL, revocation_reason FROM contact_grants WHERE source_invitation_id = $1`, + invitationID).Scan(&revoked, &reasonValue); err != nil { + t.Fatalf("read grant of %s: %v", invitationID, err) + } + if reasonValue != nil { + reason = *reasonValue + } + return revoked, reason + } + requireGrantStatus := func(candidate domain.User, invitationID uuid.UUID, status string, readable bool, reason string) { + t.Helper() + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, "/api/v1/me/invitations/"+invitationID.String(), "", login(candidate), ""), http.StatusOK) + grant := decodeContactGrantHTTP(t, read) + if grant.Status != status || grant.Readable != readable { + t.Fatalf("grant as the candidate reads it = %+v, want status %q readable %v", grant, status, readable) + } + if reason == "" { + if grant.RevocationReason != nil { + t.Fatalf("grant reason = %q, want none", *grant.RevocationReason) + } + return + } + if grant.RevocationReason == nil || *grant.RevocationReason != reason { + t.Fatalf("grant reason = %v, want %q", grant.RevocationReason, reason) + } + } + // requireNoContactValues fails when a response carries a value of the + // candidates that the test creates. Only the kinds may appear. + requireNoContactValues := func(label, text string) { + t.Helper() + for _, marker := range []string{"@example.test", "+70000000000", "Contact Candidate"} { + if strings.Contains(text, marker) { + t.Fatalf("%s carries the contact value %q: %s", label, marker, text) + } + } + } + // requireOrganizationAccess reads one invitation as its owner and checks the + // contact access of the response: its status and the kinds it lists. + requireOrganizationAccess := func(label string, organizationID, invitationID uuid.UUID, session organizationHTTPSession, status string, fields ...string) invitationHTTPBody { + t.Helper() + response := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID), "", session, "") + invitation := decodeInvitationHTTP(t, response, http.StatusOK) + if invitation.ContactAccess.Status != status || !slices.Equal(invitation.ContactAccess.Fields, fields) { + t.Fatalf("%s contact access = %+v, want %q with fields %v", label, invitation.ContactAccess, status, fields) + } + requireNoContactValues(label, response.Body.String()) + return invitation + } + // requireListedAccess checks the contact access of one invitation in the + // owner's list, which shows the same states as the single read. + requireListedAccess := func(organizationID, invitationID uuid.UUID, session organizationHTTPSession, status string, fields ...string) { + t.Helper() + response := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations?limit=100", organizationID), "", session, "") + if response.Code != http.StatusOK { + t.Fatalf("organization list = %d %s, want 200", response.Code, response.Body.String()) + } + requireNoContactValues("organization list", response.Body.String()) + var page struct { + Items []struct { + ID uuid.UUID `json:"id"` + ContactAccess struct { + Status string `json:"status"` + Fields []string `json:"fields"` + } `json:"contact_access"` + } `json:"items"` + } + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode organization list: %v", err) + } + for _, item := range page.Items { + if item.ID != invitationID { + continue + } + if item.ContactAccess.Status != status || !slices.Equal(item.ContactAccess.Fields, fields) { + t.Fatalf("listed contact access = %+v, want %q with fields %v", item.ContactAccess, status, fields) + } + return + } + t.Fatalf("organization list does not show invitation %s", invitationID) + } + candidates := []domain.User{} + for index := range 6 { + candidates = append(candidates, newCandidate(fmt.Sprintf("contact-candidate-%d@example.test", index))) + } + + t.Run("an email-only grant reads the email to the owner and nothing else", func(t *testing.T) { + candidate := candidates[0] + invitation := deliver(orgA, sessionOwnerA, candidate) + requireOrganizationAccess("organization view before the acceptance", orgA, invitation.ID, sessionOwnerA, "not_granted") + accepted := acceptFields(candidate, invitation, "email") + grantID := decodeContactGrantHTTP(t, accepted).ID + requireOrganizationAccess("organization view after the acceptance", orgA, invitation.ID, sessionOwnerA, "available", "email") + requireListedAccess(orgA, invitation.ID, sessionOwnerA, "available", "email") + + first := readContacts(orgA, invitation.ID, sessionOwnerA) + disclosure := requireDisclosure(first, invitation.ID, grantID) + if len(disclosure.Fields) != 1 || disclosure.Fields[0] != "email" || disclosure.Email == nil || *disclosure.Email != candidate.Email.Address() { + t.Fatalf("disclosure = %+v, want the confirmed email only", disclosure) + } + if disclosure.Phone != nil || disclosure.FullName != nil || disclosure.Telegram != nil { + t.Fatalf("disclosure = %+v, want null for every kind the grant does not cover", disclosure) + } + if again := readContacts(orgA, invitation.ID, sessionOwnerA); again.Code != http.StatusOK || again.Body.String() != first.Body.String() { + t.Fatalf("repeated contact read = %d %s, want the same body", again.Code, again.Body.String()) + } + + // Organization B and a non-owner member of A are refused, and so is a + // candidate or an anonymous request. + requireNotFound("owner of another organization on the path of A", readContacts(orgA, invitation.ID, sessionOwnerB)) + requireNotFound("owner of B on its own path with the invitation of A", readContacts(orgB, invitation.ID, sessionOwnerB)) + requireSessionProblem(t, readContacts(orgA, invitation.ID, sessionRecruiterA), http.StatusForbidden, "forbidden") + requireSessionProblem(t, readContacts(orgA, invitation.ID, login(candidate)), http.StatusForbidden, "forbidden") + requireSessionProblem(t, readContacts(orgA, invitation.ID, organizationHTTPSession{}), http.StatusUnauthorized, "unauthenticated") + + // Each successful read is audited with its kinds only, and the read does + // not consume the card-view quota. + var audited, emailOnly int + var actor string + if err := harness.pool.QueryRow(ctx, ` + SELECT count(*), + count(*) FILTER (WHERE field_codes = ARRAY['email']::text []), + COALESCE(max(actor_id::text), '') + FROM candidate_card_access_events + WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'contact_read'`, candidate.ID, orgA). + Scan(&audited, &emailOnly, &actor); err != nil { + t.Fatalf("read the access audit: %v", err) + } + if audited != 2 || emailOnly != 2 || actor != ownerA.ID.String() { + t.Fatalf("access audit = %d rows, %d of them the email only, by %q; want the two successful reads by the owner", audited, emailOnly, actor) + } + var viewQuota int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, orgA).Scan(&viewQuota); err != nil { + t.Fatalf("count card view quota: %v", err) + } + if viewQuota != 0 { + t.Fatalf("contact reads consumed %d card-view quota rows, want none", viewQuota) + } + requireGrantStatus(candidate, invitation.ID, "active", true, "") + if logs := harness.logs.String(); strings.Contains(logs, candidate.Email.Address()) || strings.Contains(logs, candidate.ID.String()) { + t.Fatal("the server log contains the candidate's email or identifier") + } + }) + + t.Run("revoking C4 closes the grant for the URL, the API, and a repeated request, and leaves other organizations", func(t *testing.T) { + candidate := candidates[1] + inA := deliver(orgA, sessionOwnerA, candidate) + grantA := decodeContactGrantHTTP(t, acceptFields(candidate, inA, "email")).ID + inB := deliver(orgB, sessionOwnerB, candidate) + grantB := decodeContactGrantHTTP(t, acceptFields(candidate, inB, "email")).ID + requireDisclosure(readContacts(orgA, inA.ID, sessionOwnerA), inA.ID, grantA) + requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) + + revoke := request(http.MethodDelete, "/api/v1/me/consents/c4/organizations/"+orgA.String(), "", login(candidate), "") + if revoke.Code != http.StatusNoContent { + t.Fatalf("C4 revoke for A = %d %s, want 204", revoke.Code, revoke.Body.String()) + } + requireNotFound("contact read after the revocation", readContacts(orgA, inA.ID, sessionOwnerA)) + requireNotFound("repeated contact read after the revocation", readContacts(orgA, inA.ID, sessionOwnerA)) + requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) + if revoked, reason := grantRow(inA.ID); !revoked || reason != "consent_revoked" { + t.Fatalf("grant of A after the C4 revocation: revoked %v reason %q, want consent_revoked", revoked, reason) + } + if revoked, _ := grantRow(inB.ID); revoked { + t.Fatal("the C4 revocation for A closed the grant of B") + } + requireGrantStatus(candidate, inA.ID, "revoked", false, "consent_revoked") + requireGrantStatus(candidate, inB.ID, "active", true, "") + requireOrganizationAccess("organization view of A after the C4 revocation", orgA, inA.ID, sessionOwnerA, "closed") + requireOrganizationAccess("organization view of B after the C4 revocation", orgB, inB.ID, sessionOwnerB, "available", "email") + + // The publication stays as it was: the C4 revocation closes only the grant, + // and only a new explicit C4 creates a new grant for A. + requireNotFound("contact read of the revoked grant", readContacts(orgA, inA.ID, sessionOwnerA)) + inAgain := deliver(orgA, sessionOwnerA, candidate) + grantAgain := decodeContactGrantHTTP(t, acceptFields(candidate, inAgain, "email")).ID + if grantAgain == grantA { + t.Fatal("a new C4 reused the revoked grant") + } + requireDisclosure(readContacts(orgA, inAgain.ID, sessionOwnerA), inAgain.ID, grantAgain) + requireNotFound("the revoked grant after a new C4", readContacts(orgA, inA.ID, sessionOwnerA)) + requireOrganizationAccess("organization view of the revoked invitation after a new C4", orgA, inA.ID, sessionOwnerA, "closed") + requireOrganizationAccess("organization view of the new grant", orgA, inAgain.ID, sessionOwnerA, "available", "email") + }) + + t.Run("hiding the organization closes its grants, and unhiding never reopens them", func(t *testing.T) { + candidate := candidates[2] + inA := deliver(orgA, sessionOwnerA, candidate) + grantA := decodeContactGrantHTTP(t, acceptFields(candidate, inA, "email")).ID + inB := deliver(orgB, sessionOwnerB, candidate) + grantB := decodeContactGrantHTTP(t, acceptFields(candidate, inB, "phone")).ID + // The candidate may hide only an organization that already appears in + // the candidate's access history, so the owner reads the grant first. + requireDisclosure(readContacts(orgA, inA.ID, sessionOwnerA), inA.ID, grantA) + + hide := request(http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") + if hide.Code != http.StatusOK { + t.Fatalf("hide A = %d %s, want 200", hide.Code, hide.Body.String()) + } + requireNotFound("contact read while A is hidden", readContacts(orgA, inA.ID, sessionOwnerA)) + requireDisclosure(readContacts(orgB, inB.ID, sessionOwnerB), inB.ID, grantB) + unhide := request(http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") + if unhide.Code != http.StatusNoContent { + t.Fatalf("unhide A = %d %s, want 204", unhide.Code, unhide.Body.String()) + } + requireNotFound("contact read after unhiding A", readContacts(orgA, inA.ID, sessionOwnerA)) + requireOrganizationAccess("organization view of A after hiding and unhiding", orgA, inA.ID, sessionOwnerA, "closed") + if revoked, reason := grantRow(inA.ID); !revoked || reason != "visibility_closed" { + t.Fatalf("grant of A after hiding: revoked %v reason %q, want visibility_closed", revoked, reason) + } + requireGrantStatus(candidate, inA.ID, "revoked", false, "visibility_closed") + requireOrganizationAccess("organization view of A while hidden", orgA, inA.ID, sessionOwnerA, "closed") + if revoked, _ := grantRow(inB.ID); revoked { + t.Fatal("hiding A closed the grant of B") + } + + // A grant created while the organization is hidden stays stored and blocked, + // and it becomes readable when the candidate unhides the organization. + inAHidden := deliver(orgA, sessionOwnerA, candidate) + hideAgain := request(http.MethodPut, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), "") + if hideAgain.Code != http.StatusOK { + t.Fatalf("hide A again = %d %s, want 200", hideAgain.Code, hideAgain.Body.String()) + } + blocked := decodeCandidateInvitationHTTP(t, acceptResponse(candidate, inAHidden, nextKey(), "email"), http.StatusOK) + grantHidden := decodeContactGrantHTTP(t, blocked) + if grantHidden.Readable || grantHidden.BlockedBy == nil || *grantHidden.BlockedBy != "visibility" { + t.Fatalf("grant accepted while hidden = %+v, want blocked by visibility", grantHidden) + } + requireNotFound("contact read of the blocked grant", readContacts(orgA, inAHidden.ID, sessionOwnerA)) + requireOrganizationAccess("organization view of the blocked grant", orgA, inAHidden.ID, sessionOwnerA, "closed") + if response := request(http.MethodDelete, "/api/v1/me/privacy/hidden-organizations/"+orgA.String(), "", login(candidate), ""); response.Code != http.StatusNoContent { + t.Fatalf("unhide A after the blocked acceptance = %d %s, want 204", response.Code, response.Body.String()) + } + requireDisclosure(readContacts(orgA, inAHidden.ID, sessionOwnerA), inAHidden.ID, grantHidden.ID) + requireOrganizationAccess("organization view of the blocked grant after unhiding", orgA, inAHidden.ID, sessionOwnerA, "available", "email") + }) + + t.Run("withdrawing C2 closes the grants, and publishing again does not reopen them", func(t *testing.T) { + candidate := candidates[3] + invitation := deliver(orgD, sessionOwnerD, candidate) + grant := decodeContactGrantHTTP(t, acceptFields(candidate, invitation, "email")).ID + requireDisclosure(readContacts(orgD, invitation.ID, sessionOwnerD), invitation.ID, grant) + + revokeC2 := request(http.MethodDelete, "/api/v1/me/consents/c2", "", login(candidate), "") + if revokeC2.Code != http.StatusNoContent { + t.Fatalf("C2 revoke = %d %s, want 204", revokeC2.Code, revokeC2.Body.String()) + } + requireNotFound("contact read after C2 revoke", readContacts(orgD, invitation.ID, sessionOwnerD)) + requireOrganizationAccess("organization view after the C2 withdrawal", orgD, invitation.ID, sessionOwnerD, "closed") + if revoked, reason := grantRow(invitation.ID); !revoked || reason != "visibility_closed" { + t.Fatalf("grant after C2 revoke: revoked %v reason %q, want visibility_closed", revoked, reason) + } + if response := request(http.MethodPut, "/api/v1/me/consents/c2", + fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), login(candidate), ""); response.Code != http.StatusOK { + t.Fatalf("C2 regrant = %d %s, want 200", response.Code, response.Body.String()) + } + var version int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&version); err != nil { + t.Fatalf("read publication version: %v", err) + } + if response := request(http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":["stack"]}`, version), login(candidate), ""); response.Code != http.StatusOK { + t.Fatalf("republication = %d %s, want 200", response.Code, response.Body.String()) + } + requireNotFound("contact read after republishing", readContacts(orgD, invitation.ID, sessionOwnerD)) + requireGrantStatus(candidate, invitation.ID, "revoked", false, "visibility_closed") + requireOrganizationAccess("organization view after republishing", orgD, invitation.ID, sessionOwnerD, "closed") + }) + + t.Run("closing the publication closes the grants", func(t *testing.T) { + candidate := candidates[4] + invitation := deliver(orgD, sessionOwnerD, candidate) + grant := decodeContactGrantHTTP(t, acceptFields(candidate, invitation, "email")).ID + requireDisclosure(readContacts(orgD, invitation.ID, sessionOwnerD), invitation.ID, grant) + + var version int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM candidate_publications WHERE user_id = $1`, candidate.ID).Scan(&version); err != nil { + t.Fatalf("read publication version: %v", err) + } + closing := request(http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":%d,"state":"closed","fields":[]}`, version), login(candidate), "") + if closing.Code != http.StatusOK { + t.Fatalf("closing the publication = %d %s, want 200", closing.Code, closing.Body.String()) + } + requireNotFound("contact read after closing the publication", readContacts(orgD, invitation.ID, sessionOwnerD)) + requireOrganizationAccess("organization view after closing the publication", orgD, invitation.ID, sessionOwnerD, "closed") + if revoked, reason := grantRow(invitation.ID); !revoked || reason != "visibility_closed" { + t.Fatalf("grant after closing: revoked %v reason %q, want visibility_closed", revoked, reason) + } + }) + + t.Run("the grant index for candidate-wide closing exists", func(t *testing.T) { + var indexes int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM pg_indexes WHERE indexname = 'contact_grants_candidate_active_idx'`).Scan(&indexes); err != nil { + t.Fatalf("read the index catalog: %v", err) + } + if indexes != 1 { + t.Fatalf("contact_grants_candidate_active_idx count = %d, want 1", indexes) + } + }) + + t.Run("a declined invitation shows not_granted", func(t *testing.T) { + candidate := candidates[5] + invitation := deliver(orgA, sessionOwnerA, candidate) + answer := request(http.MethodPost, "/api/v1/me/invitations/"+invitation.ID.String()+"/decline", + fmt.Sprintf(`{"expected_version":%d,"reason":"other"}`, invitation.Version), login(candidate), nextKey()) + if answer.Code != http.StatusOK { + t.Fatalf("decline = %d %s, want 200", answer.Code, answer.Body.String()) + } + declined := requireOrganizationAccess("organization view of a declined invitation", orgA, invitation.ID, sessionOwnerA, "not_granted") + if declined.State != "declined" { + t.Fatalf("declined invitation state = %q, want declined", declined.State) + } + }) + + // This subtest moves the clock to the response deadline, which ends the + // sessions that were created earlier, so it signs in again after the move. + // It must stay the last subtest. + t.Run("an expired invitation shows not_granted", func(t *testing.T) { + candidate := newCandidate("contact-candidate-expired@example.test") + invitation := deliver(orgA, sessionOwnerA, candidate) + var deadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, invitation.ID).Scan(&deadline); err != nil { + t.Fatalf("read the response deadline: %v", err) + } + harness.clock.Set(deadline) + ownerSession := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + // A read at the deadline expires the invitation before it answers. + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, "/api/v1/me/invitations/"+invitation.ID.String(), "", candidateSession, ""), http.StatusOK) + if read.State != "expired" { + t.Fatalf("candidate read at the deadline = %+v, want expired", read) + } + expired := requireOrganizationAccess("organization view of an expired invitation", orgA, invitation.ID, ownerSession, "not_granted") + if expired.State != "expired" { + t.Fatalf("expired invitation state = %q, want expired", expired.State) + } + }) +} diff --git a/backend/integration_test/delivery_sending_migration_test.go b/backend/integration_test/delivery_sending_migration_test.go new file mode 100644 index 0000000..bad9ddf --- /dev/null +++ b/backend/integration_test/delivery_sending_migration_test.go @@ -0,0 +1,96 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "testing" + "time" + + "github.com/google/uuid" +) + +// deliverySendingMigrationVersion adds the lease, cancellation, and token +// binding columns of the sending worker to deliveries. +const deliverySendingMigrationVersion = 12 + +// TestDeliverySendingMigration rolls back and applies migration 00012 over +// rows that use what it adds: the earlier schema must keep a cancelled +// delivery as a rejected one and drop reset tokens, and the migration must +// apply again. +func TestDeliverySendingMigration(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + + now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + userID, tokenID, deliveryID := uuid.New(), uuid.New(), uuid.New() + exec := func(statement string, args ...any) { + t.Helper() + if _, err := pool.Exec(ctx, statement, args...); err != nil { + t.Fatalf("exec %q: %v", statement, err) + } + } + exec(`INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, registration_version, + last_registered_at, version, created_at, updated_at) + VALUES ($1, 'migration@example.com', 'migration@example.com', $2, 'candidate', 'candidate_consents', 1, $3, 1, $3, $3)`, + userID, identityTestPasswordHash, now) + exec(`INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'password_reset', $3, 1, $4, $5)`, + tokenID, userID, make([]byte, sha256.Size), now, now.Add(time.Hour)) + exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, + content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, + created_at, updated_at, email_token_id, cancel_reason, body_redacted_at) + VALUES ($1, $2, 'migration@example.com', 'password_reset', 'password_reset.v1', 's', '', '', $3, 'resend', 'main', + 'delivery/migration', 'cancelled', 0, NULL, 1, $4, $4, $5, 'processing_failed', $4)`, + deliveryID, userID, make([]byte, sha256.Size), now, tokenID) + + for { + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() error = %v", err) + } + if result.Version == deliverySendingMigrationVersion { + break + } + } + var status string + if err := pool.QueryRow(ctx, "SELECT status FROM deliveries WHERE id = $1", deliveryID).Scan(&status); err != nil || status != "rejected" { + t.Fatalf("delivery after the rollback = %q, %v; want rejected", status, err) + } + var body string + if err := pool.QueryRow(ctx, "SELECT text_body FROM deliveries WHERE id = $1", deliveryID).Scan(&body); err != nil || body == "" { + t.Fatalf("redacted body after the rollback = %q, %v; want a placeholder that satisfies the earlier body check", body, err) + } + var resetTokens, newColumns int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM email_tokens WHERE purpose = 'password_reset'").Scan(&resetTokens); err != nil || resetTokens != 0 { + t.Fatalf("reset tokens after the rollback = %d, %v; want 0", resetTokens, err) + } + err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'deliveries' + AND column_name IN ('email_token_id', 'cancel_reason', 'claim_owner', 'claimed_until', 'first_send_started_at', 'failure_count', 'body_redacted_at')`).Scan(&newColumns) + if err != nil || newColumns != 0 { + t.Fatalf("columns of 00012 after the rollback = %d, %v; want 0", newColumns, err) + } + if _, err := pool.Exec(ctx, "UPDATE deliveries SET status = 'cancelled' WHERE id = $1", deliveryID); err == nil { + t.Fatal("the earlier schema accepts the cancelled status") + } + + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.columns WHERE table_name = 'deliveries' + AND column_name IN ('email_token_id', 'cancel_reason', 'claim_owner', 'claimed_until', 'first_send_started_at', 'failure_count', 'body_redacted_at')`).Scan(&newColumns); err != nil || newColumns != 7 { + t.Fatalf("columns of 00012 after applying it again = %d, %v; want 7", newColumns, err) + } + var due bool + if err := pool.QueryRow(ctx, "SELECT to_regclass('public.deliveries_due_idx') IS NOT NULL").Scan(&due); err != nil || !due { + t.Fatalf("deliveries_due_idx exists = %t, %v; want true", due, err) + } +} diff --git a/backend/integration_test/delivery_statistics_test.go b/backend/integration_test/delivery_statistics_test.go new file mode 100644 index 0000000..4f15ef9 --- /dev/null +++ b/backend/integration_test/delivery_statistics_test.go @@ -0,0 +1,129 @@ +//go:build integration + +package integration_test + +import ( + "context" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + deliveryStatisticsTestTimeout = 3 * time.Minute + deliveryStatisticsAddress = "metrics.fixture@example.com" +) + +// TestDeliveryStatistics checks the GetDeliveryStatistics aggregate behind the +// delivery metrics against the real deliveries table and its constraints. +func TestDeliveryStatistics(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), deliveryStatisticsTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + store := postgresadapter.NewDeliveryStatisticsStore(pool) + + empty, err := store.DeliveryStatistics(ctx) + if err != nil { + t.Fatalf("DeliveryStatistics() on an empty table error = %v", err) + } + if len(empty.Counts) != 0 || !empty.EarliestPendingAttemptAt.IsZero() { + t.Fatalf("DeliveryStatistics() on an empty table = %+v, want nothing", empty) + } + + start := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + recipient := createStatisticsRecipient(ctx, t, postgresadapter.NewIdentityStore(pool).Users(), start) + deliveries := postgresadapter.NewDeliveryStore(pool).Deliveries() + account := mustProviderAccount(t, "resend") + create := func(kind domain.MailKind, createdAt time.Time) uuid.UUID { + t.Helper() + content, err := domain.NewMailContent(kind, string(kind)+".v1", "Subject", "Body\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), + RecipientUserID: recipient.ID, + Recipient: recipient.Email, + Content: content, + ProviderAccount: account, + CreatedAt: createdAt, + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := deliveries.Create(ctx, delivery); err != nil || !created { + t.Fatalf("Create() = %t, %v; want the delivery stored", created, err) + } + return delivery.ID() + } + // New deliveries are pending and due at creation. + create(domain.MailKindVerification, start.Add(2*time.Minute)) + create(domain.MailKindVerification, start.Add(time.Minute)) + create(domain.MailKindNotification, start.Add(3*time.Minute)) + // The status updates below satisfy the table constraints for each + // status, the way the sending worker will leave them. + setStatus := func(id uuid.UUID, statement string) { + t.Helper() + if _, err := pool.Exec(ctx, "UPDATE deliveries SET "+statement+" WHERE id = $1", id); err != nil { + t.Fatalf("set the delivery status: %v", err) + } + } + // The earliest pending delivery stops being pending, so the earliest + // due time comes from the remaining pending ones only. + setStatus(create(domain.MailKindVerification, start), "status = 'unknown'") + setStatus(create(domain.MailKindPasswordReset, start), "status = 'waiting_quota', next_attempt_at = NULL") + setStatus(create(domain.MailKindNotification, start), "status = 'accepted', next_attempt_at = NULL, provider_message_id = 'msg-1'") + setStatus(create(domain.MailKindNotification, start), "status = 'rejected', next_attempt_at = NULL") + + statistics, err := store.DeliveryStatistics(ctx) + if err != nil { + t.Fatalf("DeliveryStatistics() error = %v", err) + } + got := slices.Clone(statistics.Counts) + slices.SortFunc(got, func(a, b outbound.DeliveryStatusCount) int { + return strings.Compare(string(a.Kind)+"/"+string(a.Status), string(b.Kind)+"/"+string(b.Status)) + }) + want := []outbound.DeliveryStatusCount{ + {Kind: domain.MailKindNotification, Status: domain.DeliveryStatusAccepted, Deliveries: 1}, + {Kind: domain.MailKindNotification, Status: domain.DeliveryStatusPending, Deliveries: 1}, + {Kind: domain.MailKindNotification, Status: domain.DeliveryStatusRejected, Deliveries: 1}, + {Kind: domain.MailKindPasswordReset, Status: domain.DeliveryStatusWaitingQuota, Deliveries: 1}, + {Kind: domain.MailKindVerification, Status: domain.DeliveryStatusPending, Deliveries: 2}, + {Kind: domain.MailKindVerification, Status: domain.DeliveryStatusUnknown, Deliveries: 1}, + } + if !slices.Equal(got, want) { + t.Fatalf("Counts = %+v, want %+v", got, want) + } + if !statistics.EarliestPendingAttemptAt.Equal(start.Add(time.Minute)) { + t.Fatalf("EarliestPendingAttemptAt = %s, want %s", statistics.EarliestPendingAttemptAt, start.Add(time.Minute)) + } +} + +func createStatisticsRecipient(ctx context.Context, t *testing.T, users outbound.UserRepository, now time.Time) domain.User { + t.Helper() + hash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: mustEmail(t, deliveryStatisticsAddress), + PasswordHash: hash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := users.Create(ctx, user); err != nil { + t.Fatalf("create the recipient account: %v", err) + } + return user +} diff --git a/backend/integration_test/delivery_test.go b/backend/integration_test/delivery_test.go new file mode 100644 index 0000000..afcfdeb --- /dev/null +++ b/backend/integration_test/delivery_test.go @@ -0,0 +1,606 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/worker/eventconsumer" +) + +const ( + deliveryTestTimeout = 5 * time.Minute + // The private markers are searched for in logs and events; they must + // appear only in the mail request and delivery rows. + deliveryRecipientAddress = "Delivery.Recipient@Example.com" + deliverySubject = "PRIVATE-SUBJECT about an invitation" + deliveryBody = "PRIVATE-BODY: a company invited you to an interview." + deliveryLinkPath = "/candidate/invitations" + deliveryProvider = "resend" + deliveryAccount = "integration" + deliveryOtherAccount = "integration-eu" + deliveryMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c" + // deliveryLaterVersion is a template version that exists only in this test: + // it is later than the committed notification.v2. + deliveryLaterVersion = "notification.v3" + // renamedDeliveryConsumer replays requests as a renamed consumer would: + // the dedup markers of the real name do not apply to it. + renamedDeliveryConsumer = "notification_delivery_replay" + // deliveryRetryAfter has sub-millisecond parts, so a lossy round trip + // would show. + deliveryRetryAfter = 2*time.Second + 1500*time.Microsecond + 7*time.Nanosecond +) + +var ( + deliveryTables = []pgx.Identifier{{"delivery_attempts"}, {"deliveries"}, {"mail_requests"}} + deliveryPrivacyMarkers = []string{deliveryRecipientAddress, strings.ToLower(deliveryRecipientAddress), "PRIVATE-SUBJECT", "PRIVATE-BODY"} +) + +// deliveryHarness wires the request usecase, the delivery handler, and the +// stores against one database. +type deliveryHarness struct { + env *testEnvironment + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + consumers *postgresadapter.EventConsumerStore + identity *postgresadapter.IdentityStore + requester *notification.MailRequester + handler *notification.DeliveryHandler + account domain.MailProviderAccount + logs *syncBuffer + // now is truncated to microseconds, the precision PostgreSQL stores. + now time.Time +} + +// syncBuffer collects the logs of a consumer goroutine and the test. +type syncBuffer struct { + mu sync.Mutex + buffer bytes.Buffer +} + +func (buffer *syncBuffer) Write(data []byte) (int, error) { + buffer.mu.Lock() + defer buffer.mu.Unlock() + return buffer.buffer.Write(data) +} + +func (buffer *syncBuffer) String() string { + buffer.mu.Lock() + defer buffer.mu.Unlock() + return buffer.buffer.String() +} + +// laterVersionRenderer stands for a later template version: it renders other +// copy under deliveryLaterVersion without touching the committed templates. +type laterVersionRenderer struct{} + +func (laterVersionRenderer) RenderNotification(mailtemplate.NotificationData) (domain.MailContent, error) { + return domain.NewMailContent(domain.MailKindNotification, deliveryLaterVersion, + "Новая версия письма", "Текст новой версии шаблона.\n", "

Текст новой версии шаблона.

\n") +} + +func TestMailDelivery(t *testing.T) { + env := bootstrap(t, postgresService, kafkaService) + ctx, cancel := context.WithTimeout(t.Context(), deliveryTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + account, err := domain.NewMailProviderAccount(deliveryProvider, deliveryAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + renderer := notification.NewTemplateRenderer(templates) + harness := &deliveryHarness{ + env: env, + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + consumers: postgresadapter.NewEventConsumerStore(pool, consumerHandlerTime), + identity: postgresadapter.NewIdentityStore(pool), + account: account, + logs: &syncBuffer{}, + now: time.Now().UTC().Truncate(time.Microsecond), + } + harness.requester = notification.NewMailRequester(renderer, harness.clock) + harness.handler = harness.newHandler(renderer) + // Subtests share tables and run sequentially; each starts from empty + // tables. + reset := func(t *testing.T) { + t.Helper() + tables := append([]pgx.Identifier{ + outboxEventsTable, + {"consumer_processed_events"}, + {"consumer_dead_letters"}, + }, deliveryTables...) + truncateTables(ctx, t, pool, slices.Concat(tables, usersDependentTables)...) + } + + t.Run("one event processed twice through the consumer creates one delivery", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, true) + deliveryID := harness.requestNotification(ctx, t, recipient) + event := harness.outboxEvent(ctx, t, deliveryID) + topic := env.createKafkaTopic(ctx, t, 1) + + // The relay publishes the event, then publishes it again as after a + // crash between the broker acknowledgement and the published_at + // commit; both records carry the same event_id. + relay := (&relayHarness{env: env, pool: pool, store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts)}). + newRelay((&relayHarness{env: env}).newPublisher(t, topic)) + for publication := range 2 { + if result, err := relay.PublishPending(ctx); err != nil || result.Published != 1 { + t.Fatalf("publication %d: PublishPending() = %+v, %v; want one event", publication+1, result, err) + } + if _, err := pool.Exec(ctx, "UPDATE outbox_events SET published_at = NULL"); err != nil { + t.Fatalf("mark the event unpublished again: %v", err) + } + } + + metrics := prometheus.New() + group := newConsumerGroup() + source, _ := (&consumerHarness{env: env}).newSource(t, topic, group) + consumerLogger := slog.New(slog.NewJSONHandler(harness.logs, nil)) + consumer, err := eventconsumer.New(harness.handler, source, harness.consumers, metrics, consumerLogger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, consumer) + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2}) + + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0) + assertDeliveryRecords(t, metrics, "applied", 1) + assertDeliveryRecords(t, metrics, "duplicate", 1) + delivery := harness.getDelivery(ctx, t, pool, deliveryID) + content := delivery.Content() + switch { + case delivery.SourceEventID() != event.EventID: + t.Fatal("the delivery does not name the event it came from") + case delivery.RecipientUserID() != recipient.ID || delivery.Recipient().Address() != deliveryRecipientAddress: + t.Fatal("the delivery is not addressed to the recipient account") + case delivery.Kind() != domain.MailKindNotification || content.TemplateVersion() != "notification.v2": + t.Fatalf("delivery kind %s, version %s", delivery.Kind(), content.TemplateVersion()) + case delivery.ProviderAccount() != harness.account: + t.Fatal("the delivery is not pinned to the configured provider account") + case delivery.IdempotencyKey() != "delivery/"+deliveryID.String(): + t.Fatalf("idempotency key %q", delivery.IdempotencyKey()) + case delivery.Status() != domain.DeliveryStatusPending || delivery.AttemptCount() != 0 || delivery.Version() != 1: + t.Fatalf("new delivery is %s with %d attempts at version %d", delivery.Status(), delivery.AttemptCount(), delivery.Version()) + case !strings.Contains(content.Text(), "PRIVATE-BODY") || !strings.Contains(content.Text(), env.Config.AppPublicURL+deliveryLinkPath): + t.Fatal("the stored body is not the rendering of the request") + } + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("a stored delivery keeps its body after the template changes", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, true) + first := harness.requestNotification(ctx, t, recipient) + firstEvent := harness.outboxEvent(ctx, t, first) + harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, firstEvent) + original := harness.getDelivery(ctx, t, pool, first) + + // The template moves on to a later version. A new request gets the new + // version; a replay of the first request under another consumer name + // finds the request consumed and stores nothing. + laterHandler := harness.newHandler(laterVersionRenderer{}) + second := harness.requestNotification(ctx, t, recipient) + harness.apply(ctx, t, notification.DeliveryConsumerName, laterHandler, harness.outboxEvent(ctx, t, second)) + harness.apply(ctx, t, renamedDeliveryConsumer, laterHandler, firstEvent) + + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 2) + if got := harness.getDelivery(ctx, t, pool, second).Content(); got.TemplateVersion() != deliveryLaterVersion { + t.Fatalf("the new request rendered %s, want %s", got.TemplateVersion(), deliveryLaterVersion) + } + // Read through a fresh pool and store, as another instance would. + kept := harness.getDelivery(ctx, t, newPoolFor(ctx, t, env.Config.DatabaseURL), first).Content() + want := original.Content() + if kept.TemplateVersion() != "notification.v2" || kept.Subject() != want.Subject() || + kept.Text() != want.Text() || kept.HTML() != want.HTML() || kept.Hash() != want.Hash() { + t.Fatal("the stored delivery changed after the template version changed") + } + + // The database refuses a direct change of the stored body. + _, err := pool.Exec(ctx, "UPDATE deliveries SET text_body = 'rewritten' WHERE id = $1", first) + assertSQLRefusal(t, err, "deliveries_content_immutable") + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("attempts and the provider message ID survive a restart", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, true) + deliveryID := harness.requestNotification(ctx, t, recipient) + harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID)) + + // The first instance records two attempts through its own pool. + firstPool := newPoolFor(ctx, t, env.Config.DatabaseURL) + firstStore := postgresadapter.NewDeliveryStore(firstPool).Deliveries() + created, err := firstStore.Get(ctx, deliveryID) + if err != nil { + t.Fatalf("Get() error = %v", err) + } + uncertainAt := harness.now.Add(time.Minute) + uncertain, firstAttempt, err := created.RecordAttempt(domain.DeliveryAttemptInput{ + At: uncertainAt, + Outcome: domain.DeliveryOutcomeUnknown, + ProviderCode: "concurrent_idempotent_requests", + RetryAfter: deliveryRetryAfter, + NextAttemptAt: uncertainAt.Add(time.Minute), + }) + if err != nil { + t.Fatalf("RecordAttempt(unknown) error = %v", err) + } + if err := firstStore.RecordAttempt(ctx, uncertain, firstAttempt); err != nil { + t.Fatalf("store the unknown attempt: %v", err) + } + // A second writer of the same attempt loses on the version. + if err := firstStore.RecordAttempt(ctx, uncertain, firstAttempt); !errors.Is(err, outbound.ErrDeliveryVersionConflict) { + t.Fatalf("store the same attempt again: error = %v, want ErrDeliveryVersionConflict", err) + } + acceptedAt := uncertainAt.Add(2 * time.Minute) + accepted, secondAttempt, err := uncertain.RecordAttempt(domain.DeliveryAttemptInput{ + At: acceptedAt, + Outcome: domain.DeliveryOutcomeAccepted, + ProviderMessageID: deliveryMessageID, + }) + if err != nil { + t.Fatalf("RecordAttempt(accepted) error = %v", err) + } + if err := firstStore.RecordAttempt(ctx, accepted, secondAttempt); err != nil { + t.Fatalf("store the accepted attempt: %v", err) + } + firstPool.Close() + + // A new instance reads the state back. + secondStore := postgresadapter.NewDeliveryStore(newPoolFor(ctx, t, env.Config.DatabaseURL)).Deliveries() + restored, err := secondStore.Get(ctx, deliveryID) + if err != nil { + t.Fatalf("Get() after restart error = %v", err) + } + switch { + case restored.Status() != domain.DeliveryStatusAccepted || restored.ProviderMessageID() != deliveryMessageID: + t.Fatalf("restored delivery is %s with message ID %q", restored.Status(), restored.ProviderMessageID()) + case restored.AttemptCount() != 2 || restored.Version() != 3 || !restored.LastAttemptAt().Equal(acceptedAt): + t.Fatalf("restored delivery has %d attempts, version %d, last at %s", restored.AttemptCount(), restored.Version(), restored.LastAttemptAt()) + case !restored.NextAttemptAt().IsZero() || restored.IdempotencyKey() != created.IdempotencyKey(): + t.Fatal("the restored delivery has a next attempt or another key") + } + attempts, err := secondStore.ListAttempts(ctx, deliveryID) + if err != nil { + t.Fatalf("ListAttempts() error = %v", err) + } + // sameAttempt compares RetryAfter exactly, nanoseconds included. + if len(attempts) != 2 || !sameAttempt(attempts[0], firstAttempt) || !sameAttempt(attempts[1], secondAttempt) { + t.Fatalf("restored attempts = %+v, want %+v and %+v", attempts, firstAttempt, secondAttempt) + } + if _, _, err := restored.RecordAttempt(domain.DeliveryAttemptInput{At: acceptedAt.Add(time.Minute), Outcome: domain.DeliveryOutcomeUnknown}); !errors.Is(err, domain.ErrDeliveryTransition) { + t.Fatalf("an attempt after acceptance: error = %v, want ErrDeliveryTransition", err) + } + _, err = pool.Exec(ctx, "UPDATE delivery_attempts SET outcome = 'unknown' WHERE delivery_id = $1", deliveryID) + assertSQLRefusal(t, err, "delivery_attempts_immutable") + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("a delivery is rebound and parked for the quota only within its rules", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, true) + deliveryID := harness.requestNotification(ctx, t, recipient) + harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID)) + store := postgresadapter.NewDeliveryStore(pool).Deliveries() + created := harness.getDelivery(ctx, t, pool, deliveryID) + + otherAccount, err := domain.NewMailProviderAccount(deliveryProvider, deliveryOtherAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + rebound, err := created.Rebind(harness.now.Add(time.Minute), otherAccount) + if err != nil { + t.Fatalf("Rebind() error = %v", err) + } + if err := store.Rebind(ctx, rebound); err != nil { + t.Fatalf("store Rebind() error = %v", err) + } + // A local quota defers the delivery before any attempt; the reset is + // unknown. + waiting, err := rebound.WaitForQuota(harness.now.Add(2*time.Minute), time.Time{}) + if err != nil { + t.Fatalf("WaitForQuota() error = %v", err) + } + if err := store.WaitForQuota(ctx, waiting); err != nil { + t.Fatalf("store WaitForQuota() error = %v", err) + } + if err := store.WaitForQuota(ctx, waiting); !errors.Is(err, outbound.ErrDeliveryVersionConflict) { + t.Fatalf("store WaitForQuota() over a stale version error = %v, want ErrDeliveryVersionConflict", err) + } + stored := harness.getDelivery(ctx, t, pool, deliveryID) + if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().IsZero() || + stored.ProviderAccount() != otherAccount || stored.AttemptCount() != 0 || stored.Version() != 3 { + t.Fatalf("stored delivery is %s due %s on %s/%s with %d attempts at version %d", stored.Status(), stored.NextAttemptAt(), + stored.ProviderAccount().Provider(), stored.ProviderAccount().Account(), stored.AttemptCount(), stored.Version()) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 0) + + // After the first attempt the account is fixed, in the domain and in + // the database. + attemptAt := harness.now.Add(3 * time.Minute) + attempted, attempt, err := stored.RecordAttempt(domain.DeliveryAttemptInput{ + At: attemptAt, Outcome: domain.DeliveryOutcomeRejected, Rejection: domain.DeliveryRejectionTemporary, NextAttemptAt: attemptAt.Add(time.Minute), + }) + if err != nil { + t.Fatalf("RecordAttempt() error = %v", err) + } + if err := store.RecordAttempt(ctx, attempted, attempt); err != nil { + t.Fatalf("store RecordAttempt() error = %v", err) + } + if _, err := attempted.Rebind(attemptAt.Add(time.Minute), harness.account); !errors.Is(err, domain.ErrDeliveryTransition) { + t.Fatalf("Rebind() after an attempt error = %v, want ErrDeliveryTransition", err) + } + _, err = pool.Exec(ctx, "UPDATE deliveries SET provider_account = $2 WHERE id = $1", deliveryID, deliveryAccount) + assertSQLRefusal(t, err, "deliveries_provider_pinned") + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("a notification to an unverified address is skipped", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, false) + deliveryID := harness.requestNotification(ctx, t, recipient) + harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, harness.outboxEvent(ctx, t, deliveryID)) + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0) + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0) + if !strings.Contains(harness.logs.String(), deliveryID.String()) { + t.Fatal("the skip is not logged with the delivery ID") + } + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("a request for an account that no longer exists is skipped", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, true) + deliveryID := harness.requestNotification(ctx, t, recipient) + event := harness.outboxEvent(ctx, t, deliveryID) + if _, err := pool.Exec(ctx, "DELETE FROM users WHERE id = $1", recipient.ID); err != nil { + t.Fatalf("delete the recipient: %v", err) + } + // The request text goes with the account; the outbox keeps only IDs. + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0) + harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, event) + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0) + if !strings.Contains(harness.logs.String(), deliveryID.String()) { + t.Fatal("the skip is not logged with the delivery ID") + } + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("the unverified account cleanup removes requests and deliveries and skips a locked one", func(t *testing.T) { + reset(t) + recipient := harness.createRecipient(ctx, t, false) + // A pending request and a delivery created directly, as the identity + // flows will create token mail. + harness.requestNotification(ctx, t, recipient) + deliveryID := harness.createDeliveryDirectly(ctx, t, recipient) + cutoff := harness.now.Add(time.Hour) + users := harness.identity.Users() + + // A worker holds the delivery row; the cleanup skips the account + // instead of waiting. + held, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin the holding transaction: %v", err) + } + if _, err := held.Exec(ctx, "SELECT 1 FROM deliveries WHERE id = $1 FOR UPDATE", deliveryID); err != nil { + t.Fatalf("lock the delivery: %v", err) + } + deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, 10) + if rollbackErr := held.Rollback(ctx); rollbackErr != nil { + t.Fatalf("release the delivery lock: %v", rollbackErr) + } + if err != nil || deleted != 0 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() with a locked delivery = %d, %v, want 0", deleted, err) + } + + deleted, err = users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, 10) + if err != nil || deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0) + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_requests"}, 0) + harness.assertLogsHoldNoPersonalData(t) + }) +} + +func (harness *deliveryHarness) clock() time.Time { return harness.now } + +func (harness *deliveryHarness) newHandler(renderer notification.NotificationRenderer) *notification.DeliveryHandler { + logger := slog.New(slog.NewJSONHandler(harness.logs, nil)) + return notification.NewDeliveryHandler(renderer, harness.account, harness.clock, logger) +} + +// createRecipient creates an account with deliveryRecipientAddress, +// confirmed when verified is true. +func (harness *deliveryHarness) createRecipient(ctx context.Context, t *testing.T, verified bool) domain.User { + t.Helper() + hash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: mustEmail(t, deliveryRecipientAddress), + PasswordHash: hash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: harness.now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + users := harness.identity.Users() + if err := users.Create(ctx, user); err != nil { + t.Fatalf("create the recipient account: %v", err) + } + if !verified { + return user + } + confirmed, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, harness.now) + if err != nil { + t.Fatalf("confirm the recipient address: %v", err) + } + return confirmed +} + +// requestNotification records a request in a business transaction, as a +// product usecase would, and returns the delivery ID. +func (harness *deliveryHarness) requestNotification(ctx context.Context, t *testing.T, recipient domain.User) uuid.UUID { + t.Helper() + var deliveryID uuid.UUID + err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + deliveryID, err = harness.requester.RequestNotification(ctx, unit, notification.NotificationRequest{ + RecipientUserID: recipient.ID, + Notification: mailtemplate.NotificationData{Subject: deliverySubject, Body: deliveryBody, LinkPath: deliveryLinkPath}, + }) + return err + }) + if err != nil { + t.Fatalf("RequestNotification() error = %v", err) + } + return deliveryID +} + +// createDeliveryDirectly stores a delivery without a request, as a +// transaction that issues a token will. +func (harness *deliveryHarness) createDeliveryDirectly(ctx context.Context, t *testing.T, recipient domain.User) uuid.UUID { + t.Helper() + content, err := domain.NewMailContent(domain.MailKindVerification, "verification.v1", "Подтвердите почту", "PRIVATE-BODY link\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), + RecipientUserID: recipient.ID, + Recipient: recipient.Email, + Content: content, + ProviderAccount: harness.account, + CreatedAt: harness.now, + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := postgresadapter.NewDeliveryStore(harness.pool).Deliveries().Create(ctx, delivery); err != nil || !created { + t.Fatalf("Create() = %t, %v; want the delivery stored", created, err) + } + return delivery.ID() +} + +// outboxEvent reads the request event from the outbox as the consumer +// receives it, and checks that it carries no personal data. +func (harness *deliveryHarness) outboxEvent(ctx context.Context, t *testing.T, deliveryID uuid.UUID) outbound.ConsumedEvent { + t.Helper() + for _, stored := range readOutboxEvents(ctx, t, harness.pool) { + if stored.aggregateID != deliveryID { + continue + } + for _, marker := range append([]string{"@"}, deliveryPrivacyMarkers...) { + if strings.Contains(string(stored.payload), marker) { + t.Fatalf("the outbox event carries personal data: %s", stored.payload) + } + } + return outbound.ConsumedEvent{ + EventID: stored.eventID, + EventType: stored.eventType, + SchemaVersion: stored.schemaVersion, + AggregateType: stored.aggregateType, + AggregateID: stored.aggregateID, + AggregateVersion: stored.aggregateVersion, + OccurredAt: harness.now, + Payload: stored.payload, + } + } + t.Fatalf("no outbox event for delivery %s", deliveryID) + return outbound.ConsumedEvent{} +} + +// apply runs handler in a consumer transaction with its dedup marker, as the +// consumer runtime does, and expects the event to be applied. +func (harness *deliveryHarness) apply( + ctx context.Context, + t *testing.T, + consumer string, + handler *notification.DeliveryHandler, + event outbound.ConsumedEvent, +) { + t.Helper() + applied, err := harness.consumers.ApplyOnce(ctx, consumer, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return handler.Handle(ctx, unit, event) + }) + if err != nil || !applied { + t.Fatalf("ApplyOnce(%s) = %t, %v; want the event applied", consumer, applied, err) + } +} + +func (harness *deliveryHarness) getDelivery(ctx context.Context, t *testing.T, pool *pgxpool.Pool, id uuid.UUID) domain.Delivery { + t.Helper() + delivery, err := postgresadapter.NewDeliveryStore(pool).Deliveries().Get(ctx, id) + if err != nil { + t.Fatalf("Get(%s) error = %v", id, err) + } + return delivery +} + +func (harness *deliveryHarness) assertLogsHoldNoPersonalData(t *testing.T) { + t.Helper() + logs := harness.logs.String() + for _, marker := range deliveryPrivacyMarkers { + if strings.Contains(logs, marker) { + t.Fatalf("personal data %q reached the logs:\n%s", marker, logs) + } + } +} + +// assertDeliveryRecords checks a record counter of the delivery consumer. +func assertDeliveryRecords(t *testing.T, metrics *prometheus.Metrics, outcome string, want int) { + t.Helper() + response := httptest.NewRecorder() + metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + series := fmt.Sprintf(`lincodex_event_consumer_records_total{consumer=%q,outcome=%q} %d`, notification.DeliveryConsumerName, outcome, want) + if !strings.Contains(response.Body.String(), series+"\n") { + t.Fatalf("metrics output lacks %s", series) + } +} + +func assertSQLRefusal(t *testing.T, err error, constraint string) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != "23000" || pgError.ConstraintName != constraint { + t.Fatalf("statement error = %v, want SQLSTATE 23000 on %s", err, constraint) + } +} + +func sameAttempt(got, want domain.DeliveryAttempt) bool { + return got.DeliveryID == want.DeliveryID && got.Number == want.Number && got.At.Equal(want.At) && + got.Outcome == want.Outcome && got.Rejection == want.Rejection && got.ProviderCode == want.ProviderCode && + got.ProviderMessageID == want.ProviderMessageID && got.RetryAfter == want.RetryAfter && + got.StatusAfter == want.StatusAfter && got.NextAttemptAt.Equal(want.NextAttemptAt) +} diff --git a/backend/integration_test/demo_seed_test.go b/backend/integration_test/demo_seed_test.go new file mode 100644 index 0000000..87636f5 --- /dev/null +++ b/backend/integration_test/demo_seed_test.go @@ -0,0 +1,521 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/primary/cli/demoseed" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + seedusecase "lincodex/backend/internal/usecase/demoseed" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" +) + +const ( + demoSeedTimeout = 4 * time.Minute + demoSeedActor = "operator:demo-seed-test" + demoSeedPassword = "synthetic demo stand password" + // demoSeedKeySecret keys the in-test attempt and view services only. + demoSeedKeySecret = "demo-seed-integration-key-secret-0123456789" + ordinaryEmail = "visitor@example.test" +) + +// demoSeedStand is one isolated database with the startup policy seeded, as +// a freshly started backend leaves it. +type demoSeedStand struct { + ctx context.Context + pool *pgxpool.Pool + databaseURL string +} + +func newDemoSeedStand(ctx context.Context, t *testing.T, env *testEnvironment) demoSeedStand { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + return demoSeedStand{ctx: ctx, pool: pool, databaseURL: databaseURL} +} + +// run executes the operator command with the given environment overrides on +// top of the stand's DATABASE_URL, the isolated mode, and the password. +func (stand demoSeedStand) run(t *testing.T, overrides map[string]string, args ...string) (string, error) { + t.Helper() + environment := map[string]string{ + "DATABASE_URL": stand.databaseURL, demoseed.DemoModeName: demoseed.IsolatedDemoMode, + demoseed.PasswordName: demoSeedPassword, + } + for key, value := range overrides { + if value == "" { + delete(environment, key) + continue + } + environment[key] = value + } + lookup := func(key string) (string, bool) { + value, ok := environment[key] + return value, ok + } + var output bytes.Buffer + err := demoseed.Run(stand.ctx, args, lookup, &output, time.Now) + return output.String(), err +} + +func (stand demoSeedStand) inventory(t *testing.T) string { + t.Helper() + output, err := stand.run(t, nil, "inventory") + if err != nil { + t.Fatalf("inventory error = %v (output %q)", err, output) + } + return output +} + +func (stand demoSeedStand) count(t *testing.T, query string, args ...any) int { + t.Helper() + var value int + if err := stand.pool.QueryRow(stand.ctx, query, args...).Scan(&value); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return value +} + +func (stand demoSeedStand) userID(t *testing.T, email string) uuid.UUID { + t.Helper() + var id uuid.UUID + if err := stand.pool.QueryRow(stand.ctx, `SELECT id FROM users WHERE email_normalized = $1`, email).Scan(&id); err != nil { + t.Fatalf("read account %s: %v", email, err) + } + return id +} + +// createOrdinaryAccount stores an unconfirmed registration outside the +// synthetic domain, the way a visitor's own sign-up leaves it. +func (stand demoSeedStand) createOrdinaryAccount(t *testing.T) uuid.UUID { + t.Helper() + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + password, err := domain.NewPassword("ordinary visitor password") + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + hash, err := hasher.Hash(stand.ctx, password) + if err != nil { + t.Fatalf("Hash() error = %v", err) + } + address, err := domain.NewEmailAddress(ordinaryEmail) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: time.Now().UTC().Truncate(time.Microsecond), + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + err = postgresadapter.NewTransactor(stand.pool).WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Users().Create(ctx, user) + }) + if err != nil { + t.Fatalf("create ordinary account: %v", err) + } + return user.ID +} + +func demoEmail(local string) string { return local + "@" + seedusecase.SyntheticDomain } + +func TestDemoSeedCommand(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), demoSeedTimeout) + defer cancel() + + t.Run("refuses without the isolated mode before it connects", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + for _, args := range [][]string{{"seed", "--actor", demoSeedActor}, {"check-reset"}, {"inventory"}} { + for _, mode := range []string{"", "production", "Isolated"} { + overrides := map[string]string{demoseed.DemoModeName: mode} + if _, err := stand.run(t, overrides, args...); err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") { + t.Errorf("%v with DEMO_MODE=%q error = %v, want the isolated mode refusal", args, mode, err) + } + } + } + // An unreachable database proves that the guard runs before connecting. + if _, err := stand.run(t, map[string]string{demoseed.DemoModeName: "", "DATABASE_URL": "postgres://nobody@127.0.0.1:1/none"}, "check-reset"); err == nil || + !strings.Contains(err.Error(), "DEMO_MODE=isolated") { + t.Errorf("check-reset against an unreachable database error = %v, want the mode refusal first", err) + } + if _, err := stand.run(t, map[string]string{demoseed.PasswordName: "short"}, "seed", "--actor", demoSeedActor); err == nil || + !strings.Contains(err.Error(), demoseed.PasswordName) { + t.Errorf("seed with a short password error = %v, want a password refusal", err) + } + if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 0 { + t.Fatalf("accounts after refusals = %d, want none", accounts) + } + if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 { + t.Fatalf("policy versions after refusals = %d, want only the startup version", versions) + } + }) + + t.Run("refuses a stand with ordinary accounts that was never seeded", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + visitor := stand.createOrdinaryAccount(t) + if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err == nil || !strings.Contains(err.Error(), "never seeded") { + t.Fatalf("seed over an ordinary account = %q, %v, want a refusal", output, err) + } + if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "never deletes ordinary data") { + t.Fatalf("check-reset with an ordinary account = %q, %v, want a refusal", output, err) + } + if accounts := stand.count(t, `SELECT count(*) FROM users`); accounts != 1 || stand.userID(t, ordinaryEmail) != visitor { + t.Fatalf("accounts after the refused seed = %d, want only the visitor", accounts) + } + if versions := stand.count(t, `SELECT count(*) FROM policy_versions`); versions != 1 { + t.Fatalf("policy versions after the refused seed = %d, want the startup version only", versions) + } + }) + + t.Run("seeds once, repeats without change, and keeps ordinary data", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (empty)") { + t.Fatalf("check-reset on an empty stand = %q, %v, want allowed", output, err) + } + first, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil { + t.Fatalf("first seed error = %v (output %q)", err, first) + } + if strings.Contains(first, demoSeedPassword) || !strings.Contains(first, "login: candidate@"+seedusecase.SyntheticDomain) || + !strings.Contains(first, "prepared full attempt: ") || strings.Contains(first, "created 0 records") { + t.Fatalf("first seed output = %q, want logins and prepared attempts without the password", first) + } + afterFirst := stand.inventory(t) + for _, want := range []string{ + "synthetic_accounts=9\n", "verified_synthetic_accounts=9\n", "ordinary_accounts=0\n", "organizations=2\n", + "memberships=3\n", "candidate_profiles=7\n", "questionnaires=7\n", "attempts=6\n", "attempt_results=6\n", + "current_categories=6\n", "published_cards=6\n", "product_policy_versions=2\n", "published_families=28\n", + "category_openings=1\n", "category_attestations=1\n", "training_bindings=1\n", + } { + if !strings.Contains(afterFirst, want) { + t.Errorf("inventory after the first seed lacks %q:\n%s", want, afterFirst) + } + } + if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts < 6 { + t.Errorf("evidence facts after the prepared attempts = %d, want the projection of six results", facts) + } + + second, err := stand.run(t, nil, "seed", "--actor", "operator:another-operator") + if err != nil || !strings.Contains(second, "created 0 records") || strings.Contains(second, "updated:") { + t.Fatalf("second seed = %q, %v, want nothing created or updated", second, err) + } + if afterSecond := stand.inventory(t); afterSecond != afterFirst { + t.Fatalf("inventory changed on the repeat:\nfirst:\n%s\nsecond:\n%s", afterFirst, afterSecond) + } + + assertDemoSeedOnboarding(t, stand) + assertDemoSeedMarkers(t, stand) + assertDemoSeedPermissions(t, stand) + assertDemoSeedVisibleCohort(t, stand) + assertExpressAssignsNoCategory(t, stand) + + if output, err := stand.run(t, nil, "check-reset"); err != nil || !strings.Contains(output, "reset allowed (synthetic)") { + t.Fatalf("check-reset on the seeded stand = %q, %v, want allowed", output, err) + } + visitor := stand.createOrdinaryAccount(t) + if output, err := stand.run(t, nil, "check-reset"); err == nil || !strings.Contains(err.Error(), "1 accounts outside") { + t.Fatalf("check-reset with a visitor = %q, %v, want a refusal that counts one ordinary account", output, err) + } + // A repeat after a visitor registered is still a no-op and leaves the + // visitor alone. + if output, err := stand.run(t, nil, "seed", "--actor", demoSeedActor); err != nil || !strings.Contains(output, "created 0 records") { + t.Fatalf("seed after a visitor = %q, %v, want nothing created", output, err) + } + if stand.userID(t, ordinaryEmail) != visitor { + t.Fatal("the visitor account changed") + } + }) + + t.Run("repairs the onboarding step of a stand seeded before the step was set", func(t *testing.T) { + stand := newDemoSeedStand(ctx, t, env) + first, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil { + t.Fatalf("first seed error = %v (output %q)", err, first) + } + afterFirst := stand.inventory(t) + // An earlier seed left every candidate at the consent step. One prepared + // candidate has moved on to a later step, which a repair must keep. + if _, err := stand.pool.Exec(stand.ctx, ` + UPDATE users SET onboarding_step = 'candidate_consents' + WHERE scenario = 'candidate' AND email_normalized LIKE '%@' || $1`, seedusecase.SyntheticDomain); err != nil { + t.Fatalf("set the consent step on every candidate: %v", err) + } + if _, err := stand.pool.Exec(stand.ctx, `UPDATE users SET onboarding_step = 'completed' WHERE email_normalized = $1`, + demoEmail("prepared-1")); err != nil { + t.Fatalf("move one candidate past the assessment: %v", err) + } + + repaired, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil || !strings.Contains(repaired, "created 0 records") || strings.Count(repaired, "updated: onboarding of ") != 6 { + t.Fatalf("repairing seed = %q, %v, want six updated steps and no created record", repaired, err) + } + if step := stand.onboardingStep(t, demoEmail("prepared-1")); step != "completed" { + t.Fatalf("a later step of prepared-1 = %q, want completed kept", step) + } + if at := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'candidate' + AND email_normalized LIKE '%@' || $1 AND onboarding_step = 'candidate_assessment'`, seedusecase.SyntheticDomain); at != 6 { + t.Fatalf("candidates repaired to the assessment step = %d, want six", at) + } + if afterRepair := stand.inventory(t); afterRepair != afterFirst { + t.Fatalf("inventory changed by the repair:\nfirst:\n%s\nrepaired:\n%s", afterFirst, afterRepair) + } + + again, err := stand.run(t, nil, "seed", "--actor", demoSeedActor) + if err != nil || !strings.Contains(again, "created 0 records") || strings.Contains(again, "updated:") { + t.Fatalf("seed after the repair = %q, %v, want nothing created or updated", again, err) + } + }) +} + +// onboardingStep reads the saved onboarding step of one account. +func (stand demoSeedStand) onboardingStep(t *testing.T, email string) string { + t.Helper() + var step string + if err := stand.pool.QueryRow(stand.ctx, `SELECT onboarding_step FROM users WHERE email_normalized = $1`, email).Scan(&step); err != nil { + t.Fatalf("read onboarding step of %s: %v", email, err) + } + return step +} + +// assertDemoSeedOnboarding checks that every synthetic candidate, the +// self-service one and the prepared ones alike, stands at the step that a +// saved questionnaire leaves, and that the employers are unchanged. +func assertDemoSeedOnboarding(t *testing.T, stand demoSeedStand) { + t.Helper() + const candidates = 7 + if total := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'candidate' AND email_normalized LIKE '%@' || $1`, + seedusecase.SyntheticDomain); total != candidates { + t.Fatalf("synthetic candidates = %d, want %d", total, candidates) + } + if at := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'candidate' + AND email_normalized LIKE '%@' || $1 AND onboarding_step = 'candidate_assessment'`, seedusecase.SyntheticDomain); at != candidates { + t.Errorf("candidates at the assessment step = %d, want %d", at, candidates) + } + if step := stand.onboardingStep(t, demoEmail("candidate")); step != "candidate_assessment" { + t.Errorf("the self-service candidate step = %q, want candidate_assessment", step) + } + if employers := stand.count(t, `SELECT count(*) FROM users WHERE scenario = 'employer' AND onboarding_step = 'employer_company' + AND email_normalized LIKE '%@' || $1`, seedusecase.SyntheticDomain); employers != 2 { + t.Errorf("synthetic employers at employer_company = %d, want 2", employers) + } +} + +// assertDemoSeedMarkers checks that every organization and profile of the seed +// names itself as synthetic and that the categories come from the synthetic +// demonstration source. +func assertDemoSeedMarkers(t *testing.T, stand demoSeedStand) { + t.Helper() + if unmarked := stand.count(t, `SELECT count(*) FROM organizations WHERE name NOT LIKE '%(синтетические данные)'`); unmarked != 0 { + t.Errorf("organizations without the synthetic marker = %d", unmarked) + } + if unmarked := stand.count(t, `SELECT count(*) FROM candidate_profiles AS profile WHERE NOT EXISTS ( + SELECT 1 FROM candidate_profile_claims AS claim + WHERE claim.user_id = profile.user_id AND claim.kind = 'full_name' AND claim.value::text LIKE '%синтетический профиль%')`); unmarked != 0 { + t.Errorf("profiles without the synthetic marker in the name = %d", unmarked) + } + if prepared := stand.count(t, `SELECT count(DISTINCT user_id) FROM candidate_profile_claims + WHERE kind = 'experience' AND value::text LIKE '%подготовлена командой demo-seed%'`); prepared != 6 { + t.Errorf("profiles that label the prepared attempt = %d, want 6", prepared) + } + if other := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE source <> 'synthetic_demo' OR calibration_status <> 'uncalibrated'`); other != 0 { + t.Errorf("categories outside the uncalibrated synthetic source = %d", other) + } + if outside := stand.count(t, `SELECT count(*) FROM users WHERE email_normalized NOT LIKE '%@' || $1`, seedusecase.SyntheticDomain); outside != 0 { + t.Errorf("seeded accounts outside the synthetic domain = %d", outside) + } +} + +// assertDemoSeedPermissions checks the two organizations: each has its own +// owner, and the owner of Alpha is only a recruiter of Beta. +func assertDemoSeedPermissions(t *testing.T, stand demoSeedStand) { + t.Helper() + rows, err := stand.pool.Query(stand.ctx, ` + SELECT split_part(users.email_normalized, '@', 1), organizations.name, memberships.role, memberships.state + FROM memberships + JOIN users ON users.id = memberships.user_id + JOIN organizations ON organizations.id = memberships.organization_id + ORDER BY 1, 2`) + if err != nil { + t.Fatalf("read memberships: %v", err) + } + defer rows.Close() + var got []string + for rows.Next() { + var account, organization, role, state string + if err := rows.Scan(&account, &organization, &role, &state); err != nil { + t.Fatalf("scan membership: %v", err) + } + got = append(got, fmt.Sprintf("%s|%s|%s|%s", account, strings.Fields(organization)[1], role, state)) + } + want := []string{ + "employer-alpha|«Альфа»|owner|active", + "employer-alpha|«Бета»|recruiter|active", + "employer-beta|«Бета»|owner|active", + } + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("memberships = %v, want %v", got, want) + } +} + +func demoSeedKeyring(t *testing.T) *identity.Keyring { + t.Helper() + keyring, err := identity.NewKeyring([]byte(demoSeedKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + return keyring +} + +// assertDemoSeedVisibleCohort checks that the owner of Alpha sees the six +// prepared cards, which pass the minimum cohort of five, and no card of the +// self-service candidate, who did not publish. +func assertDemoSeedVisibleCohort(t *testing.T, stand demoSeedStand) { + t.Helper() + key, err := demoSeedKeyring(t).CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + transactor := postgresadapter.NewTransactor(stand.pool) + quota := companyquota.NewService(time.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(stand.pool), key, time.Now), + PseudonymKey: key, Clock: time.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + owner := stand.userID(t, demoEmail("employer-alpha")) + var organizationID uuid.UUID + if err := stand.pool.QueryRow(stand.ctx, `SELECT organization_id FROM memberships WHERE user_id = $1 AND role = 'owner'`, owner).Scan(&organizationID); err != nil { + t.Fatalf("read Alpha: %v", err) + } + var cards []domain.VisibleCandidateCard + err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + cards, err = views.ListVisibleCards(ctx, unit, owner, organizationID) + return err + }) + if err != nil { + t.Fatalf("ListVisibleCards() error = %v", err) + } + selfService := stand.userID(t, demoEmail("candidate")) + if len(cards) != 6 { + t.Fatalf("visible cards of Alpha = %d, want the six prepared candidates", len(cards)) + } + for _, card := range cards { + if card.CandidateID == selfService { + t.Fatal("the unpublished self-service candidate is visible") + } + } +} + +// assertExpressAssignsNoCategory runs the express as the self-service +// candidate through the ordinary attempt operations, then checks that it +// created no category and no evidence, and that the full test still starts. +func assertExpressAssignsNoCategory(t *testing.T, stand demoSeedStand) { + t.Helper() + transactor := postgresadapter.NewTransactor(stand.pool) + attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, demoSeedKeyring(t), time.Now, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + if err != nil { + t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err) + } + candidateID := stand.userID(t, demoEmail("candidate")) + factsBefore := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`) + created, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{ + ActorID: candidateID, IdempotencyKey: "express-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindDemoExpress, + }) + if err != nil || created.Outcome.StatusCode != http.StatusCreated { + t.Fatalf("create express = %+v, %v", created.Outcome, err) + } + var express domain.AssessmentAttempt + err = transactor.WithinTransaction(stand.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + express, err = unit.AssessmentAttempts().GetForCandidate(ctx, candidateID, created.Outcome.Response.ID) + return err + }) + if err != nil { + t.Fatalf("read express attempt: %v", err) + } + snapshot := express.Snapshot() + if len(snapshot.Items) != 3 || snapshot.BankCategory != domain.AssessmentCategory(seedusecase.TrainingCategory) { + t.Fatalf("express has %d items from %q, want 3 from the training category", len(snapshot.Items), snapshot.BankCategory) + } + version := snapshot.Version + for _, item := range snapshot.Items { + reference, err := strconv.ParseInt(item.Variant.ReferenceAnswer, 10, 64) + if err != nil { + t.Fatalf("express reference answer %q: %v", item.Variant.ReferenceAnswer, err) + } + answer, err := json.Marshal(map[string]any{"format": "number", "number": reference}) + if err != nil { + t.Fatalf("marshal express answer: %v", err) + } + result, err := attempts.SubmitAnswer(stand.ctx, assessment.SubmitAttemptAnswerCommand{ + ActorID: candidateID, AttemptID: express.ID(), ItemID: item.ID, ExpectedVersion: version, + IdempotencyKey: "express-answer-" + uuid.NewString(), Answer: answer, + }) + if err != nil || result.Outcome.StatusCode != http.StatusOK { + t.Fatalf("answer express item = %+v, %v", result.Outcome, err) + } + version = result.Outcome.Response.Version + } + finalized, err := attempts.FinalizeAttempt(stand.ctx, assessment.FinalizeAssessmentAttemptCommand{ + ActorID: candidateID, AttemptID: express.ID(), ExpectedVersion: version, IdempotencyKey: "express-finalize-" + uuid.NewString(), + }) + if err != nil || finalized.Outcome.StatusCode != http.StatusOK { + t.Fatalf("finalize express = %+v, %v", finalized.Outcome, err) + } + if categories := stand.count(t, `SELECT count(*) FROM candidate_assessment_categories WHERE candidate_id = $1`, candidateID); categories != 0 { + t.Fatalf("categories after a perfect express = %d, want none", categories) + } + if outcome := stand.count(t, `SELECT count(*) FROM assessment_attempts WHERE id = $1 AND outcome = 'demonstration'`, express.ID().UUID()); outcome != 1 { + t.Fatalf("express outcome rows = %d, want one demonstration outcome", outcome) + } + result, err := attempts.GetMyResult(stand.ctx, candidateID, express.ID()) + if err != nil || result.Summary != "Это тренировочный запуск: он не оценивает и не подтверждает уровень." { + t.Fatalf("express result summary = %q, %v, want the Russian training text", result.Summary, err) + } + if facts := stand.count(t, `SELECT count(*) FROM skill_evidence_facts`); facts != factsBefore { + t.Fatalf("evidence facts after the express = %d, want %d", facts, factsBefore) + } + specialization, grade, language := domain.SpecializationBackend, domain.GradeJunior, domain.TaskLanguageGo + full, err := attempts.CreateAttempt(stand.ctx, assessment.CreateAttemptCommand{ + ActorID: candidateID, IdempotencyKey: "full-" + uuid.NewString(), Kind: domain.AssessmentAttemptKindRoot, + Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language, + }) + if err != nil || full.Outcome.StatusCode != http.StatusCreated { + t.Fatalf("start the full test = %+v, %v, want a new attempt", full.Outcome, err) + } +} diff --git a/backend/integration_test/email_code_test.go b/backend/integration_test/email_code_test.go new file mode 100644 index 0000000..324abf2 --- /dev/null +++ b/backend/integration_test/email_code_test.go @@ -0,0 +1,363 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "regexp" + "sync" + "testing" + "time" +) + +const ( + emailVerificationCodePath = "/api/v1/identity/email-verifications/code" + codeTestTimeout = 5 * time.Minute + // codeWaitAfterMessage waits out the verification message interval of the + // test stand. Its counters use the real clock, as the Redis limiter does. + codeWaitAfterMessage = registrationMinInterval + 100*time.Millisecond +) + +// verificationCodeText finds the code in the text part of the message. +var verificationCodeText = regexp.MustCompile(`Код подтверждения: ([0-9]{6})\b`) + +// codeTokenState is the stored state of one verification token that the code +// path reads and writes. +type codeTokenState struct { + codeStored bool + codeFailedAttempts int + consumed bool + invalidated bool + pendingStored bool + codeLifetimeMinute int64 +} + +func messageCode(t *testing.T, text string) string { + t.Helper() + match := verificationCodeText.FindStringSubmatch(text) + if match == nil { + t.Fatal("the verification message has no six-digit code") + } + return match[1] +} + +func messageToken(t *testing.T, text string) string { + t.Helper() + match := verificationLinkToken.FindStringSubmatch(text) + if match == nil { + t.Fatal("the verification message has no token in its link") + } + return match[1] +} + +// registerAndSendCode registers the address and returns the token of its link +// and the code of its message. +func (harness *registrationHarness) registerAndSendCode(ctx context.Context, t *testing.T, email, scenario, password string) (string, string) { + t.Helper() + text := harness.registerAndReceiveVerification(ctx, t, email, scenario, password) + return messageToken(t, text), messageCode(t, text) +} + +func (harness *registrationHarness) confirmByCode(t *testing.T, email, code, password string) registrationResponse { + t.Helper() + body, err := json.Marshal(struct { + Email string `json:"email"` + Code string `json:"code"` + Password string `json:"password"` + }{Email: email, Code: code, Password: password}) + if err != nil { + t.Fatalf("encode code confirmation request: %v", err) + } + return harness.post(t, emailVerificationCodePath, string(body), nil) +} + +func readCodeTokenState(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) codeTokenState { + t.Helper() + hash := sha256.Sum256([]byte(rawToken)) + var state codeTokenState + err := harness.pool.QueryRow(ctx, ` +SELECT + code_hash IS NOT NULL, + code_failed_attempts, + consumed_at IS NOT NULL, + invalidated_at IS NOT NULL, + pending_password_hash IS NOT NULL, + coalesce(extract(epoch FROM (code_expires_at - created_at)) / 60, 0)::bigint +FROM email_tokens +WHERE token_hash = $1`, hash[:]).Scan( + &state.codeStored, &state.codeFailedAttempts, &state.consumed, &state.invalidated, + &state.pendingStored, &state.codeLifetimeMinute, + ) + if err != nil { + t.Fatalf("read code token state: %v", err) + } + return state +} + +// requireCodeRefusal checks the one refusal of the code operation: the same +// status, content type, and problem code whatever the cause, and no session or +// rate-limit header. +func requireCodeRefusal(t *testing.T, response registrationResponse) { + t.Helper() + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.setCookie != "" || response.retryAfter != "" { + t.Fatalf("refusal set a cookie %q or Retry-After %q", response.setCookie, response.retryAfter) + } +} + +// problemShape returns the body of a refusal without its per-request trace_id, +// so refusals of different causes can be compared. +func problemShape(t *testing.T, response registrationResponse) string { + t.Helper() + var problem map[string]any + if err := json.Unmarshal([]byte(response.body), &problem); err != nil { + t.Fatalf("decode refusal %q: %v", response.body, err) + } + delete(problem, "trace_id") + shape, err := json.Marshal(problem) + if err != nil { + t.Fatalf("encode refusal shape: %v", err) + } + return fmt.Sprintf("%d %s %s", response.status, response.contentType, shape) +} + +func TestEmailVerificationCodeOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), codeTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + publicOrigin := env.Config.AppPublicURL + reset := func(t *testing.T) { + t.Helper() + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + } + + t.Run("the code from the message confirms the registration like the link", func(t *testing.T) { + reset(t) + const email = "code.confirm@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + if before.pendingPasswordHash == nil { + t.Fatal("registration did not store the pending password on the token") + } + state := readCodeTokenState(ctx, t, harness, token) + if !state.codeStored || state.codeLifetimeMinute != 30 || !state.pendingStored { + t.Fatalf("token code state = %+v, want a stored code of 30 minutes", state) + } + + response := harness.confirmByCode(t, email, code, registrationPassword) + requireConfirmationSuccess(t, response, "candidate", "candidate_consents") + after := readConfirmationState(ctx, t, harness, email, token) + assertConfirmationApplied(t, before, after, "candidate", "candidate_consents") + assertSingleConfirmationEvent(ctx, t, harness, email) + if after.sessionCount != 0 { + t.Fatalf("code confirmation created %d sessions, want none", after.sessionCount) + } + afterState := readCodeTokenState(ctx, t, harness, token) + if afterState.codeStored || !afterState.consumed || afterState.pendingStored { + t.Fatalf("consumed token keeps code or pending state: %+v", afterState) + } + harness.assertLogsHoldNoSecrets(t, code, registrationPassword, token) + + replay := harness.confirmByCode(t, email, code, registrationPassword) + requireCodeRefusal(t, replay) + if !sameConfirmationState(after, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("replaying a consumed code changed the account") + } + }) + + t.Run("five wrong codes burn the token, and then even the right code and the link fail", func(t *testing.T) { + reset(t) + const email = "code.burn@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + wrong := wrongDigits(code) + for attempt := 1; attempt <= 5; attempt++ { + requireCodeRefusal(t, harness.confirmByCode(t, email, wrong, registrationPassword)) + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != attempt || state.invalidated != (attempt == 5) { + t.Fatalf("after wrong attempt %d the state is %+v", attempt, state) + } + } + requireCodeRefusal(t, harness.confirmByCode(t, email, code, registrationPassword)) + requireProblemStatus(t, harness.confirm(t, token, registrationPassword, &publicOrigin), http.StatusBadRequest, "verification_token_invalid") + state := readCodeTokenState(ctx, t, harness, token) + if state.consumed || state.codeStored || state.pendingStored { + t.Fatalf("a burned token keeps state: %+v", state) + } + if verified := harness.count(ctx, t, `SELECT count(*) FROM users WHERE email_normalized = $1 AND email_verified_at IS NOT NULL`, email); verified != 0 { + t.Fatal("a burned code verified the address") + } + harness.assertLogsHoldNoSecrets(t, code, wrong, registrationPassword, token) + }) + + t.Run("concurrent wrong codes count at most five attempts", func(t *testing.T) { + reset(t) + const email = "code.concurrent@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "employer", registrationPassword) + wrong := wrongDigits(code) + const parallel = 8 + responses := make([]registrationResponse, parallel) + var group sync.WaitGroup + for index := range parallel { + group.Add(1) + go func() { + defer group.Done() + responses[index] = harness.confirmByCode(t, email, wrong, registrationPassword) + }() + } + group.Wait() + for _, response := range responses { + requireCodeRefusal(t, response) + } + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != 5 || !state.invalidated { + t.Fatalf("concurrent wrong attempts left %+v, want exactly five counted and the token burned", state) + } + }) + + t.Run("a wrong password with the right code is refused and counted", func(t *testing.T) { + reset(t) + const email = "code.password@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + requireCodeRefusal(t, harness.confirmByCode(t, email, code, "this is the wrong password")) + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != 1 || state.consumed || state.invalidated { + t.Fatalf("after a wrong password the state is %+v", state) + } + requireConfirmationSuccess(t, harness.confirmByCode(t, email, code, registrationPassword), "candidate", "candidate_consents") + }) + + t.Run("an expired code is refused, while the link stays valid until the token expires", func(t *testing.T) { + reset(t) + const email = "code.expired@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + harness.clock.Set(harness.clock.Now().Add(31 * time.Minute)) + requireCodeRefusal(t, harness.confirmByCode(t, email, code, registrationPassword)) + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != 1 || state.consumed { + t.Fatalf("expired code state = %+v, want one counted attempt and an open token", state) + } + requireConfirmationSuccess(t, harness.confirm(t, token, registrationPassword, &publicOrigin), "candidate", "candidate_consents") + }) + + t.Run("the link consumes the code and the code consumes the link", func(t *testing.T) { + reset(t) + const linkFirst = "code.link-first@example.com" + token, code := harness.registerAndSendCode(ctx, t, linkFirst, "candidate", registrationPassword) + requireConfirmationSuccess(t, harness.confirm(t, token, registrationPassword, &publicOrigin), "candidate", "candidate_consents") + requireCodeRefusal(t, harness.confirmByCode(t, linkFirst, code, registrationPassword)) + + const codeFirst = "code.code-first@example.com" + token, code = harness.registerAndSendCode(ctx, t, codeFirst, "candidate", registrationPassword) + requireConfirmationSuccess(t, harness.confirmByCode(t, codeFirst, code, registrationPassword), "candidate", "candidate_consents") + requireProblemStatus(t, harness.confirm(t, token, registrationPassword, &publicOrigin), http.StatusBadRequest, "verification_token_invalid") + }) + + t.Run("a resend replaces the code and the earlier code stops working", func(t *testing.T) { + reset(t) + const email = "code.resend@example.com" + _, first := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + time.Sleep(codeWaitAfterMessage) + requestCount := len(harness.fixture.Requests()) + response := harness.resend(t, email) + requireAccepted(t, response) + second := messageCode(t, harness.receiveVerificationText(ctx, t, email, requestCount)) + if first == second { + t.Skip("the two random codes were equal; the replacement cannot be told apart") + } + requireCodeRefusal(t, harness.confirmByCode(t, email, first, registrationPassword)) + requireConfirmationSuccess(t, harness.confirmByCode(t, email, second, registrationPassword), "candidate", "candidate_consents") + }) + + t.Run("a registration replaced by a stranger's address cannot be confirmed with its code", func(t *testing.T) { + reset(t) + const email = "code.hijack@example.com" + const attackerPassword = "attacker registered this address first" + attackerToken, attackerCode := harness.registerAndSendCode(ctx, t, email, "candidate", attackerPassword) + time.Sleep(codeWaitAfterMessage) + harness.clock.Set(harness.clock.Now().Add(time.Minute)) + requestCount := len(harness.fixture.Requests()) + requireAccepted(t, harness.register(t, email, "candidate", "")) + ownerText := harness.receiveVerificationText(ctx, t, email, requestCount) + ownerCode := messageCode(t, ownerText) + ownerToken := messageToken(t, ownerText) + if state := readCodeTokenState(ctx, t, harness, attackerToken); !state.invalidated { + t.Fatal("the owner's registration did not replace the earlier token") + } + requireCodeRefusal(t, harness.confirmByCode(t, email, attackerCode, attackerPassword)) + requireCodeRefusal(t, harness.confirmByCode(t, email, ownerCode, attackerPassword)) + requireConfirmationSuccess(t, harness.confirmByCode(t, email, ownerCode, registrationPassword), "candidate", "candidate_consents") + if ownerState := readCodeTokenState(ctx, t, harness, ownerToken); !ownerState.consumed { + t.Fatal("the owner's code did not consume the owner's token") + } + }) + + t.Run("an unknown address and a wrong code give the same refusal", func(t *testing.T) { + reset(t) + const email = "code.enumeration@example.com" + _, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + unknown := harness.confirmByCode(t, "nobody.registered@example.com", code, registrationPassword) + wrong := harness.confirmByCode(t, email, wrongDigits(code), registrationPassword) + expired := harness.confirmByCode(t, "nobody.either@example.com", wrongDigits(code), "a password nobody set") + if problemShape(t, unknown) != problemShape(t, wrong) || problemShape(t, wrong) != problemShape(t, expired) { + t.Fatalf("refusals differ:\nunknown %s\nwrong %s\nother %s", problemShape(t, unknown), problemShape(t, wrong), problemShape(t, expired)) + } + }) + + t.Run("a malformed code is a validation failure before any lookup", func(t *testing.T) { + reset(t) + for _, body := range []string{ + `{"email":"candidate@example.com","code":"12345","password":"` + registrationPassword + `"}`, + `{"email":"candidate@example.com","code":"1234567","password":"` + registrationPassword + `"}`, + } { + response := harness.post(t, emailVerificationCodePath, body, nil) + requireProblemStatus(t, response, http.StatusBadRequest, "validation_failed") + } + }) + + t.Run("the address limit refuses after ten code requests", func(t *testing.T) { + reset(t) + const email = "code.limit@example.com" + _, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + wrong := wrongDigits(code) + for range registrationEmailHourlyLimit { + response := harness.confirmByCode(t, email, wrong, registrationPassword) + if response.status != http.StatusBadRequest { + t.Fatalf("request within the limit = %d %s", response.status, response.body) + } + } + limited := harness.confirmByCode(t, email, code, registrationPassword) + requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.retryAfter == "" { + t.Fatal("the refused code request has no Retry-After") + } + }) + + t.Run("an origin that is not the public one is refused before the usecase", func(t *testing.T) { + reset(t) + const email = "code.origin@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + body, err := json.Marshal(map[string]string{"email": email, "code": code, "password": registrationPassword}) + if err != nil { + t.Fatal(err) + } + response := harness.postWithOriginDefault(t, emailVerificationCodePath, string(body), map[string]string{"Origin": "https://foreign.example"}, false) + requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed") + if state := readCodeTokenState(ctx, t, harness, token); state.codeFailedAttempts != 0 { + t.Fatal("a refused origin counted an attempt") + } + }) +} + +// wrongDigits returns a six-digit code that differs from code. +func wrongDigits(code string) string { + if code == "000000" { + return "000001" + } + return "000000" +} diff --git a/backend/integration_test/email_verification_test.go b/backend/integration_test/email_verification_test.go new file mode 100644 index 0000000..e0df035 --- /dev/null +++ b/backend/integration_test/email_verification_test.go @@ -0,0 +1,680 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "mime" + "net/http" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" +) + +const ( + confirmationTestTimeout = 5 * time.Minute + confirmationRetryWindow = time.Hour + confirmationSecondPassword = "another correct horse battery staple" + confirmationWrongPassword = "this is the wrong password" + confirmationUnknownToken = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + confirmationFailureFunction = "integration_reject_email_confirmation" + confirmationFailureTrigger = "integration_reject_email_confirmation_event" +) + +type confirmationState struct { + scenario string + onboardingStep string + passwordHash string + emailVerifiedAt *time.Time + registrationVersion int64 + userVersion int64 + tokenRegistrationVersion int64 + tokenConsumedAt *time.Time + tokenInvalidatedAt *time.Time + pendingPasswordHash *string + pendingScenario *string + pendingOnboardingStep *string + c1RegistrationVersion *int64 + tokenCount int + sessionCount int + confirmationEventCount int +} + +func TestEmailVerificationOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), confirmationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + reset := func(t *testing.T) { + t.Helper() + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + } + publicOrigin := env.Config.AppPublicURL + + t.Run("a candidate and employer confirm the registration received by mail", func(t *testing.T) { + for _, test := range []struct { + name string + email string + scenario string + step string + }{ + {name: "candidate", email: "confirm.candidate@example.com", scenario: "candidate", step: "candidate_consents"}, + {name: "employer", email: "confirm.employer@example.com", scenario: "employer", step: "employer_company"}, + } { + t.Run(test.name, func(t *testing.T) { + reset(t) + token := harness.registerAndSendVerification(ctx, t, test.email, test.scenario, registrationPassword) + before := readConfirmationState(ctx, t, harness, test.email, token) + if before.pendingPasswordHash == nil || before.c1RegistrationVersion == nil || + *before.c1RegistrationVersion != before.tokenRegistrationVersion { + t.Fatal("registration did not bind its C1 record and pending password to the emailed token") + } + + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireConfirmationSuccess(t, response, test.scenario, test.step) + after := readConfirmationState(ctx, t, harness, test.email, token) + assertConfirmationApplied(t, before, after, test.scenario, test.step) + assertSingleConfirmationEvent(ctx, t, harness, test.email) + if after.sessionCount != 0 { + t.Fatalf("confirmation created %d sessions, want none", after.sessionCount) + } + harness.assertLogsHoldNoSecrets(t, test.email, registrationPassword, token) + + // A consumed link cannot be replayed and leaves the committed account alone. + replay := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireProblemStatus(t, replay, http.StatusBadRequest, "verification_token_invalid") + if replay.setCookie != "" || !sameConfirmationState(after, readConfirmationState(ctx, t, harness, test.email, token)) { + t.Fatal("replaying a consumed token changed the account or set a cookie") + } + }) + } + }) + + t.Run("an unknown token is refused without creating identity state", func(t *testing.T) { + reset(t) + response := harness.confirm(t, confirmationUnknownToken, registrationPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.retryAfter != "" || response.setCookie != "" || + harness.count(ctx, t, `SELECT count(*) FROM users`) != 0 || + harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != 0 || + harness.count(ctx, t, `SELECT count(*) FROM sessions`) != 0 || + harness.count(ctx, t, `SELECT count(*) FROM outbox_events WHERE event_type = 'identity.email_verified'`) != 0 { + t.Fatal("an unknown token changed identity state or returned rate-limit/session headers") + } + harness.assertLogsHoldNoSecrets(t, confirmationUnknownToken, registrationPassword) + }) + + t.Run("an expired token remains unconsumed", func(t *testing.T) { + reset(t) + const email = "confirm.expired@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + expiresAt := tokenExpiresAt(ctx, t, harness, token) + harness.clock.Set(expiresAt.Add(time.Second)) + + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired") + if response.retryAfter != "" || response.setCookie != "" || + !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("an expired token changed the account or returned rate-limit/session headers") + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + + t.Run("an expired active token from an earlier registration version is invalid", func(t *testing.T) { + reset(t) + const email = "confirm.stale-active-version@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + hash := sha256.Sum256([]byte(token)) + deadline := harness.clock.Now().Add(time.Second) + harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, deadline, hash[:]) + harness.clock.Set(deadline.Add(time.Second)) + harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`, + harness.clock.Now(), strings.ToLower(email)) + before := readConfirmationState(ctx, t, harness, email, token) + if before.tokenInvalidatedAt != nil || before.pendingPasswordHash == nil || + before.registrationVersion == before.tokenRegistrationVersion || !deadline.Before(harness.clock.Now()) { + t.Fatal("fixture does not contain an expired, active token for an earlier account version") + } + + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.retryAfter != "" || response.setCookie != "" || + !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("an expired active token from an earlier account version changed identity state") + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + + t.Run("expiry is checked after confirmation waits for token, consent, or user locks", func(t *testing.T) { + for _, target := range []struct { + name string + query string + }{ + {name: "token", query: `SELECT 1 FROM email_tokens WHERE token_hash = $1 FOR UPDATE`}, + {name: "registration consent", query: ` + SELECT 1 FROM consent_records AS consent + JOIN users AS account ON account.id = consent.subject_id + WHERE account.email_normalized = $1 AND consent.purpose = 'c1' + AND consent.source = 'registration' AND consent.revoked_at IS NULL + FOR UPDATE OF consent`}, + {name: "user", query: `SELECT 1 FROM users WHERE email_normalized = $1 FOR UPDATE`}, + } { + t.Run(target.name, func(t *testing.T) { + reset(t) + email := "confirm.lock-expiry-" + strings.ReplaceAll(target.name, " ", "-") + "@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + expiresAt := tokenExpiresAt(ctx, t, harness, token) + monitorPool := env.newPool(ctx, t) + holder, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin %s lock: %v", target.name, err) + } + defer func() { + if err := holder.Rollback(context.WithoutCancel(ctx)); err != nil && !errors.Is(err, pgx.ErrTxClosed) { + t.Errorf("release %s lock: %v", target.name, err) + } + }() + + var lockKey any = strings.ToLower(email) + if target.name == "token" { + hash := sha256.Sum256([]byte(token)) + lockKey = hash[:] + } + var locked int + if err := holder.QueryRow(ctx, target.query, lockKey).Scan(&locked); err != nil { + t.Fatalf("lock the emailed %s row: %v", target.name, err) + } + + type confirmationReply struct{ response registrationResponse } + reply := make(chan confirmationReply, 1) + go func() { + reply <- confirmationReply{response: harness.confirm(t, token, registrationPassword, &publicOrigin)} + }() + waitEvent, observed := waitForLockWait(ctx, monitorPool, registrationApplication) + if !observed { + _ = holder.Rollback(context.WithoutCancel(ctx)) + <-reply + t.Fatalf("confirmation did not wait on the %s row lock (last wait event %q)", target.name, waitEvent) + } + harness.clock.Set(expiresAt.Add(time.Second)) + if err := holder.Commit(ctx); err != nil { + t.Fatalf("release the %s lock: %v", target.name, err) + } + response := (<-reply).response + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired") + if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatalf("a request queued on the %s lock consumed the token after its deadline", target.name) + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + } + }) + + t.Run("missing, null, and foreign Origin values are rejected without consuming the token", func(t *testing.T) { + reset(t) + const email = "confirm.origin@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + for _, test := range []struct { + name string + origin *string + }{ + {name: "missing"}, + {name: "null", origin: stringPointer("null")}, + {name: "foreign", origin: stringPointer("https://foreign.example")}, + } { + t.Run(test.name, func(t *testing.T) { + response := harness.confirm(t, token, registrationPassword, test.origin) + requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed") + if response.retryAfter != "" || response.setCookie != "" || + !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("an invalid Origin changed the account or returned rate-limit/session headers") + } + }) + } + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireConfirmationSuccess(t, response, "candidate", "candidate_consents") + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + + t.Run("the second registrant confirms only with its own password and token", func(t *testing.T) { + reset(t) + const email = "confirm.replaced@example.com" + firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + firstHash := sha256.Sum256([]byte(firstToken)) + firstDeadline := harness.clock.Now().Add(time.Second) + harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, firstDeadline, firstHash[:]) + harness.clock.Set(firstDeadline.Add(time.Second)) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword) + oldBefore := readConfirmationState(ctx, t, harness, email, firstToken) + if oldBefore.tokenInvalidatedAt == nil || oldBefore.pendingPasswordHash != nil { + t.Fatal("re-registration did not invalidate the old token and clear its pending credentials") + } + + old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin) + requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid") + if !sameConfirmationState(oldBefore, readConfirmationState(ctx, t, harness, email, firstToken)) { + t.Fatal("an expired token from a replaced registration changed account or token rows") + } + + currentBefore := readConfirmationState(ctx, t, harness, email, secondToken) + wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin) + requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid") + if !sameConfirmationState(currentBefore, readConfirmationState(ctx, t, harness, email, secondToken)) { + t.Fatal("a wrong password consumed the current token or changed the account") + } + + accepted := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin) + requireConfirmationSuccess(t, accepted, "employer", "employer_company") + after := readConfirmationState(ctx, t, harness, email, secondToken) + assertConfirmationApplied(t, currentBefore, after, "employer", "employer_company") + assertSingleConfirmationEvent(ctx, t, harness, email) + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken) + }) + + t.Run("the original registrant can replace a second registrant before confirmation", func(t *testing.T) { + reset(t) + const email = "confirm.owner-first@example.com" + firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword) + firstAfterReplacement := readConfirmationState(ctx, t, harness, email, firstToken) + if firstAfterReplacement.tokenInvalidatedAt == nil || firstAfterReplacement.pendingPasswordHash != nil { + t.Fatal("the second registration did not invalidate the original token and clear its pending credentials") + } + + old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin) + requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid") + if !sameConfirmationState(firstAfterReplacement, readConfirmationState(ctx, t, harness, email, firstToken)) { + t.Fatal("the original registrant's replaced token changed account or token rows") + } + + secondBefore := readConfirmationState(ctx, t, harness, email, secondToken) + wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin) + requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid") + if !sameConfirmationState(secondBefore, readConfirmationState(ctx, t, harness, email, secondToken)) { + t.Fatal("the original password consumed the second registrant's token or changed the account") + } + + time.Sleep(registrationMinInterval + 100*time.Millisecond) + harness.clock.Advance(registrationMinInterval + time.Second) + thirdToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + secondAfterReplacement := readConfirmationState(ctx, t, harness, email, secondToken) + if secondAfterReplacement.tokenInvalidatedAt == nil || secondAfterReplacement.pendingPasswordHash != nil { + t.Fatal("the original registrant's new registration did not invalidate the second token") + } + superseded := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin) + requireProblemStatus(t, superseded, http.StatusBadRequest, "verification_token_invalid") + if !sameConfirmationState(secondAfterReplacement, readConfirmationState(ctx, t, harness, email, secondToken)) { + t.Fatal("confirming the superseded second registration changed account or token rows") + } + + thirdBefore := readConfirmationState(ctx, t, harness, email, thirdToken) + accepted := harness.confirm(t, thirdToken, registrationPassword, &publicOrigin) + requireConfirmationSuccess(t, accepted, "candidate", "candidate_consents") + after := readConfirmationState(ctx, t, harness, email, thirdToken) + assertConfirmationApplied(t, thirdBefore, after, "candidate", "candidate_consents") + assertSingleConfirmationEvent(ctx, t, harness, email) + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken, thirdToken) + }) + + t.Run("a confirmed registration stays current if another registration follows", func(t *testing.T) { + reset(t) + const email = "confirm.before-reregistration@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireConfirmationSuccess(t, response, "candidate", "candidate_consents") + confirmed := readConfirmationState(ctx, t, harness, email, token) + assertConfirmationApplied(t, before, confirmed, "candidate", "candidate_consents") + + time.Sleep(registrationMinInterval + 100*time.Millisecond) + registrationResponse := harness.registerBody(t, registrationBody(email, "employer", confirmationSecondPassword, registrationC1), "") + requireAccepted(t, registrationResponse) + if registrationResponse.setCookie != "" || !sameConfirmationState(confirmed, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("a registration after confirmation changed the verified account") + } + assertSingleConfirmationEvent(ctx, t, harness, email) + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token, confirmationSecondPassword) + }) + + t.Run("a token cannot use the C1 record of another registration version", func(t *testing.T) { + reset(t) + const email = "confirm.c1-version@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + if before.c1RegistrationVersion == nil || *before.c1RegistrationVersion != before.tokenRegistrationVersion { + t.Fatal("initial C1 record is not bound to the token registration version") + } + hash := sha256.Sum256([]byte(token)) + harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`, + harness.clock.Now().Add(time.Second), strings.ToLower(email)) + harness.exec(ctx, t, `UPDATE email_tokens SET registration_version = registration_version + 1 WHERE token_hash = $1`, hash[:]) + stale := readConfirmationState(ctx, t, harness, email, token) + if stale.registrationVersion != stale.tokenRegistrationVersion || stale.c1RegistrationVersion == nil || + *stale.c1RegistrationVersion == stale.tokenRegistrationVersion { + t.Fatal("fixture did not create a token and account version newer than its C1 record") + } + + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.setCookie != "" || !sameConfirmationState(stale, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("a token without current-version C1 changed the account or token") + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + + t.Run("a token without pending registration credentials cannot be confirmed", func(t *testing.T) { + reset(t) + const email = "confirm.no-pending@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + hash := sha256.Sum256([]byte(token)) + harness.exec(ctx, t, `UPDATE email_tokens SET pending_password_hash = NULL, pending_scenario = NULL, pending_onboarding_step = NULL WHERE token_hash = $1`, hash[:]) + before := readConfirmationState(ctx, t, harness, email, token) + if before.pendingPasswordHash != nil || before.pendingScenario != nil || before.pendingOnboardingStep != nil { + t.Fatal("test token still has pending registration data") + } + + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("a token without pending registration data changed the account or token") + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + + t.Run("confirmation rate limits refusals and reports Retry-After", func(t *testing.T) { + reset(t) + const email = "confirm.rate-limit@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + for range 2 { + response := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.retryAfter != "" || response.setCookie != "" || + !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("a refused password attempt changed identity state or returned rate-limit/session headers") + } + } + limited := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin) + requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited") + requirePositiveRetryAfter(t, limited) + if limited.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("a rate-limited confirmation changed identity state or set a cookie") + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationWrongPassword, token) + }) + + t.Run("an outbox failure rolls back token consumption and account confirmation", func(t *testing.T) { + reset(t) + const email = "confirm.rollback@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + installConfirmationOutboxFailure(ctx, t, harness) + + response := harness.confirm(t, token, registrationPassword, &publicOrigin) + requireProblemStatus(t, response, http.StatusInternalServerError, "internal") + if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("a failed confirmation outbox insert did not roll back all account and token changes") + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) + + t.Run("two concurrent HTTP confirmations produce one success and one event", func(t *testing.T) { + reset(t) + const email = "confirm.concurrent@example.com" + token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + responses := make([]registrationResponse, 2) + start := make(chan struct{}) + finished := make(chan int, len(responses)) + for index := range responses { + go func(index int) { + <-start + responses[index] = harness.confirm(t, token, registrationPassword, &publicOrigin) + finished <- index + }(index) + } + close(start) + <-finished + <-finished + + successes := 0 + refusals := 0 + for _, response := range responses { + switch response.status { + case http.StatusOK: + successes++ + requireConfirmationSuccess(t, response, "candidate", "candidate_consents") + case http.StatusBadRequest: + refusals++ + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + default: + t.Fatalf("concurrent confirmation returned status %d, want one success and one invalid-token refusal", response.status) + } + if response.setCookie != "" { + t.Fatal("confirmation set a cookie") + } + } + if successes != 1 || refusals != 1 { + t.Fatalf("concurrent confirmations had %d successes and %d refusals, want one each", successes, refusals) + } + after := readConfirmationState(ctx, t, harness, email, token) + assertConfirmationApplied(t, before, after, "candidate", "candidate_consents") + assertSingleConfirmationEvent(ctx, t, harness, email) + if after.sessionCount != 0 { + t.Fatalf("concurrent confirmation created %d sessions, want none", after.sessionCount) + } + harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token) + }) +} + +func (harness *registrationHarness) confirm(t *testing.T, token, password string, origin *string) registrationResponse { + t.Helper() + headers := make(map[string]string) + if origin != nil { + headers["Origin"] = *origin + } + body, err := json.Marshal(struct { + Token string `json:"token"` + Password string `json:"password"` + }{Token: token, Password: password}) + if err != nil { + t.Fatalf("encode confirmation request: %v", err) + } + if origin == nil { + return harness.postWithoutDefaultOrigin(t, emailVerificationPath, string(body), headers) + } + return harness.post(t, emailVerificationPath, string(body), headers) +} + +func readConfirmationState(ctx context.Context, t *testing.T, harness *registrationHarness, email, rawToken string) confirmationState { + t.Helper() + hash := sha256.Sum256([]byte(rawToken)) + var state confirmationState + err := harness.pool.QueryRow(ctx, ` + SELECT account.scenario, account.onboarding_step, account.password_hash, + account.email_verified_at, account.registration_version, account.version, + token.registration_version, token.consumed_at, token.invalidated_at, + token.pending_password_hash, token.pending_scenario, token.pending_onboarding_step, + consent.registration_version, + (SELECT count(*)::integer FROM email_tokens WHERE user_id = account.id), + (SELECT count(*)::integer FROM sessions WHERE user_id = account.id), + (SELECT count(*)::integer FROM outbox_events + WHERE aggregate_id = account.id AND event_type = 'identity.email_verified') + FROM users AS account + JOIN email_tokens AS token ON token.user_id = account.id AND token.token_hash = $1 + LEFT JOIN LATERAL ( + SELECT registration_version FROM consent_records + WHERE subject_id = account.id AND purpose = 'c1' AND source = 'registration' AND revoked_at IS NULL + ORDER BY granted_at DESC, id DESC LIMIT 1 + ) AS consent ON TRUE + WHERE account.email_normalized = $2`, hash[:], strings.ToLower(email)).Scan( + &state.scenario, &state.onboardingStep, &state.passwordHash, + &state.emailVerifiedAt, &state.registrationVersion, &state.userVersion, + &state.tokenRegistrationVersion, &state.tokenConsumedAt, &state.tokenInvalidatedAt, + &state.pendingPasswordHash, &state.pendingScenario, &state.pendingOnboardingStep, + &state.c1RegistrationVersion, &state.tokenCount, &state.sessionCount, &state.confirmationEventCount, + ) + if err != nil { + t.Fatalf("read confirmation state: %v", err) + } + return state +} + +func tokenExpiresAt(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) time.Time { + t.Helper() + hash := sha256.Sum256([]byte(rawToken)) + var expiresAt time.Time + if err := harness.pool.QueryRow(ctx, `SELECT expires_at FROM email_tokens WHERE token_hash = $1`, hash[:]).Scan(&expiresAt); err != nil { + t.Fatalf("read emailed token deadline: %v", err) + } + return expiresAt +} + +func sameConfirmationState(left, right confirmationState) bool { + return left.scenario == right.scenario && left.onboardingStep == right.onboardingStep && + left.passwordHash == right.passwordHash && sameOptionalTime(left.emailVerifiedAt, right.emailVerifiedAt) && + left.registrationVersion == right.registrationVersion && left.userVersion == right.userVersion && + left.tokenRegistrationVersion == right.tokenRegistrationVersion && + sameOptionalTime(left.tokenConsumedAt, right.tokenConsumedAt) && + sameOptionalTime(left.tokenInvalidatedAt, right.tokenInvalidatedAt) && + sameOptionalString(left.pendingPasswordHash, right.pendingPasswordHash) && + sameOptionalString(left.pendingScenario, right.pendingScenario) && + sameOptionalString(left.pendingOnboardingStep, right.pendingOnboardingStep) && + sameOptionalInt64(left.c1RegistrationVersion, right.c1RegistrationVersion) && + left.tokenCount == right.tokenCount && left.sessionCount == right.sessionCount && + left.confirmationEventCount == right.confirmationEventCount +} + +func assertConfirmationApplied(t *testing.T, before, after confirmationState, scenario, step string) { + t.Helper() + if after.scenario != scenario || after.onboardingStep != step || after.emailVerifiedAt == nil || + after.registrationVersion != before.tokenRegistrationVersion || + after.userVersion != before.userVersion+1 || after.tokenConsumedAt == nil || + after.tokenInvalidatedAt != nil || after.pendingPasswordHash != nil || + after.pendingScenario != nil || after.pendingOnboardingStep != nil || + after.c1RegistrationVersion == nil || *after.c1RegistrationVersion != after.tokenRegistrationVersion || + before.pendingPasswordHash == nil || after.passwordHash != *before.pendingPasswordHash || + after.tokenCount != before.tokenCount || after.sessionCount != 0 || after.confirmationEventCount != 1 { + t.Fatal("confirmation did not atomically apply the emailed registration and consume its token") + } +} + +func assertSingleConfirmationEvent(ctx context.Context, t *testing.T, harness *registrationHarness, email string) { + t.Helper() + var userID string + if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users WHERE email_normalized = $1`, strings.ToLower(email)).Scan(&userID); err != nil { + t.Fatalf("read confirmed account ID: %v", err) + } + var count int + var eventType, aggregateType, aggregateID, payload string + var aggregateVersion int64 + rows, err := harness.pool.Query(ctx, `SELECT event_type, aggregate_type, aggregate_id::text, aggregate_version, payload::text + FROM outbox_events WHERE event_type = 'identity.email_verified' AND aggregate_id = $1`, userID) + if err != nil { + t.Fatalf("read confirmation outbox event: %v", err) + } + for rows.Next() { + count++ + if err := rows.Scan(&eventType, &aggregateType, &aggregateID, &aggregateVersion, &payload); err != nil { + rows.Close() + t.Fatalf("scan confirmation outbox event: %v", err) + } + } + if err := rows.Err(); err != nil { + rows.Close() + t.Fatalf("read confirmation outbox events: %v", err) + } + rows.Close() + var userVersion int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1::uuid`, userID).Scan(&userVersion); err != nil { + t.Fatalf("read confirmed account version: %v", err) + } + if count != 1 || eventType != "identity.email_verified" || aggregateType != "user" || + aggregateID != userID || aggregateVersion != userVersion || payload != "{}" { + t.Fatal("confirmation outbox event count or contents do not match the confirmed account") + } +} + +func requireConfirmationSuccess(t *testing.T, response registrationResponse, scenario, step string) { + t.Helper() + want := fmt.Sprintf(`{"email_verified":true,"scenario":%q,"onboarding_step":%q}`, scenario, step) + mediaType, _, contentTypeErr := mime.ParseMediaType(response.contentType) + if response.status != http.StatusOK || response.body != want || contentTypeErr != nil || mediaType != "application/json" || + response.setCookie != "" || response.retryAfter != "" { + t.Fatalf("confirmation response = %d %q (content type %q, Set-Cookie present %t, Retry-After %q), want 200 %q with JSON media type and no session or rate-limit headers", + response.status, response.body, response.contentType, response.setCookie != "", response.retryAfter, want) + } +} + +func requirePositiveRetryAfter(t *testing.T, response registrationResponse) { + t.Helper() + seconds, err := strconv.Atoi(response.retryAfter) + if err != nil || seconds < 1 || seconds > int(confirmationRetryWindow/time.Second) { + t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(confirmationRetryWindow/time.Second)) + } +} + +func installConfirmationOutboxFailure(ctx context.Context, t *testing.T, harness *registrationHarness) { + t.Helper() + harness.exec(ctx, t, fmt.Sprintf(`CREATE FUNCTION %s() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.event_type = 'identity.email_verified' THEN + RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'test confirmation outbox failure'; + END IF; + RETURN NEW; + END; + $$`, pgx.Identifier{confirmationFailureFunction}.Sanitize())) + harness.exec(ctx, t, fmt.Sprintf(`CREATE TRIGGER %s BEFORE INSERT ON outbox_events + FOR EACH ROW EXECUTE FUNCTION %s()`, + pgx.Identifier{confirmationFailureTrigger}.Sanitize(), + pgx.Identifier{confirmationFailureFunction}.Sanitize())) + t.Cleanup(func() { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON outbox_events`, + pgx.Identifier{confirmationFailureTrigger}.Sanitize())); err != nil { + t.Errorf("drop confirmation outbox trigger: %v", err) + } + if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP FUNCTION IF EXISTS %s()`, + pgx.Identifier{confirmationFailureFunction}.Sanitize())); err != nil { + t.Errorf("drop confirmation outbox trigger function: %v", err) + } + }) +} + +func stringPointer(value string) *string { return &value } + +func sameOptionalString(left, right *string) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func sameOptionalTime(left, right *time.Time) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return left.Equal(*right) +} + +func sameOptionalInt64(left, right *int64) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} diff --git a/backend/integration_test/event_consumer_test.go b/backend/integration_test/event_consumer_test.go new file mode 100644 index 0000000..3462bde --- /dev/null +++ b/backend/integration_test/event_consumer_test.go @@ -0,0 +1,1207 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "log/slog" + "maps" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" + + "lincodex/backend/internal/adapter/secondary/kafka" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/eventconsumer" + "lincodex/backend/internal/worker/retry" +) + +const ( + consumerTestTimeout = 5 * time.Minute + // consumerWaitTimeout bounds every wait for a consumer to reach a state; + // it covers the group join and the first fetch on a loaded machine. + consumerWaitTimeout = time.Minute + // consumerStopTimeout bounds Run's return after cancellation: the grace + // plus one commit and margin. + consumerStopTimeout = 15 * time.Second + consumerName = "integration_effects" + consumerEventType = "test.effect_requested" + consumerAggregate = "test_effect" + consumerMaxAttempts = 3 + consumerShortBackoff = 10 * time.Millisecond + // consumerPoisonBackoff makes every retry wait between 100ms and 200ms, + // long enough to tell backoff from a hot loop. + consumerPoisonBackoff = 200 * time.Millisecond + consumerPoisonMinimumGap = consumerPoisonBackoff / 2 + // consumerPoisonBudget bounds the whole retry sequence of one poison + // event: the attempts are fast, so it is the backoff plus a large margin. + consumerPoisonBudget = 5 * time.Second + // consumerHandlerTime outlasts lockWaitTimeout, so a race test on a slow + // machine fails on the lock wait it asserts, not on an attempt timeout. + consumerHandlerTime = 2 * lockWaitTimeout + consumerCommitTimeout = 5 * time.Second + consumerGrace = 2 * time.Second + // consumerShortGrace lets a stuck handler be canceled quickly. + consumerShortGrace = 300 * time.Millisecond + // consumerQuietPeriod is how long a test watches that a finished consumer + // does not touch a record again. + consumerQuietPeriod = 500 * time.Millisecond + effectsTable = "effects" + effectsSchema = "consumer_test" + racingApplication = "consumer_race_second" +) + +var ( + effectsIdentifier = pgx.Identifier{effectsSchema, effectsTable} + createEffectsTable = fmt.Sprintf(` + CREATE SCHEMA %[1]s; + -- No unique key: a second effect for an event must stay visible. + CREATE TABLE %[2]s ( + event_id uuid NOT NULL, + consumer_name text NOT NULL + )`, pgx.Identifier{effectsSchema}.Sanitize(), effectsIdentifier.Sanitize()) + errEffectFailed = errors.New("effect failed") +) + +// effectHandler is the test-only consumer: it writes one row per applied +// event into a table that exists only in this test, then runs hook inside +// the same transaction. +type effectHandler struct { + hook func(ctx context.Context, tx pgx.Tx, event outbound.ConsumedEvent) error + + mu sync.Mutex + calls map[uuid.UUID][]time.Time +} + +func newEffectHandler(hook func(context.Context, pgx.Tx, outbound.ConsumedEvent) error) *effectHandler { + return &effectHandler{hook: hook, calls: make(map[uuid.UUID][]time.Time)} +} + +func (*effectHandler) ConsumerName() string { return consumerName } + +func (*effectHandler) Handles(eventType string) bool { return eventType == consumerEventType } + +func (handler *effectHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, event outbound.ConsumedEvent) error { + handler.mu.Lock() + handler.calls[event.EventID] = append(handler.calls[event.EventID], time.Now()) + handler.mu.Unlock() + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return errors.New("unit of work is not a PostgreSQL transaction") + } + if _, err := tx.Exec(ctx, "INSERT INTO "+effectsIdentifier.Sanitize()+" (event_id, consumer_name) VALUES ($1, $2)", event.EventID, consumerName); err != nil { + return err + } + if handler.hook == nil { + return nil + } + return handler.hook(ctx, tx, event) +} + +func (handler *effectHandler) callTimes(eventID uuid.UUID) []time.Time { + handler.mu.Lock() + defer handler.mu.Unlock() + return append([]time.Time(nil), handler.calls[eventID]...) +} + +func (handler *effectHandler) totalCalls() int { + handler.mu.Lock() + defer handler.mu.Unlock() + total := 0 + for _, calls := range handler.calls { + total += len(calls) + } + return total +} + +// consumerHarness owns the database side of consumer tests. +type consumerHarness struct { + env *testEnvironment + pool *pgxpool.Pool + store *postgresadapter.EventConsumerStore +} + +func TestEventConsumer(t *testing.T) { + env := bootstrap(t, postgresService, kafkaService) + ctx, cancel := context.WithTimeout(t.Context(), consumerTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + for _, statement := range []string{createEffectsTable, createTestAccountsTable} { + if _, err := pool.Exec(ctx, statement); err != nil { + t.Fatalf("create test-only tables: %v", err) + } + } + harness := &consumerHarness{ + env: env, + pool: pool, + store: postgresadapter.NewEventConsumerStore(pool, consumerHandlerTime), + } + // Subtests share tables and run sequentially; each starts from empty + // tables and uses its own topic and consumer group. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, + effectsIdentifier, + pgx.Identifier{"consumer_processed_events"}, + pgx.Identifier{"consumer_dead_letters"}, + outboxEventsTable, + testAccountsTable, + ) + } + + t.Run("an event delivered three times on two partitions is applied once", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 2) + repeated, other := newConsumerEnvelope(), newConsumerEnvelope() + producer := env.newKafkaClient(t, kgo.RecordPartitioner(kgo.ManualPartitioner())) + produceKafkaRecords(ctx, t, producer, + envelopeRecord(t, topic, 0, repeated), + envelopeRecord(t, topic, 1, repeated), + envelopeRecord(t, topic, 0, repeated), + envelopeRecord(t, topic, 1, other), + ) + handler := newEffectHandler(nil) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2, 1: 2}) + harness.assertEffects(ctx, t, repeated.EventID, 1) + harness.assertEffects(ctx, t, other.EventID, 1) + harness.assertMarkers(ctx, t, 2) + assertConsumerMetric(t, metrics, "records", "applied", 2) + assertConsumerMetric(t, metrics, "records", "duplicate", 2) + }) + + t.Run("two deliveries of one event racing on the marker apply it once", func(t *testing.T) { + reset(t) + record := consumedRecord(newConsumerEnvelope()) + inEffect := make(chan struct{}) + releaseFirst := make(chan struct{}) + first := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + close(inEffect) + return awaitOrCancel(ctx, releaseFirst, nil) + }) + second := newEffectHandler(nil) + firstSource, secondSource := newStaticSource(record), newStaticSource(record) + firstMetrics, secondMetrics := prometheus.New(), prometheus.New() + + runWithSource(ctx, t, firstSource, first, harness.store, firstMetrics, consumerTestSettings(consumerGrace)) + awaitSignal(ctx, t, inEffect, "the first delivery to hold its marker") + // The first transaction holds the uncommitted marker. The second + // delivery's marker insert must wait for it instead of running the + // effect in parallel. + racingPool := env.newPoolWithApplicationName(ctx, t, racingApplication) + runWithSource(ctx, t, secondSource, second, postgresadapter.NewEventConsumerStore(racingPool, consumerHandlerTime), secondMetrics, consumerTestSettings(consumerGrace)) + if waitEvent, waiting := waitForLockWait(ctx, pool, racingApplication); !waiting { + t.Fatalf("the second delivery did not wait for the first marker; last wait event %q", waitEvent) + } + close(releaseFirst) + + firstSource.waitForCommit(ctx, t) + secondSource.waitForCommit(ctx, t) + harness.assertEffects(ctx, t, record.EventID, 1) + if calls := len(second.callTimes(record.EventID)); calls != 0 { + t.Fatalf("the second delivery ran the handler %d times after the first committed", calls) + } + assertConsumerMetric(t, firstMetrics, "records", "applied", 1) + assertConsumerMetric(t, secondMetrics, "records", "duplicate", 1) + }) + + t.Run("when the first of two racing deliveries rolls back the second applies the event once", func(t *testing.T) { + reset(t) + record := consumedRecord(newConsumerEnvelope()) + inEffect := make(chan struct{}) + failFirst := make(chan struct{}) + var firstCalls atomic.Int64 + first := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + if firstCalls.Add(1) == 1 { + close(inEffect) + return awaitOrCancel(ctx, failFirst, errEffectFailed) + } + return nil + }) + second := newEffectHandler(nil) + firstSource, secondSource := newStaticSource(record), newStaticSource(record) + firstMetrics, secondMetrics := prometheus.New(), prometheus.New() + + // The first delivery retries only after the second one committed, + // with a margin of 100ms or more over a commit of one row. + firstSettings := consumerTestSettings(consumerGrace) + firstSettings.Backoff = retry.Backoff{Initial: consumerPoisonBackoff, Max: consumerPoisonBackoff} + runWithSource(ctx, t, firstSource, first, harness.store, firstMetrics, firstSettings) + awaitSignal(ctx, t, inEffect, "the first delivery to hold its marker") + racingPool := env.newPoolWithApplicationName(ctx, t, racingApplication) + runWithSource(ctx, t, secondSource, second, postgresadapter.NewEventConsumerStore(racingPool, consumerHandlerTime), secondMetrics, consumerTestSettings(consumerGrace)) + if waitEvent, waiting := waitForLockWait(ctx, pool, racingApplication); !waiting { + t.Fatalf("the second delivery did not wait for the first marker; last wait event %q", waitEvent) + } + close(failFirst) + + firstSource.waitForCommit(ctx, t) + secondSource.waitForCommit(ctx, t) + harness.assertEffects(ctx, t, record.EventID, 1) + // The second delivery applied the event after the rollback; the + // first one's retry then found the marker. + assertConsumerMetric(t, secondMetrics, "records", "applied", 1) + assertConsumerMetric(t, firstMetrics, "records", "duplicate", 1) + assertConsumerMetric(t, firstMetrics, "failures", "handler", 1) + }) + + t.Run("a consumer stopped before its commit leaves the record to its successor, which applies it once", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + group := newConsumerGroup() + + effectWritten := make(chan struct{}) + stuck := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + close(effectWritten) + // The effect row is written; the process now "dies" before the + // commit: the handler outlives the shutdown grace. + <-ctx.Done() + return ctx.Err() + }) + stop := harness.startConsumer(ctx, t, topic, group, stuck, prometheus.New(), consumerShortGrace) + awaitSignal(ctx, t, effectWritten, "the first consumer to reach the handler") + stop() + + harness.assertEffects(ctx, t, event.EventID, 0) + harness.assertMarkers(ctx, t, 0) + if offsets := env.committedOffsets(ctx, t, group, topic); len(offsets) != 0 { + t.Fatalf("the stopped consumer committed %v for unfinished work", offsets) + } + + successor := newEffectHandler(nil) + metrics := prometheus.New() + harness.startConsumer(ctx, t, topic, group, successor, metrics, consumerGrace) + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + harness.assertEffects(ctx, t, event.EventID, 1) + assertConsumerMetric(t, metrics, "records", "applied", 1) + }) + + t.Run("a record whose effect committed before a crash is a duplicate on redelivery", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + // The earlier instance committed the effect and the marker, then + // crashed before it committed the offset. + applied, err := harness.store.ApplyOnce(ctx, consumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return newEffectHandler(nil).Handle(ctx, unit, consumedRecord(event).Event) + }) + if err != nil || !applied { + t.Fatalf("ApplyOnce() = %t, %v; want the first application", applied, err) + } + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + handler := newEffectHandler(nil) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + harness.assertEffects(ctx, t, event.EventID, 1) + if calls := handler.totalCalls(); calls != 0 { + t.Fatalf("handler ran %d times for a redelivered event", calls) + } + assertConsumerMetric(t, metrics, "records", "duplicate", 1) + }) + + t.Run("an invalid record is dead-lettered once and later records on its partition are applied", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + headerID := uuid.New() + invalidValue := []byte(`{"envelope_version":1,"payload":"secret-value"`) + valid := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), + &kgo.Record{Topic: topic, Value: invalidValue, Headers: []kgo.RecordHeader{{Key: "event_id", Value: []byte(headerID.String())}}}, + envelopeRecord(t, topic, -1, valid), + ) + handler := newEffectHandler(nil) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, handler, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2}) + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 1 { + t.Fatalf("dead letters = %d, want 1", len(letters)) + } + assertDeadLetter(t, letters[0], deadLetterRow{ + topic: topic, partition: 0, offset: 0, eventID: &headerID, + errorClass: string(outbound.DeadLetterInvalidRecord), attempts: 0, + valueSize: len(invalidValue), valueSHA256: sha256.Sum256(invalidValue), + }) + if strings.Contains(letters[0].reason, "secret") { + t.Fatalf("dead letter reason quotes the value: %q", letters[0].reason) + } + harness.assertEffects(ctx, t, valid.EventID, 1) + if calls := handler.totalCalls(); calls != 1 { + t.Fatalf("handler ran %d times, want only for the valid record", calls) + } + assertConsumerMetric(t, metrics, "records", "dead_lettered", 1) + assertConsumerMetric(t, metrics, "records", "applied", 1) + // The dead letter is final: the consumer does not come back to it. + time.Sleep(consumerQuietPeriod) + if again := harness.readDeadLetters(ctx, t); len(again) != 1 { + t.Fatalf("dead letters = %d after the quiet period, want 1", len(again)) + } + }) + + t.Run("a handler that keeps failing is retried with backoff a bounded number of times, then dead-lettered", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + poison, next := newConsumerEnvelope(), newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, poison), envelopeRecord(t, topic, -1, next)) + handler := newEffectHandler(func(_ context.Context, _ pgx.Tx, event outbound.ConsumedEvent) error { + if event.EventID == poison.EventID { + // The effect row was written; the failure must roll it back. + return errEffectFailed + } + return nil + }) + metrics := prometheus.New() + group := newConsumerGroup() + settings := consumerTestSettings(consumerGrace) + settings.Backoff = retry.Backoff{Initial: consumerPoisonBackoff, Max: consumerPoisonBackoff} + harness.startConsumerWith(ctx, t, topic, group, handler, metrics, settings) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 2}) + calls := handler.callTimes(poison.EventID) + if len(calls) != consumerMaxAttempts { + t.Fatalf("poison event attempts = %d, want %d", len(calls), consumerMaxAttempts) + } + for index := 1; index < len(calls); index++ { + if gap := calls[index].Sub(calls[index-1]); gap < consumerPoisonMinimumGap { + t.Fatalf("attempt %d followed the previous one after %s, want at least %s", index+1, gap, consumerPoisonMinimumGap) + } + } + if spent := calls[len(calls)-1].Sub(calls[0]); spent > consumerPoisonBudget { + t.Fatalf("retries took %s, want at most %s", spent, consumerPoisonBudget) + } + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 1 { + t.Fatalf("dead letters = %d, want 1", len(letters)) + } + value := envelopeValue(t, poison) + eventType := consumerEventType + assertDeadLetter(t, letters[0], deadLetterRow{ + topic: topic, partition: 0, offset: 0, eventID: &poison.EventID, eventType: &eventType, + errorClass: string(outbound.DeadLetterRetriesExhausted), attempts: consumerMaxAttempts, + valueSize: len(value), valueSHA256: sha256.Sum256(value), + }) + if !strings.Contains(letters[0].reason, errEffectFailed.Error()) { + t.Fatalf("dead letter reason = %q, want the handler error", letters[0].reason) + } + harness.assertEffects(ctx, t, poison.EventID, 0) + harness.assertEffects(ctx, t, next.EventID, 1) + assertConsumerMetric(t, metrics, "failures", "handler", consumerMaxAttempts) + assertConsumerMetric(t, metrics, "records", "dead_lettered", 1) + // No hot loop: after the dead letter the handler is not called again. + time.Sleep(consumerQuietPeriod) + if again := len(handler.callTimes(poison.EventID)); again != consumerMaxAttempts { + t.Fatalf("poison event attempts grew to %d after the dead letter", again) + } + }) + + t.Run("a connection killed inside the handler rolls back on the server, and a new member applies the event once", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + group := newConsumerGroup() + + killed := make(chan struct{}) + var backendPID atomic.Int32 + crashing := newEffectHandler(func(ctx context.Context, tx pgx.Tx, _ outbound.ConsumedEvent) error { + // The effect row and the marker are written but not committed. + // Ending the backend is what a crashed process or a dropped + // connection leaves behind: only the server can roll back. + var pid int32 + if err := tx.QueryRow(ctx, "SELECT pg_backend_pid()").Scan(&pid); err != nil { + return err + } + backendPID.Store(pid) + var terminated bool + if err := pool.QueryRow(ctx, "SELECT pg_terminate_backend($1)", pid).Scan(&terminated); err != nil || !terminated { + return fmt.Errorf("terminate backend %d: %t, %w", pid, terminated, err) + } + close(killed) + <-ctx.Done() + return ctx.Err() + }) + stop := harness.startConsumer(ctx, t, topic, group, crashing, prometheus.New(), consumerShortGrace) + awaitSignal(ctx, t, killed, "the handler to end its own backend") + stop() + + waitFor(ctx, t, "the terminated backend to disappear", func() bool { + var alive bool + err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = $1)", backendPID.Load()).Scan(&alive) + return err == nil && !alive + }) + harness.assertEffects(ctx, t, event.EventID, 0) + harness.assertMarkers(ctx, t, 0) + if offsets := env.committedOffsets(ctx, t, group, topic); len(offsets) != 0 { + t.Fatalf("the crashed member committed %v", offsets) + } + + successor := newEffectHandler(nil) + metrics := prometheus.New() + harness.startConsumer(ctx, t, topic, group, successor, metrics, consumerGrace) + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + harness.assertEffects(ctx, t, event.EventID, 1) + assertConsumerMetric(t, metrics, "records", "applied", 1) + }) + + t.Run("a handler that ignores a failed statement ends in a dead letter instead of retrying forever", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, 1) + event := newConsumerEnvelope() + produceKafkaRecords(ctx, t, env.newKafkaClient(t), envelopeRecord(t, topic, -1, event)) + swallowing := newEffectHandler(func(ctx context.Context, tx pgx.Tx, _ outbound.ConsumedEvent) error { + // The failed statement aborts the transaction; the handler + // hides the error, so PostgreSQL refuses the commit. + _, _ = tx.Exec(ctx, "SELECT 1 / 0") + return nil + }) + metrics := prometheus.New() + group := newConsumerGroup() + harness.startConsumer(ctx, t, topic, group, swallowing, metrics, consumerGrace) + + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: 1}) + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 1 || letters[0].errorClass != string(outbound.DeadLetterRetriesExhausted) || letters[0].attempts != consumerMaxAttempts { + t.Fatalf("dead letters = %+v, want one retries_exhausted after %d attempts", letters, consumerMaxAttempts) + } + if calls := len(swallowing.callTimes(event.EventID)); calls != consumerMaxAttempts { + t.Fatalf("handler ran %d times, want %d", calls, consumerMaxAttempts) + } + harness.assertEffects(ctx, t, event.EventID, 0) + harness.assertMarkers(ctx, t, 0) + assertConsumerMetric(t, metrics, "failures", "handler", consumerMaxAttempts) + assertConsumerMetric(t, metrics, "failures", "store", 0) + }) + + t.Run("a repeated dead letter updates its row, and another value at the same position gets its own", func(t *testing.T) { + reset(t) + letter := outbound.DeadLetter{ + Consumer: consumerName, Topic: "integration-dead-letters", Partition: 1, Offset: 7, + EventID: uuid.New(), EventType: consumerEventType, ErrorClass: outbound.DeadLetterHandlerRejected, + Reason: "first failure", Attempts: 1, ValueSize: 3, ValueSHA256: sha256.Sum256([]byte("one")), + } + if err := harness.store.RecordDeadLetter(ctx, letter); err != nil { + t.Fatalf("RecordDeadLetter() error = %v", err) + } + // After a rewind the same record fails again, differently. + again := letter + again.ErrorClass, again.Reason, again.Attempts = outbound.DeadLetterRetriesExhausted, "second failure", consumerMaxAttempts + if err := harness.store.RecordDeadLetter(ctx, again); err != nil { + t.Fatalf("RecordDeadLetter() again error = %v", err) + } + // A recreated topic reuses the position for another record. + other := letter + other.EventID, other.ValueSHA256 = uuid.New(), sha256.Sum256([]byte("two")) + if err := harness.store.RecordDeadLetter(ctx, other); err != nil { + t.Fatalf("RecordDeadLetter() other error = %v", err) + } + + letters := harness.readDeadLetters(ctx, t) + if len(letters) != 2 { + t.Fatalf("dead letters = %d, want 2", len(letters)) + } + if letters[0].errorClass != string(outbound.DeadLetterRetriesExhausted) || letters[0].reason != "second failure" || + letters[0].attempts != consumerMaxAttempts || letters[0].valueSHA256 != letter.ValueSHA256 { + t.Fatalf("repeated dead letter = %+v, want the second outcome", letters[0]) + } + if letters[1].valueSHA256 != other.ValueSHA256 || *letters[1].eventID != other.EventID { + t.Fatalf("dead letter of the other value = %+v", letters[1]) + } + }) + + t.Run("a member joining while another holds a record takes over without a lost or repeated effect", func(t *testing.T) { + reset(t) + harness.runRebalanceHandover(ctx, t) + }) + + t.Run("an event appended to the outbox reaches the consumer through the relay", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + relayHarness := &relayHarness{ + env: env, + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts), + } + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + relayHarness.save(ctx, t, account, event) + relay := relayHarness.newRelay(relayHarness.newPublisher(t, topic)) + if result, err := relay.PublishPending(ctx); err != nil || result.Published != 1 { + t.Fatalf("PublishPending() = %+v, %v; want one event published", result, err) + } + + var received atomic.Pointer[outbound.ConsumedEvent] + handler := accountHandler{received: &received} + metrics := prometheus.New() + group := newConsumerGroup() + source, _ := harness.newSource(t, topic, group) + consumer, err := eventconsumer.New(handler, source, harness.store, metrics, slog.New(slog.DiscardHandler), consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, consumer) + + waitFor(ctx, t, "the relayed event to be applied", func() bool { return received.Load() != nil }) + got := received.Load() + if got.EventID != event.EventID() || got.AggregateID != account.id || got.AggregateVersion != account.version || + got.EventType != testAccountEventType || got.AggregateType != testAggregateType { + t.Fatalf("consumed event %+v does not match the outbox event %s", got, event.EventID()) + } + assertJSONEqual(t, got.Payload, accountPayload(account)) + }) +} + +// accountHandler records the account event it consumed. +type accountHandler struct { + received *atomic.Pointer[outbound.ConsumedEvent] +} + +func (accountHandler) ConsumerName() string { return "integration_relay_check" } + +func (accountHandler) Handles(eventType string) bool { return eventType == testAccountEventType } + +func (handler accountHandler) Handle(_ context.Context, _ outbound.UnitOfWork, event outbound.ConsumedEvent) error { + handler.received.Store(&event) + return nil +} + +func consumerTestSettings(grace time.Duration) eventconsumer.Settings { + return eventconsumer.Settings{ + MaxAttempts: consumerMaxAttempts, + Backoff: retry.Backoff{Initial: consumerShortBackoff, Max: consumerShortBackoff}, + HandlerTimeout: consumerHandlerTime, + CommitTimeout: consumerCommitTimeout, + ShutdownGrace: grace, + } +} + +func newConsumerGroup() string { + return "integration-consumer-" + strings.ToLower(rand.Text()) +} + +// newSource creates a group member for topic. close leaves the group; it +// also runs when t finishes, after the consumer stopped. +func (harness *consumerHarness) newSource(t *testing.T, topic, group string) (source *kafka.EventSource, closeOnce func()) { + t.Helper() + settings := harness.env.Config + settings.KafkaEventsTopic = topic + settings.ConsumerCommitTimeout = consumerCommitTimeout + source, closeSource, err := kafka.NewEventSource(settings, group, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewEventSource() error = %v", err) + } + var once sync.Once + closeOnce = func() { once.Do(closeSource) } + t.Cleanup(closeOnce) + return source, closeOnce +} + +func (harness *consumerHarness) startConsumer( + ctx context.Context, + t *testing.T, + topic, group string, + handler *effectHandler, + metrics *prometheus.Metrics, + grace time.Duration, +) (stop func()) { + t.Helper() + return harness.startConsumerWith(ctx, t, topic, group, handler, metrics, consumerTestSettings(grace)) +} + +// startConsumerWith runs a consumer of topic in group. stop cancels it, +// waits until Run returned, and then leaves the group, as bootstrap does. +func (harness *consumerHarness) startConsumerWith( + ctx context.Context, + t *testing.T, + topic, group string, + handler *effectHandler, + metrics *prometheus.Metrics, + settings eventconsumer.Settings, +) (stop func()) { + t.Helper() + source, closeSource := harness.newSource(t, topic, group) + consumer, err := eventconsumer.New(handler, source, harness.store, metrics, slog.New(slog.DiscardHandler), settings) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + stopRun := runConsumer(ctx, t, consumer) + return func() { + t.Helper() + stopRun() + closeSource() + } +} + +// runWithSource runs a consumer of a static source with store. +func runWithSource( + ctx context.Context, + t *testing.T, + source *staticSource, + handler *effectHandler, + store outbound.EventConsumerStore, + metrics *prometheus.Metrics, + settings eventconsumer.Settings, +) { + t.Helper() + consumer, err := eventconsumer.New(handler, source, store, metrics, slog.New(slog.DiscardHandler), settings) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, consumer) +} + +// runConsumer runs consumer until the returned stop or the end of t. +func runConsumer(ctx context.Context, t *testing.T, consumer *eventconsumer.Consumer) (stop func()) { + t.Helper() + runCtx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + go func() { + defer close(done) + consumer.Run(runCtx) + }() + var once sync.Once + stop = func() { + once.Do(func() { + cancel() + select { + case <-done: + case <-time.After(consumerStopTimeout): + t.Errorf("consumer %s did not stop within %s", consumer.Name(), consumerStopTimeout) + } + }) + } + t.Cleanup(stop) + return stop +} + +// staticSource delivers one batch, then waits for ctx, and records the +// committed offsets. It stands in for Kafka where a test needs two +// consumers to receive the same record at a moment it controls. +type staticSource struct { + mu sync.Mutex + batch []outbound.ConsumedRecord + committed []int64 + commitSeen chan struct{} +} + +func newStaticSource(records ...outbound.ConsumedRecord) *staticSource { + return &staticSource{batch: records, commitSeen: make(chan struct{})} +} + +func (source *staticSource) Poll(ctx context.Context) ([]outbound.ConsumedRecord, error) { + source.mu.Lock() + batch := source.batch + source.batch = nil + source.mu.Unlock() + if len(batch) > 0 { + return batch, nil + } + <-ctx.Done() + return nil, ctx.Err() +} + +func (source *staticSource) Commit(_ context.Context, finished []outbound.ConsumedRecord) error { + source.mu.Lock() + defer source.mu.Unlock() + for _, record := range finished { + source.committed = append(source.committed, record.Offset) + } + select { + case <-source.commitSeen: + default: + close(source.commitSeen) + } + return nil +} + +func (*staticSource) Release() {} + +func (source *staticSource) waitForCommit(ctx context.Context, t *testing.T) { + t.Helper() + select { + case <-source.commitSeen: + case <-ctx.Done(): + t.Fatal("the consumer did not commit its record") + case <-time.After(consumerWaitTimeout): + t.Fatal("the consumer did not commit its record") + } +} + +func newConsumerEnvelope() receivedEnvelope { + return receivedEnvelope{ + EnvelopeVersion: kafka.EnvelopeVersion, + EventID: uuid.New(), + EventType: consumerEventType, + SchemaVersion: 1, + AggregateType: consumerAggregate, + AggregateID: uuid.New(), + AggregateVersion: 1, + OccurredAt: time.Now().UTC(), + Payload: json.RawMessage(`{"step":1}`), + } +} + +func envelopeValue(t *testing.T, envelope receivedEnvelope) []byte { + t.Helper() + value, err := json.Marshal(envelope) + if err != nil { + t.Fatalf("encode envelope: %v", err) + } + return value +} + +// envelopeRecord builds a record as the relay writes it. A negative +// partition leaves the choice to the producer's partitioner. +func envelopeRecord(t *testing.T, topic string, partition int32, envelope receivedEnvelope) *kgo.Record { + t.Helper() + record := &kgo.Record{ + Topic: topic, + // A distinct key per record lets a duplicate land on another + // partition, as a manual partitioner sends it. + Key: []byte(envelope.AggregateType + ":" + envelope.AggregateID.String()), + Value: envelopeValue(t, envelope), + Headers: []kgo.RecordHeader{ + {Key: "event_id", Value: []byte(envelope.EventID.String())}, + {Key: "event_type", Value: []byte(envelope.EventType)}, + {Key: "schema_version", Value: []byte(strconv.Itoa(int(envelope.SchemaVersion)))}, + }, + } + if partition >= 0 { + record.Partition = partition + } + return record +} + +// consumedRecord is the decoded form of envelope at offset 0. +func consumedRecord(envelope receivedEnvelope) outbound.ConsumedRecord { + return outbound.ConsumedRecord{ + Topic: "static", + EventID: envelope.EventID, + Event: outbound.ConsumedEvent{ + EventID: envelope.EventID, + EventType: envelope.EventType, + SchemaVersion: envelope.SchemaVersion, + AggregateType: envelope.AggregateType, + AggregateID: envelope.AggregateID, + AggregateVersion: envelope.AggregateVersion, + OccurredAt: envelope.OccurredAt, + Payload: envelope.Payload, + }, + } +} + +// committedOffsets returns the committed offsets of group on topic. The +// coordinator of a new group can be unavailable for a moment while Kafka +// creates the offsets topic, so it retries retriable errors. +func (env *testEnvironment) committedOffsets(ctx context.Context, t *testing.T, group, topic string) map[int32]int64 { + t.Helper() + var offsets map[int32]int64 + var lastErr error + waitFor(ctx, t, "the offsets of group "+group, func() bool { + offsets, lastErr = env.fetchCommittedOffsets(ctx, group, topic) + if lastErr != nil && !kerr.IsRetriable(lastErr) { + t.Fatalf("fetch offsets of group %s: %v", group, lastErr) + } + return lastErr == nil + }) + return offsets +} + +func (env *testEnvironment) fetchCommittedOffsets(ctx context.Context, group, topic string) (map[int32]int64, error) { + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + offsets := make(map[int32]int64) + responses, err := env.KafkaAdmin.FetchOffsets(ctx, group) + if errors.Is(err, kerr.GroupIDNotFound) { + return offsets, nil + } + if err != nil { + return nil, err + } + responses.Each(func(response kadm.OffsetResponse) { + if response.Topic == topic && response.Err == nil && response.At >= 0 { + offsets[response.Partition] = response.At + } + }) + return offsets, nil +} + +func (env *testEnvironment) waitForCommittedOffsets(ctx context.Context, t *testing.T, group, topic string, want map[int32]int64) { + t.Helper() + waitFor(ctx, t, fmt.Sprintf("group %s to commit %v", group, want), func() bool { + got, err := env.fetchCommittedOffsets(ctx, group, topic) + if err != nil && !kerr.IsRetriable(err) { + t.Fatalf("fetch offsets of group %s: %v", group, err) + } + return err == nil && maps.Equal(got, want) + }) +} + +// waitFor polls condition until it holds or consumerWaitTimeout passes. +func waitFor(ctx context.Context, t *testing.T, what string, condition func() bool) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, consumerWaitTimeout) + defer cancel() + ticker := time.NewTicker(readinessInterval) + defer ticker.Stop() + for !condition() { + select { + case <-ctx.Done(): + t.Fatalf("timed out waiting for %s", what) + case <-ticker.C: + } + } +} + +func (env *testEnvironment) newPoolWithApplicationName(ctx context.Context, t *testing.T, name string) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.ConnConfig.RuntimeParams["application_name"] = name + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create PostgreSQL pool %s: %v", name, err) + } + t.Cleanup(pool.Close) + return pool +} + +func (harness *consumerHarness) assertEffects(ctx context.Context, t *testing.T, eventID uuid.UUID, want int) { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+effectsIdentifier.Sanitize()+" WHERE event_id = $1", eventID).Scan(&count); err != nil { + t.Fatalf("count effects: %v", err) + } + if count != want { + t.Fatalf("event %s has %d effect rows, want %d", eventID, count, want) + } +} + +func (harness *consumerHarness) assertMarkers(ctx context.Context, t *testing.T, want int) { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consumer_processed_events WHERE consumer_name = $1", consumerName).Scan(&count); err != nil { + t.Fatalf("count processed event markers: %v", err) + } + if count != want { + t.Fatalf("processed event markers = %d, want %d", count, want) + } +} + +type deadLetterRow struct { + consumer string + topic string + partition int32 + offset int64 + eventID *uuid.UUID + eventType *string + errorClass string + reason string + attempts int + valueSize int + valueSHA256 [32]byte +} + +func (harness *consumerHarness) readDeadLetters(ctx context.Context, t *testing.T) []deadLetterRow { + t.Helper() + rows, err := harness.pool.Query(ctx, ` + SELECT consumer_name, topic, kafka_partition, kafka_offset, event_id, event_type, + error_class, reason, attempts, value_size, value_sha256 + FROM consumer_dead_letters ORDER BY id`) + if err != nil { + t.Fatalf("read dead letters: %v", err) + } + letters, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (deadLetterRow, error) { + var letter deadLetterRow + var digest []byte + err := row.Scan(&letter.consumer, &letter.topic, &letter.partition, &letter.offset, &letter.eventID, &letter.eventType, + &letter.errorClass, &letter.reason, &letter.attempts, &letter.valueSize, &digest) + copy(letter.valueSHA256[:], digest) + return letter, err + }) + if err != nil { + t.Fatalf("scan dead letters: %v", err) + } + return letters +} + +func assertDeadLetter(t *testing.T, got, want deadLetterRow) { + t.Helper() + sameID := (got.eventID == nil) == (want.eventID == nil) && (got.eventID == nil || *got.eventID == *want.eventID) + sameType := (got.eventType == nil) == (want.eventType == nil) && (got.eventType == nil || *got.eventType == *want.eventType) + if got.consumer != consumerName || got.topic != want.topic || got.partition != want.partition || got.offset != want.offset || + !sameID || !sameType || got.errorClass != want.errorClass || got.attempts != want.attempts || + got.valueSize != want.valueSize || got.valueSHA256 != want.valueSHA256 || got.reason == "" { + t.Fatalf("dead letter %+v, want %+v", got, want) + } +} + +// assertConsumerMetric reads lincodex_event_consumer__total for the +// test consumer and one outcome or stage label from the scrape output. +func assertConsumerMetric(t *testing.T, metrics *prometheus.Metrics, kind, label string, want int) { + t.Helper() + labelName := map[string]string{"records": "outcome", "failures": "stage"}[kind] + response := httptest.NewRecorder() + metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + prefix := fmt.Sprintf(`lincodex_event_consumer_%s_total{consumer=%q,%s=%q} `, kind, consumerName, labelName, label) + for line := range strings.SplitSeq(response.Body.String(), "\n") { + if value, found := strings.CutPrefix(line, prefix); found { + if value != strconv.Itoa(want) { + t.Fatalf("%s%s, want %d", prefix, value, want) + } + return + } + } + t.Fatalf("metrics output has no series %s", prefix) +} + +// awaitOrCancel waits for release inside a handler and returns result, or the +// context error when the attempt ends first, so a failed test never leaves a +// handler blocked. +func awaitOrCancel(ctx context.Context, release <-chan struct{}, result error) error { + select { + case <-release: + return result + case <-ctx.Done(): + return ctx.Err() + } +} + +// awaitSignal waits for signal within consumerWaitTimeout. +func awaitSignal(ctx context.Context, t *testing.T, signal <-chan struct{}, what string) { + t.Helper() + select { + case <-signal: + case <-ctx.Done(): + t.Fatalf("test ended while waiting for %s", what) + case <-time.After(consumerWaitTimeout): + t.Fatalf("timed out waiting for %s", what) + } +} + +// failingCommits makes every offset commit of one member fail, as a +// coordinator that keeps rejecting commits would. The member's finished +// positions then stay pending, and only the revocation of a partition can +// commit them. It records the offsets the member tried to commit. +type failingCommits struct { + *kafka.EventSource + + succeeded atomic.Int64 + mu sync.Mutex + attempted map[int32][]int64 +} + +func (source *failingCommits) Commit(ctx context.Context, finished []outbound.ConsumedRecord) error { + source.mu.Lock() + for _, record := range finished { + source.attempted[record.Partition] = append(source.attempted[record.Partition], record.Offset) + } + source.mu.Unlock() + canceled, cancel := context.WithCancel(ctx) + cancel() + err := source.EventSource.Commit(canceled, finished) + if err == nil { + source.succeeded.Add(1) + } + return err +} + +func (source *failingCommits) attemptedOffsets(partition int32) []int64 { + source.mu.Lock() + defer source.mu.Unlock() + return append([]int64(nil), source.attempted[partition]...) +} + +// runRebalanceHandover lets a second member join a group while the first one +// holds a record, so the rebalance has to wait for it. The first member's +// commits fail, so the position of the partition it gives up reaches Kafka +// only through the commit in its revocation. +func (harness *consumerHarness) runRebalanceHandover(ctx context.Context, t *testing.T) { + t.Helper() + env := harness.env + logger := slog.New(slog.DiscardHandler) + topic := env.createKafkaTopic(ctx, t, 2) + group := newConsumerGroup() + producer := env.newKafkaClient(t, kgo.RecordPartitioner(kgo.ManualPartitioner())) + first := [2]receivedEnvelope{newConsumerEnvelope(), newConsumerEnvelope()} + produceKafkaRecords(ctx, t, producer, envelopeRecord(t, topic, 0, first[0]), envelopeRecord(t, topic, 1, first[1])) + + held, release := make(chan struct{}), make(chan struct{}) + var holding sync.Once + holder := newEffectHandler(func(ctx context.Context, _ pgx.Tx, _ outbound.ConsumedEvent) error { + hold := false + holding.Do(func() { hold = true }) + if !hold { + return nil + } + close(held) + return awaitOrCancel(ctx, release, nil) + }) + holderSource, closeHolder := harness.newSource(t, topic, group) + failing := &failingCommits{EventSource: holderSource, attempted: make(map[int32][]int64)} + holderConsumer, err := eventconsumer.New(holder, failing, harness.store, prometheus.New(), logger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + stopHolder := runConsumer(ctx, t, holderConsumer) + awaitSignal(ctx, t, held, "the first member to hold a record") + + joiner := newEffectHandler(nil) + joinerSource, _ := harness.newSource(t, topic, group) + joinerMetrics := prometheus.New() + joinerConsumer, err := eventconsumer.New(joiner, joinerSource, harness.store, joinerMetrics, logger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New() error = %v", err) + } + runConsumer(ctx, t, joinerConsumer) + // The join starts a rebalance that cannot finish while the first member + // holds its polled records. + env.waitForGroupState(ctx, t, group, "PreparingRebalance") + close(release) + // Cooperative rebalancing first revokes the partition that moves, then + // assigns it to the joiner in a second round. + env.waitForBalancedGroup(ctx, t, group, 2) + + // After the handover each member owns one partition. One new event per + // partition shows which partition moved. + second := [2]receivedEnvelope{newConsumerEnvelope(), newConsumerEnvelope()} + produceKafkaRecords(ctx, t, producer, envelopeRecord(t, topic, 0, second[0]), envelopeRecord(t, topic, 1, second[1])) + all := []receivedEnvelope{first[0], first[1], second[0], second[1]} + waitFor(ctx, t, "every event to be applied", func() bool { + for _, event := range all { + if harness.countEffects(ctx, t, event.EventID) == 0 { + return false + } + } + return true + }) + moved := int32(-1) + for partition := range int32(2) { + if len(joiner.callTimes(second[partition].EventID)) > 0 { + moved = partition + } + } + if moved < 0 { + t.Fatal("the joining member applied no event, so no partition moved") + } + kept := 1 - moved + + for _, event := range all { + harness.assertEffects(ctx, t, event.EventID, 1) + } + for partition := range int32(2) { + if calls := len(holder.callTimes(first[partition].EventID)); calls != 1 { + t.Fatalf("the first member handled the first event of partition %d %d times, want once before the rebalance", partition, calls) + } + } + if failing.succeeded.Load() != 0 { + t.Fatal("a commit of the first member succeeded, so the revocation path was not needed") + } + // The moved partition's position was committed in the revocation: the + // joiner started after the first event instead of receiving it again. + if calls := len(joiner.callTimes(first[moved].EventID)); calls != 0 { + t.Fatalf("the joiner applied the moved partition's first event %d times", calls) + } + assertConsumerMetric(t, joinerMetrics, "records", "duplicate", 0) + // No commit for the moved partition came from the first member after it + // lost the partition. + if offsets := failing.attemptedOffsets(moved); len(offsets) != 1 || offsets[0] != 0 { + t.Fatalf("the first member tried to commit offsets %v of the moved partition %d, want only 0", offsets, moved) + } + if calls := len(holder.callTimes(second[moved].EventID)); calls != 0 { + t.Fatalf("the first member handled the moved partition's second event %d times", calls) + } + waitFor(ctx, t, "the joiner to commit the moved partition", func() bool { + offsets, err := env.fetchCommittedOffsets(ctx, group, topic) + return err == nil && offsets[moved] == 2 + }) + + // Leaving the group revokes the kept partition, and the revocation + // commits its pending position; the moved partition is not rewound. + stopHolder() + closeHolder() + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{moved: 2, kept: 2}) + assertConsumerMetric(t, joinerMetrics, "records", "duplicate", 0) +} + +func (env *testEnvironment) waitForGroupState(ctx context.Context, t *testing.T, group, state string) { + t.Helper() + last := "" + waitFor(ctx, t, "group "+group+" to reach state "+state, func() bool { + requestCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + described, err := env.KafkaAdmin.DescribeGroups(requestCtx, group) + if err != nil { + return false + } + if detail, ok := described[group]; ok && detail.Err == nil { + last = detail.State + } + return last == state + }) +} + +func (harness *consumerHarness) countEffects(ctx context.Context, t *testing.T, eventID uuid.UUID) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+effectsIdentifier.Sanitize()+" WHERE event_id = $1", eventID).Scan(&count); err != nil { + t.Fatalf("count effects: %v", err) + } + return count +} + +// waitForBalancedGroup waits until group is stable with members members that +// each own at least one partition. +func (env *testEnvironment) waitForBalancedGroup(ctx context.Context, t *testing.T, group string, members int) { + t.Helper() + waitFor(ctx, t, fmt.Sprintf("group %s to give each of %d members a partition", group, members), func() bool { + requestCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + described, err := env.KafkaAdmin.DescribeGroups(requestCtx, group) + if err != nil { + return false + } + detail, ok := described[group] + if !ok || detail.Err != nil || detail.State != "Stable" || len(detail.Members) != members { + return false + } + for _, member := range detail.Members { + assignment, ok := member.Assigned.AsConsumer() + if !ok || len(assignment.Topics) == 0 || len(assignment.Topics[0].Partitions) == 0 { + return false + } + } + return true + }) +} diff --git a/backend/integration_test/files_store_test.go b/backend/integration_test/files_store_test.go new file mode 100644 index 0000000..87042fa --- /dev/null +++ b/backend/integration_test/files_store_test.go @@ -0,0 +1,275 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "io" + "mime/multipart" + "net/http" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + + "lincodex/backend/config" + "lincodex/backend/internal/usecase/files" +) + +const ( + syntheticFileLimit = 1 << 20 + // streamIterations exceeds the adapter's per-host connection limit, so a + // leaked response body would block a later Open until it times out. + streamIterations = 50 + streamLoopTimeout = 20 * time.Second +) + +func TestPrivateFileStoreAgainstSeaweedFS(t *testing.T) { + env := bootstrap(t, seaweedfsService) + ctx := t.Context() + store := files.NewStore(env.SeaweedFS) + policy := newFilePolicy(t, files.NamespaceResume) + payload := bytes.Repeat([]byte("%PDF-1.7 synthetic test document\n"), 8<<10) + digest := sha256.Sum256(payload) + + record, err := store.Put(ctx, policy, files.Upload{ + // Hide Seek so the upload streams like an HTTP request body. + Body: struct{ io.Reader }{bytes.NewReader(payload)}, Size: int64(len(payload)), + ContentType: "application/pdf", OriginalName: "../Synthetic CV.pdf", + }) + if err != nil { + t.Fatalf("upload synthetic file: %v", err) + } + if record.SHA256 != hex.EncodeToString(digest[:]) || record.Size != int64(len(payload)) || record.OriginalName != "Synthetic CV.pdf" { + t.Fatalf("record differs: %+v", record) + } + + t.Run("write and read through the adapter", func(t *testing.T) { + assertStoredFile(ctx, t, store, policy, record.Key, payload) + empty, err := store.Put(ctx, policy, files.Upload{Body: bytes.NewReader(nil), ContentType: "application/pdf"}) + if err != nil { + t.Fatalf("upload empty file: %v", err) + } + assertStoredFile(ctx, t, store, policy, empty.Key, nil) + }) + t.Run("anonymous access is refused", func(t *testing.T) { + objectURL := env.Config.SeaweedFSEndpoint + "/" + env.Config.SeaweedFSBucket + "/" + record.Key + filer := env.seaweedfsInternalEndpoint(ctx, t, seaweedfsFilerPort) + master := env.seaweedfsInternalEndpoint(ctx, t, seaweedfsMasterPort) + for _, probe := range []struct { + name, method, url string + status int + }{ + {name: "S3 object", method: http.MethodGet, url: objectURL, status: http.StatusForbidden}, + {name: "S3 object with presign-like query", method: http.MethodGet, url: objectURL + "?X-Amz-Algorithm=AWS4-HMAC-SHA256", status: http.StatusForbidden}, + {name: "S3 bucket listing", method: http.MethodGet, url: env.Config.SeaweedFSEndpoint + "/" + env.Config.SeaweedFSBucket, status: http.StatusForbidden}, + {name: "S3 upload", method: http.MethodPut, url: objectURL + "-anonymous", status: http.StatusForbidden}, + {name: "S3 deletion", method: http.MethodDelete, url: objectURL, status: http.StatusForbidden}, + {name: "filer object", method: http.MethodGet, url: filer + "/buckets/" + env.Config.SeaweedFSBucket + "/" + record.Key, status: http.StatusUnauthorized}, + {name: "filer listing", method: http.MethodGet, url: filer + "/buckets/" + env.Config.SeaweedFSBucket + "/", status: http.StatusUnauthorized}, + {name: "filer upload", method: http.MethodPut, url: filer + "/buckets/" + env.Config.SeaweedFSBucket + "/anonymous", status: http.StatusUnauthorized}, + {name: "master volume assignment", method: http.MethodGet, url: master + "/dir/assign", status: http.StatusUnauthorized}, + {name: "master collection deletion", method: http.MethodGet, url: master + "/col/delete?collection=" + env.Config.SeaweedFSBucket, status: http.StatusUnauthorized}, + } { + t.Run(probe.name, func(t *testing.T) { + status, body := unsignedRequest(ctx, t, probe.method, probe.url) + if status != probe.status || bytes.Contains(body, payload[:64]) { + t.Fatalf("unsigned %s returned HTTP %d, want %d", probe.method, status, probe.status) + } + }) + } + assertStoredFile(ctx, t, store, policy, record.Key, payload) + if _, err := store.Open(ctx, policy, record.Key+"-anonymous"); !errors.Is(err, files.ErrInvalidKey) { + t.Fatalf("anonymous key was accepted: %v", err) + } + }) + t.Run("volume refuses callers outside the container", func(t *testing.T) { + // The master hands out a signed write token with every assignment. The + // volume whitelist must refuse it from any other address, and reads + // need a token that never leaves the container. + fid, token := env.assignSeaweedFSVolume(ctx, t) + volume := env.seaweedfsInternalEndpoint(ctx, t, seaweedfsVolumePort) + "/" + fid + if status, _ := unsignedRequest(ctx, t, http.MethodGet, volume); status != http.StatusUnauthorized { + t.Fatalf("volume read without a token returned HTTP %d", status) + } + if status := volumeUpload(ctx, t, volume, token); status != http.StatusUnauthorized { + t.Fatalf("volume write with the assigned token returned HTTP %d", status) + } + }) + t.Run("wrong secret is refused", func(t *testing.T) { + other := env.Config + other.SeaweedFSSecretKey = "wrong-secret" + unauthorized := files.NewStore(env.newStorage(t, other)) + if _, err := unauthorized.Open(ctx, policy, record.Key); err == nil || errors.Is(err, files.ErrNotFound) { + t.Fatalf("wrong secret opened a file or looked like absence: %v", err) + } + if _, err := unauthorized.Put(ctx, policy, files.Upload{Body: strings.NewReader("no"), Size: 2, ContentType: "application/pdf"}); err == nil { + t.Fatal("wrong secret uploaded a file") + } + if err := unauthorized.Delete(ctx, policy, record.Key); err == nil { + t.Fatal("wrong secret deleted a file") + } + assertStoredFile(ctx, t, store, policy, record.Key, payload) + }) + t.Run("streams are closed", func(t *testing.T) { + // The adapter timeout would eventually release a leaked body, so this + // store waits much longer than the whole loop may take. + patient := env.Config + patient.SeaweedFSTimeout = time.Hour + patientStore := files.NewStore(env.newStorage(t, patient)) + loopCtx, cancel := context.WithTimeout(ctx, streamLoopTimeout) + defer cancel() + for range streamIterations { + file, err := patientStore.Open(loopCtx, policy, record.Key) + if err != nil { + t.Fatalf("open after earlier closes: %v", err) + } + if _, err := io.ReadFull(file, make([]byte, 1)); err != nil { + t.Fatal(err) + } + if err := file.Close(); err != nil { + t.Fatal(err) + } + if _, err := file.Read(make([]byte, 1)); err == nil { + t.Fatal("read after close succeeded") + } + } + }) + t.Run("size limits abort and leave no object", func(t *testing.T) { + limited := newFilePolicy(t, files.NamespaceProfilePDF) + oversized := bytes.Repeat([]byte("x"), syntheticFileLimit+1) + for _, test := range []struct { + name string + upload files.Upload + want error + }{ + {name: "declared over limit", upload: files.Upload{Body: bytes.NewReader(oversized), Size: int64(len(oversized))}, want: files.ErrTooLarge}, + {name: "stream past limit", upload: files.Upload{Body: bytes.NewReader(oversized), Size: syntheticFileLimit}, want: files.ErrTooLarge}, + {name: "stream past declared size", upload: files.Upload{Body: strings.NewReader("0123456789"), Size: 4}, want: files.ErrTooLarge}, + {name: "stream shorter than declared", upload: files.Upload{Body: strings.NewReader("0123"), Size: 10}, want: files.ErrSizeMismatch}, + } { + t.Run(test.name, func(t *testing.T) { + test.upload.ContentType = "application/pdf" + test.upload.Body = struct{ io.Reader }{test.upload.Body} + if _, err := store.Put(ctx, limited, test.upload); !errors.Is(err, test.want) { + t.Fatalf("error = %v, want %v", err, test.want) + } + }) + } + if keys := listKeys(ctx, t, env.Config, string(files.NamespaceProfilePDF)+"/"); len(keys) != 0 { + t.Fatalf("rejected uploads left %d objects", len(keys)) + } + }) + t.Run("delete then not found", func(t *testing.T) { + if err := store.Delete(ctx, policy, record.Key); err != nil { + t.Fatal(err) + } + if err := store.Delete(ctx, policy, record.Key); err != nil { + t.Fatalf("repeated deletion: %v", err) + } + if _, err := store.Open(ctx, policy, record.Key); !errors.Is(err, files.ErrNotFound) { + t.Fatalf("deleted file: %v", err) + } + }) +} + +func newFilePolicy(t *testing.T, namespace files.Namespace) files.Policy { + t.Helper() + policy, err := files.NewPolicy(namespace, syntheticFileLimit, "application/pdf") + if err != nil { + t.Fatal(err) + } + return policy +} + +func assertStoredFile(ctx context.Context, t *testing.T, store *files.Store, policy files.Policy, key string, want []byte) { + t.Helper() + file, err := store.Open(ctx, policy, key) + if err != nil { + t.Fatal(err) + } + defer file.Close() + data, err := io.ReadAll(file) + if err != nil || !bytes.Equal(data, want) || file.Size != int64(len(want)) || file.ContentType != "application/pdf" { + t.Fatalf("stored file differs: size=%d type=%q error=%v", file.Size, file.ContentType, err) + } +} + +func unsignedRequest(ctx context.Context, t *testing.T, method, url string) (int, []byte) { + t.Helper() + request, err := http.NewRequestWithContext(ctx, method, url, strings.NewReader("anonymous")) + if err != nil { + t.Fatal(err) + } + client := &http.Client{Timeout: storageTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + response, err := client.Do(request) + if err != nil { + t.Fatalf("unsigned request: %v", err) + } + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil { + t.Fatalf("read unsigned response: %v", err) + } + return response.StatusCode, body +} + +func volumeUpload(ctx context.Context, t *testing.T, url, token string) int { + t.Helper() + var body bytes.Buffer + form := multipart.NewWriter(&body) + part, err := form.CreateFormFile("file", "synthetic.txt") + if err != nil { + t.Fatal(err) + } + if _, err := part.Write([]byte("synthetic")); err != nil { + t.Fatal(err) + } + if err := form.Close(); err != nil { + t.Fatal(err) + } + request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &body) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Content-Type", form.FormDataContentType()) + request.Header.Set("Authorization", token) + response, err := (&http.Client{Timeout: storageTimeout}).Do(request) + if err != nil { + t.Fatalf("volume upload: %v", err) + } + defer response.Body.Close() + _, _ = io.Copy(io.Discard, response.Body) + return response.StatusCode +} + +// listKeys uses a separate signed client to see objects the store never +// returned, such as a partial write under a key the caller did not learn. +func listKeys(ctx context.Context, t *testing.T, settings config.Config, prefix string) []string { + t.Helper() + client := s3.New(s3.Options{ + Region: settings.SeaweedFSRegion, + BaseEndpoint: aws.String(settings.SeaweedFSEndpoint), + UsePathStyle: true, + Credentials: credentials.NewStaticCredentialsProvider(settings.SeaweedFSAccessKey, settings.SeaweedFSSecretKey, ""), + }) + output, err := client.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(settings.SeaweedFSBucket), Prefix: aws.String(prefix)}) + if err != nil { + t.Fatalf("list objects: %v", err) + } + keys := make([]string, 0, len(output.Contents)) + for _, object := range output.Contents { + keys = append(keys, aws.ToString(object.Key)) + } + if aws.ToBool(output.IsTruncated) { + t.Fatalf("listing of %s is truncated", prefix) + } + return keys +} diff --git a/backend/integration_test/holding_migration_test.go b/backend/integration_test/holding_migration_test.go new file mode 100644 index 0000000..dafe981 --- /dev/null +++ b/backend/integration_test/holding_migration_test.go @@ -0,0 +1,196 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" +) + +// holdingsMigrationVersion creates the holdings table and organizations.holding_id. +const holdingsMigrationVersion = 41 + +// legacyMembership is a membership row written without the application. +type legacyMembership struct { + userID uuid.UUID + role string + createdAt time.Time +} + +// TestHoldingsMigrationBackfillsFoundersAndGuardsRollback runs the migration on +// organizations that were created before holdings existed. The backfill must +// give one holding per founder, and the rollback must refuse while a holding +// groups several organizations. +func TestHoldingsMigrationBackfillsFoundersAndGuardsRollback(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + // The schema before holdings: the organizations are written without them. + rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion-1) + + now := time.Now().UTC().Truncate(time.Microsecond).Add(-24 * time.Hour) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + founderA := identity.createUser(t, "holding-backfill-first@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) + founderB := identity.createUser(t, "holding-backfill-other@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) + cofounder := identity.createUser(t, "holding-backfill-cofounder@example.test", domain.ScenarioEmployer, now.Add(-time.Hour)) + + first := insertLegacyOrganization(ctx, t, pool, "Legacy first", now, + legacyMembership{userID: founderA.ID, role: "owner", createdAt: now}) + second := insertLegacyOrganization(ctx, t, pool, "Legacy second", now.Add(time.Hour), + legacyMembership{userID: founderA.ID, role: "owner", createdAt: now.Add(time.Hour)}, + // A later owner does not change the founder: the earliest membership does. + legacyMembership{userID: cofounder.ID, role: "owner", createdAt: now.Add(2 * time.Hour)}) + other := insertLegacyOrganization(ctx, t, pool, "Legacy other", now.Add(30*time.Minute), + legacyMembership{userID: founderB.ID, role: "owner", createdAt: now.Add(30 * time.Minute)}) + + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() with the holdings migration error = %v", err) + } + // Later migrations sit above holdings: the rollback subtests undo holdings + // with DownOne, so the schema is taken back to the holdings version first. + rollBackAboveMigration(ctx, t, migrator, holdingsMigrationVersion) + + t.Run("backfill gives each founder one holding dated by its first organization", func(t *testing.T) { + firstHolding := legacyHolding(ctx, t, pool, first) + if got := legacyHolding(ctx, t, pool, second); got != firstHolding { + t.Fatalf("holding of the second organization = %s, want the founder's holding %s", got, firstHolding) + } + if got := legacyHolding(ctx, t, pool, other); got == firstHolding { + t.Fatal("two founders share one holding") + } + assertLegacyHoldingFounder(ctx, t, pool, firstHolding, founderA.ID, now) + assertLegacyHoldingFounder(ctx, t, pool, legacyHolding(ctx, t, pool, other), founderB.ID, now.Add(30*time.Minute)) + var count int64 + if err := pool.QueryRow(ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil { + t.Fatalf("count holdings: %v", err) + } + if count != 2 { + t.Fatalf("holdings = %d, want one per founder (2)", count) + } + }) + + t.Run("rollback refuses while a holding groups several organizations", func(t *testing.T) { + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a grouped holding", err, privacyIntegrityViolation, "organizations_holding_grouped") + if got := legacyHolding(ctx, t, pool, first); got != legacyHolding(ctx, t, pool, second) { + t.Fatal("refused rollback changed the grouping") + } + }) + + t.Run("rollback succeeds once every holding has one organization", func(t *testing.T) { + split := uuid.Must(uuid.NewV7()) + if _, err := pool.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3)`, + split, cofounder.ID, now); err != nil { + t.Fatalf("insert the holding of the split organization: %v", err) + } + if _, err := pool.Exec(ctx, `UPDATE organizations SET holding_id = $2 WHERE id = $1`, second, split); err != nil { + t.Fatalf("move the second organization to its own holding: %v", err) + } + if _, err := migrator.DownOne(ctx); err != nil { + t.Fatalf("DownOne() with single-organization holdings error = %v", err) + } + var holdingsGone, columnGone bool + var organizations int64 + if err := pool.QueryRow(ctx, ` + SELECT + to_regclass('public.holdings') IS NULL, + NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'organizations' AND column_name = 'holding_id'), + (SELECT count(*) FROM organizations)`).Scan(&holdingsGone, &columnGone, &organizations); err != nil { + t.Fatalf("read the rolled-back schema: %v", err) + } + if !holdingsGone || !columnGone { + t.Fatalf("rollback left holdings table gone = %t, holding_id column gone = %t", holdingsGone, columnGone) + } + if organizations != 3 { + t.Fatalf("organizations after rollback = %d, want the 3 that were created", organizations) + } + + // Applying the migration again backfills the same grouping from the + // memberships, so the founders get one holding each. + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } + if got := legacyHolding(ctx, t, pool, second); got != legacyHolding(ctx, t, pool, first) { + t.Fatal("reapplied backfill does not group the founder's organizations") + } + }) +} + +// insertLegacyOrganization stores an organization and its memberships in one +// transaction, as creation did before holdings. The owner membership keeps the +// deferred constraint satisfied at commit. +func insertLegacyOrganization( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + name string, + createdAt time.Time, + memberships ...legacyMembership, +) uuid.UUID { + t.Helper() + organizationID := uuid.Must(uuid.NewV7()) + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin legacy organization transaction: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, ` + INSERT INTO organizations ( + id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at + ) VALUES ($1, $2, 'e0', 'confirmed_email', $3, 1, $3, $3)`, organizationID, name, createdAt); err != nil { + t.Fatalf("insert legacy organization: %v", err) + } + for _, membership := range memberships { + if _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + VALUES ($1, $2, $3, $4, 'active', $5, $5)`, + uuid.Must(uuid.NewV7()), organizationID, membership.userID, membership.role, membership.createdAt); err != nil { + t.Fatalf("insert legacy membership: %v", err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit legacy organization: %v", err) + } + return organizationID +} + +func legacyHolding(ctx context.Context, t *testing.T, pool *pgxpool.Pool, organizationID uuid.UUID) uuid.UUID { + t.Helper() + var holdingID uuid.UUID + if err := pool.QueryRow(ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil { + t.Fatalf("read holding of organization: %v", err) + } + return holdingID +} + +func assertLegacyHoldingFounder(ctx context.Context, t *testing.T, pool *pgxpool.Pool, holdingID, founderID uuid.UUID, createdAt time.Time) { + t.Helper() + var gotFounder uuid.UUID + var gotCreatedAt time.Time + if err := pool.QueryRow(ctx, ` + SELECT founder_account_id, created_at FROM holdings WHERE id = $1`, holdingID).Scan(&gotFounder, &gotCreatedAt); err != nil { + t.Fatalf("read holding: %v", err) + } + if gotFounder != founderID { + t.Fatalf("holding founder = %s, want %s", gotFounder, founderID) + } + if !gotCreatedAt.Equal(createdAt) { + t.Fatalf("holding created_at = %s, want %s", gotCreatedAt, createdAt) + } +} diff --git a/backend/integration_test/holding_test.go b/backend/integration_test/holding_test.go new file mode 100644 index 0000000..9fc989f --- /dev/null +++ b/backend/integration_test/holding_test.go @@ -0,0 +1,418 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// holdingConcurrentConns sizes the pool of the concurrency subtests, so that +// every goroutine of one subtest holds a connection at the same time. +const holdingConcurrentConns = 8 + +// TestHoldings covers the E0 quota pools that the organizations of one holding +// share, the isolation of accounts, and the creation of holdings. +func TestHoldings(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), companyQuotaTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + fixture := newCompanyQuotaFixture(ctx, t, databaseURL) + + t.Run("organizations of one account share the E0 pools and keep the E1 pools apart", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("shared-owner")) + first := fixture.organizationOf(t, owner, "shared-first", domain.OrganizationVerificationE0) + second := fixture.organizationOf(t, owner, "shared-second", domain.OrganizationVerificationE0) + verified := fixture.organizationOf(t, owner, "shared-verified", domain.OrganizationVerificationE1) + fixture.assertSameHolding(t, owner.ID, first.ID(), second.ID(), verified.ID()) + + // The verified organization draws on its own pool, and its usage does + // not count toward the E0 pool that follows. + for range 3 { + fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified)) + fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t)) + } + for range 6 { + fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first)) + } + for range 4 { + fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second)) + } + fixture.assertInvitationDenied(t, first, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertInvitationDenied(t, second, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertQuotaRowCounts(t, first.ID(), 6, 0) + fixture.assertQuotaRowCounts(t, second.ID(), 4, 0) + fixture.assertQuotaRowCounts(t, verified.ID(), 3, 3) + + for range 30 { + fixture.reserveCardViewAllowed(t, first, fixture.newCandidateID(t)) + } + for range 20 { + fixture.reserveCardViewAllowed(t, second, fixture.newCandidateID(t)) + } + fixture.assertCardViewDenied(t, first, fixture.clock.Now().Add(24*time.Hour)) + fixture.assertCardViewDenied(t, second, fixture.clock.Now().Add(24*time.Hour)) + fixture.assertQuotaRowCounts(t, first.ID(), 6, 30) + fixture.assertQuotaRowCounts(t, second.ID(), 4, 20) + + // The verified organization keeps its own pool: it still has room. + fixture.reserveInvitationAllowed(t, verified, fixture.newInvitationID(t, verified)) + fixture.reserveCardViewAllowed(t, verified, fixture.newCandidateID(t)) + }) + + t.Run("a second account forms its own holding and pool", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("other-owner")) + other := fixture.organizationOf(t, owner, "other-first", domain.OrganizationVerificationE0) + for range 10 { + fixture.reserveInvitationAllowed(t, other, fixture.newInvitationID(t, other)) + } + fixture.assertInvitationDenied(t, other, fixture.clock.Now().Add(7*24*time.Hour)) + + neighbour := fixture.organizations.employer(t, uniqueHoldingEmail("neighbour-owner")) + separate := fixture.organizationOf(t, neighbour, "neighbour-first", domain.OrganizationVerificationE0) + if fixture.holdingOf(t, separate.ID()) == fixture.holdingOf(t, other.ID()) { + t.Fatal("organizations of two accounts share one holding") + } + fixture.reserveInvitationAllowed(t, separate, fixture.newInvitationID(t, separate)) + fixture.reserveCardViewAllowed(t, separate, fixture.newCandidateID(t)) + }) + + t.Run("usage leaves the E0 pool with its organization", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("leave-owner")) + raised := fixture.organizationOf(t, owner, "leave-raised", domain.OrganizationVerificationE0) + sibling := fixture.organizationOf(t, owner, "leave-sibling", domain.OrganizationVerificationE0) + for range 6 { + fixture.reserveInvitationAllowed(t, raised, fixture.newInvitationID(t, raised)) + } + + if _, err := fixture.pool.Exec(fixture.ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, raised.ID(), fixture.clock.Now().Add(-30*time.Second)); err != nil { + t.Fatalf("raise organization to E1: %v", err) + } + raisedNow, _, err := fixture.organizations.read(owner.ID, raised.ID()) + if err != nil { + t.Fatalf("read raised organization: %v", err) + } + // The six invitations stay stored, but they no longer count toward the + // E0 pool, which the sibling can use in full. + for range 10 { + fixture.reserveInvitationAllowed(t, sibling, fixture.newInvitationID(t, sibling)) + } + fixture.assertInvitationDenied(t, sibling, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertQuotaRowCounts(t, raised.ID(), 6, 0) + fixture.reserveInvitationAllowed(t, raisedNow, fixture.newInvitationID(t, raisedNow)) + }) + + t.Run("concurrent reservations of one E0 pool never exceed its limits", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("race-owner")) + first := fixture.organizationOf(t, owner, "race-first", domain.OrganizationVerificationE0) + second := fixture.organizationOf(t, owner, "race-second", domain.OrganizationVerificationE0) + concurrent := newConcurrentTransactor(ctx, t, databaseURL) + + for range 5 { + fixture.reserveInvitationAllowed(t, first, fixture.newInvitationID(t, first)) + } + for range 4 { + fixture.reserveInvitationAllowed(t, second, fixture.newInvitationID(t, second)) + } + // Nine of the ten invitations are used. Four reservations race for the + // last place, two from each organization. + racers := []domain.Organization{first, second, first, second} + invitationIDs := make([]uuid.UUID, len(racers)) + for index, organization := range racers { + invitationIDs[index] = fixture.newInvitationID(t, organization) + } + decisions := make([]outbound.CompanyQuotaDecision, len(racers)) + runConcurrently(t, len(racers), func(index int) error { + decision, err := fixture.reserveInvitationLocked(concurrent, racers[index], invitationIDs[index]) + decisions[index] = decision + return err + }) + fixture.assertOneAllowed(t, decisions, fixture.clock.Now().Add(7*24*time.Hour)) + fixture.assertInvitationRowsOf(t, 10, first.ID(), second.ID()) + + viewCandidates := make([]uuid.UUID, 0, 49) + for range 49 { + viewCandidates = append(viewCandidates, fixture.newCandidateID(t)) + } + for index, candidateID := range viewCandidates { + organization := first + if index%2 == 1 { + organization = second + } + fixture.reserveCardViewAllowed(t, organization, candidateID) + } + viewRacers := make([]uuid.UUID, len(racers)) + for index := range racers { + viewRacers[index] = fixture.newCandidateID(t) + } + viewDecisions := make([]outbound.CompanyQuotaDecision, len(racers)) + runConcurrently(t, len(racers), func(index int) error { + decision, err := fixture.reserveCardViewLocked(concurrent, racers[index], viewRacers[index]) + viewDecisions[index] = decision + return err + }) + fixture.assertOneAllowed(t, viewDecisions, fixture.clock.Now().Add(24*time.Hour)) + fixture.assertCardViewRowsOf(t, 50, first.ID(), second.ID()) + }) + + t.Run("concurrent creations by one account end in one holding", func(t *testing.T) { + owner := fixture.organizations.employer(t, uniqueHoldingEmail("create-owner")) + concurrent := newConcurrentTransactor(ctx, t, databaseURL) + const creations = holdingConcurrentConns + at := fixture.clock.Now().Add(-time.Minute) + organizationIDs := make([]uuid.UUID, creations) + runConcurrently(t, creations, func(index int) error { + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{Name: fmt.Sprintf("Concurrent company %d", index)}) + if err != nil { + return fmt.Errorf("profile: %w", err) + } + company, err := domain.NewOrganization(profile, at) + if err != nil { + return fmt.Errorf("organization: %w", err) + } + membership, err := domain.NewOwnerMembership(company.ID(), owner.ID, at) + if err != nil { + return fmt.Errorf("owner membership: %w", err) + } + organizationIDs[index] = company.ID() + return concurrent.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, company, membership) + }) + }) + fixture.assertSameHolding(t, owner.ID, organizationIDs...) + if got := fixture.holdingCount(t, owner.ID); got != 1 { + t.Fatalf("holdings of the founder = %d, want 1", got) + } + }) + + t.Run("an unknown founder stores no holding", func(t *testing.T) { + before := fixture.totalHoldings(t) + unknown := uuid.New() + profile := mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Orphan company"}) + company, err := domain.NewOrganization(profile, fixture.clock.Now().Add(-time.Minute)) + if err != nil { + t.Fatalf("NewOrganization() error = %v", err) + } + membership, err := domain.NewOwnerMembership(company.ID(), unknown, company.CreatedAt()) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, company, membership) + }) + if !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("CreateWithOwner(unknown founder) error = %v, want ErrUserNotFound", err) + } + if after := fixture.totalHoldings(t); after != before { + t.Fatalf("holdings = %d after the refused creation, want %d", after, before) + } + }) +} + +// uniqueHoldingEmail returns a fresh address so that every subtest creates its +// own account and therefore its own holding. +func uniqueHoldingEmail(prefix string) string { + return fmt.Sprintf("holding-%s-%s@example.test", prefix, uuid.NewString()) +} + +// newConcurrentTransactor opens a pool of the isolated database that lets every +// goroutine of a subtest run its transaction at the same time. +func newConcurrentTransactor(ctx context.Context, t *testing.T, databaseURL string) *postgresadapter.Transactor { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + t.Fatalf("parse isolated database URL: %v", err) + } + poolConfig.MaxConns = holdingConcurrentConns + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create concurrent PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return postgresadapter.NewTransactor(pool) +} + +// runConcurrently calls work for every index at once, after all goroutines +// have started, and fails the test on the first error. work must not call +// testing methods that stop the test goroutine. +func runConcurrently(t *testing.T, count int, work func(index int) error) { + t.Helper() + errs := make([]error, count) + start := make(chan struct{}) + done := make(chan struct{}, count) + for index := range count { + go func() { + defer func() { done <- struct{}{} }() + <-start + errs[index] = work(index) + }() + } + close(start) + for range count { + <-done + } + for index, err := range errs { + if err != nil { + t.Fatalf("concurrent call %d error = %v", index, err) + } + } +} + +// reserveInvitationLocked reserves one invitation the way the production +// callers do: the organization lock first, then the reservation, in one +// transaction. +func (fixture companyQuotaFixture) reserveInvitationLocked( + transactor *postgresadapter.Transactor, + organization domain.Organization, + invitationID uuid.UUID, +) (outbound.CompanyQuotaDecision, error) { + var decision outbound.CompanyQuotaDecision + err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil { + return err + } + var err error + decision, err = fixture.service.ReserveInvitation(ctx, unit, organization, invitationID) + return err + }) + return decision, err +} + +// reserveCardViewLocked is reserveInvitationLocked for a distinct card view. +func (fixture companyQuotaFixture) reserveCardViewLocked( + transactor *postgresadapter.Transactor, + organization domain.Organization, + candidateID uuid.UUID, +) (outbound.CompanyQuotaDecision, error) { + var decision outbound.CompanyQuotaDecision + err := transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.CompanyQuotas().LockOrganization(ctx, organization.ID()); err != nil { + return err + } + var err error + decision, err = fixture.service.ReserveCardView(ctx, unit, organization, candidateID) + return err + }) + return decision, err +} + +// assertSameHolding checks that every organization is in the holding of the +// owner and that the owner has exactly one holding. +func (fixture companyQuotaFixture) assertSameHolding(t *testing.T, founderID uuid.UUID, organizationIDs ...uuid.UUID) { + t.Helper() + if got := fixture.holdingCount(t, founderID); got != 1 { + t.Fatalf("holdings of the founder = %d, want 1", got) + } + want := fixture.holdingOf(t, organizationIDs[0]) + for _, organizationID := range organizationIDs { + if got := fixture.holdingOf(t, organizationID); got != want { + t.Fatalf("organization %s is in holding %s, want %s", organizationID, got, want) + } + } +} + +func (fixture companyQuotaFixture) holdingOf(t *testing.T, organizationID uuid.UUID) uuid.UUID { + t.Helper() + var holdingID uuid.UUID + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT holding_id FROM organizations WHERE id = $1`, organizationID).Scan(&holdingID); err != nil { + t.Fatalf("read holding of organization: %v", err) + } + return holdingID +} + +func (fixture companyQuotaFixture) holdingCount(t *testing.T, founderID uuid.UUID) int64 { + t.Helper() + var count int64 + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings WHERE founder_account_id = $1`, founderID).Scan(&count); err != nil { + t.Fatalf("count holdings of founder: %v", err) + } + return count +} + +func (fixture companyQuotaFixture) totalHoldings(t *testing.T) int64 { + t.Helper() + var count int64 + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM holdings`).Scan(&count); err != nil { + t.Fatalf("count holdings: %v", err) + } + return count +} + +// assertInvitationDenied checks that the organization cannot reserve a new +// invitation and that the denial retries at retryAt. +func (fixture companyQuotaFixture) assertInvitationDenied(t *testing.T, organization domain.Organization, retryAt time.Time) { + t.Helper() + decision, err := fixture.reserveInvitation(organization, fixture.newInvitationID(t, organization)) + if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) { + t.Fatalf("ReserveInvitation() = %+v, %v; want a denial that retries at %s", decision, err, retryAt) + } +} + +// assertCardViewDenied is assertInvitationDenied for a distinct card view. +func (fixture companyQuotaFixture) assertCardViewDenied(t *testing.T, organization domain.Organization, retryAt time.Time) { + t.Helper() + decision, err := fixture.reserveCardView(organization, fixture.newCandidateID(t)) + if err != nil || decision.Allowed || !decision.RetryAt.Equal(retryAt) { + t.Fatalf("ReserveCardView() = %+v, %v; want a denial that retries at %s", decision, err, retryAt) + } +} + +// assertOneAllowed checks that exactly one of the decisions was allowed and +// that the others were denied with the given retry time. +func (fixture companyQuotaFixture) assertOneAllowed(t *testing.T, decisions []outbound.CompanyQuotaDecision, retryAt time.Time) { + t.Helper() + allowed := 0 + for _, decision := range decisions { + switch { + case decision.Allowed && decision.RetryAt.IsZero() && !decision.Reused: + allowed++ + case !decision.Allowed && decision.RetryAt.Equal(retryAt): + default: + t.Fatalf("unexpected concurrent decision %+v, want retry at %s", decision, retryAt) + } + } + if allowed != 1 { + t.Fatalf("allowed concurrent reservations = %d, want exactly 1 of %d", allowed, len(decisions)) + } +} + +// assertInvitationRowsOf checks the invitation usage stored for the given +// organizations together, which is the count of the shared pool. +func (fixture companyQuotaFixture) assertInvitationRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) { + t.Helper() + var got int64 + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil { + t.Fatalf("count invitation usage rows: %v", err) + } + if got != want { + t.Fatalf("invitation usage rows of the pool = %d, want %d", got, want) + } +} + +// assertCardViewRowsOf is assertInvitationRowsOf for distinct card views. +func (fixture companyQuotaFixture) assertCardViewRowsOf(t *testing.T, want int64, organizationIDs ...uuid.UUID) { + t.Helper() + var got int64 + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = ANY($1)`, organizationIDs).Scan(&got); err != nil { + t.Fatalf("count card-view usage rows: %v", err) + } + if got != want { + t.Fatalf("card-view usage rows of the pool = %d, want %d", got, want) + } +} diff --git a/backend/integration_test/identity_test.go b/backend/integration_test/identity_test.go new file mode 100644 index 0000000..42f855e --- /dev/null +++ b/backend/integration_test/identity_test.go @@ -0,0 +1,1228 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + identityTestTimeout = 2 * time.Minute + parallelConsumers = 10 + tokenLifetime = 24 * time.Hour + sessionLifetime = 7 * 24 * time.Hour + sessionIdleTimeout = 24 * time.Hour + signedInSessions = 3 + staleAccounts = 3 + cleanupBatch = 2 + cleanupLockTimeout = 200 * time.Millisecond + // heldTransactionConns covers a held transaction, a contender, and a spare. + heldTransactionConns = 3 + // A syntactically valid Argon2id PHC string; the tests never hash a password. + identityTestPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA" +) + +var ( + usersTable = pgx.Identifier{"users"} + emailTokensTable = pgx.Identifier{"email_tokens"} + sessionsTable = pgx.Identifier{"sessions"} + identityTables = []pgx.Identifier{usersTable, emailTokensTable, sessionsTable} +) + +type identityFixture struct { + ctx context.Context + pool *pgxpool.Pool + store *postgresadapter.IdentityStore + // now is truncated to microseconds, the precision PostgreSQL stores. + now time.Time +} + +func TestIdentityRepositories(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), identityTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + transactor := postgresadapter.NewTransactor(pool) + fixture := identityFixture{ + ctx: ctx, + pool: pool, + store: postgresadapter.NewIdentityStore(pool), + now: time.Now().UTC().Truncate(time.Microsecond), + } + + // Subtests share tables and run sequentially; each starts from empty tables. + reset := func(t *testing.T) { + t.Helper() + // The deliveries and consent records reference users, so TRUNCATE + // must name them too. + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("stores an account and finds it by ID and by any case of its email", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "Alice.Smith@Example.com", domain.ScenarioCandidate, fixture.now) + lookup := mustEmail(t, " alice.smith@EXAMPLE.COM ") + byEmail, err := fixture.store.Users().GetByEmail(ctx, lookup) + if err != nil { + t.Fatalf("GetByEmail() error = %v", err) + } + assertSameUser(t, byEmail, user) + if byEmail.Email.Address() != "Alice.Smith@Example.com" { + t.Fatalf("stored delivery address = %q, want the registered form", byEmail.Email.Address()) + } + byID, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + assertSameUser(t, byID, user) + + if _, err := fixture.store.Users().GetByID(ctx, uuid.New()); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(unknown) error = %v, want ErrUserNotFound", err) + } + if _, err := fixture.store.Users().GetByEmail(ctx, mustEmail(t, "nobody@example.com")); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByEmail(unknown) error = %v, want ErrUserNotFound", err) + } + }) + + t.Run("letter-case variants of an email conflict", func(t *testing.T) { + reset(t) + fixture.createUser(t, "Jose@Example.com", domain.ScenarioCandidate, fixture.now) + for _, variant := range []string{"jose@example.com", "JOSE@EXAMPLE.COM"} { + duplicate := fixture.newUser(t, variant, domain.ScenarioEmployer, fixture.now) + err := fixture.store.Users().Create(ctx, duplicate) + if !errors.Is(err, outbound.ErrEmailTaken) { + t.Fatalf("Create(%q) error = %v, want ErrEmailTaken", variant, err) + } + if !strings.Contains(err.Error(), "users_email_normalized_key") { + t.Fatalf("Create(%q) error = %v, want the constraint name", variant, err) + } + } + assertRowCount(ctx, t, pool, usersTable, 1) + }) + + t.Run("stores only hashes of email and session tokens", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "hashes@example.com", domain.ScenarioCandidate, fixture.now) + rawEmailToken, emailToken := fixture.issueToken(t, user, fixture.now, tokenLifetime) + rawSessionToken, session := fixture.startSession(t, user, fixture.now) + + for _, check := range []struct { + table pgx.Identifier + id uuid.UUID + raw domain.SecretToken + }{ + {table: emailTokensTable, id: emailToken.ID, raw: rawEmailToken}, + {table: sessionsTable, id: session.ID, raw: rawSessionToken}, + } { + var rowText string + var storedHash []byte + err := pool.QueryRow(ctx, fmt.Sprintf(` + SELECT row_to_json(stored)::text, stored.token_hash + FROM %s AS stored WHERE stored.id = $1`, check.table.Sanitize()), check.id).Scan(&rowText, &storedHash) + if err != nil { + t.Fatalf("read %s row: %v", check.table.Sanitize(), err) + } + if strings.Contains(rowText, check.raw.Reveal()) { + t.Fatalf("%s row contains the raw token", check.table.Sanitize()) + } + if want := sha256.Sum256([]byte(check.raw.Reveal())); string(storedHash) != string(want[:]) { + t.Fatalf("%s token_hash is not the SHA-256 digest of the raw token", check.table.Sanitize()) + } + } + for _, raw := range []domain.SecretToken{rawEmailToken, rawSessionToken} { + var matches int + err := pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM users AS u WHERE strpos(row_to_json(u)::text, $1) > 0) + + (SELECT count(*) FROM email_tokens AS e WHERE strpos(row_to_json(e)::text, $1) > 0) + + (SELECT count(*) FROM sessions AS s WHERE strpos(row_to_json(s)::text, $1) > 0)`, + raw.Reveal()).Scan(&matches) + if err != nil { + t.Fatalf("search identity tables for a raw token: %v", err) + } + if matches != 0 { + t.Fatalf("%d identity rows contain a raw token", matches) + } + } + + // Every secret-bearing column in the identity schema is a hash. + rows, err := pool.Query(ctx, ` + SELECT table_name || '.' || column_name FROM information_schema.columns + WHERE table_schema = 'public' + AND table_name IN ('users', 'email_tokens', 'sessions') + AND (column_name LIKE '%password%' OR column_name LIKE '%token%' OR column_name LIKE '%secret%') + AND column_name NOT LIKE '%\_hash' + ORDER BY 1`) + if err != nil { + t.Fatalf("list secret-bearing columns: %v", err) + } + unhashed, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("read secret-bearing columns: %v", err) + } + if len(unhashed) != 0 { + t.Fatalf("identity columns store secrets without hashing: %v", unhashed) + } + }) + + t.Run("re-registration advances versions and rejects a stale writer or a verified account", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "rereg@example.com", domain.ScenarioCandidate, fixture.now) + later := fixture.now.Add(time.Hour) + changed, err := user.ReRegister(fixture.registration(t, "ReReg@Example.com", domain.ScenarioEmployer, later)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + stored, err := fixture.store.Users().UpdateRegistration(ctx, changed) + if err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + if stored.Version != 2 || stored.RegistrationVersion != 2 || stored.Scenario != domain.ScenarioEmployer || + stored.OnboardingStep != domain.OnboardingStepEmployerCompany || stored.Email.Address() != "ReReg@Example.com" || + !stored.LastRegisteredAt.Equal(later) || !stored.CreatedAt.Equal(fixture.now) { + t.Fatalf("UpdateRegistration() = %+v", stored) + } + + // A writer that still holds version 1 must not overwrite version 2. + stale, err := user.ReRegister(fixture.registration(t, "rereg@example.com", domain.ScenarioCandidate, later)) + if err != nil { + t.Fatalf("ReRegister(stale) error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, stale); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(stale) error = %v, want ErrUserVersionConflict", err) + } + + verified, err := fixture.store.Users().MarkEmailVerified(ctx, user.ID, stored.RegistrationVersion, later) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + // The stored row is verified even if a caller still holds the unverified view. + unverifiedView := verified + unverifiedView.EmailVerifiedAt = nil + afterVerification, err := unverifiedView.ReRegister(fixture.registration(t, "rereg@example.com", domain.ScenarioCandidate, later)) + if err != nil { + t.Fatalf("ReRegister(unverified view) error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, afterVerification); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("UpdateRegistration(verified account) error = %v, want ErrUserVersionConflict", err) + } + current, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + assertSameUser(t, current, verified) + }) + + t.Run("verification requires the current registration version and happens once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "verify@example.com", domain.ScenarioCandidate, fixture.now) + users := fixture.store.Users() + if _, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion+1, fixture.now); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("MarkEmailVerified(other registration version) error = %v, want ErrUserVersionConflict", err) + } + verified, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, fixture.now) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + if !verified.EmailVerified() || !verified.EmailVerifiedAt.Equal(fixture.now) || verified.Version != user.Version+1 { + t.Fatalf("MarkEmailVerified() = %+v", verified) + } + if _, err := users.MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, fixture.now); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("second MarkEmailVerified() error = %v, want ErrUserVersionConflict", err) + } + }) + + t.Run("parallel confirmations consume a token exactly once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "parallel@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + // One connection per confirmation plus a spare, so nothing queues in the pool. + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, parallelConsumers+1)) + at := fixture.now.Add(time.Minute) + + errs := make([]error, parallelConsumers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range parallelConsumers { + group.Go(func() { + <-start + errs[index] = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + token, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at) + if err != nil { + return err + } + _, err = unit.Users().MarkEmailVerified(ctx, token.UserID, token.RegistrationVersion, at) + return err + }) + }) + } + close(start) + group.Wait() + + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrEmailTokenConsumed): + default: + t.Fatalf("confirmation %d error = %v, want nil or ErrEmailTokenConsumed", index, err) + } + } + if successes != 1 { + t.Fatalf("%d confirmations succeeded, want exactly 1", successes) + } + verified, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + if !verified.EmailVerified() || verified.Version != user.Version+1 { + t.Fatalf("account after confirmations = %+v, want verified once", verified) + } + }) + + t.Run("parallel consumes outside a transaction succeed exactly once", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "autocommit@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentStore := postgresadapter.NewIdentityStore(env.newPoolWithMaxConns(ctx, t, parallelConsumers+1)) + errs := make([]error, parallelConsumers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range parallelConsumers { + group.Go(func() { + <-start + _, errs[index] = concurrentStore.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + }) + } + close(start) + group.Wait() + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrEmailTokenConsumed): + default: + t.Fatalf("consume %d error = %v, want nil or ErrEmailTokenConsumed", index, err) + } + } + if successes != 1 { + t.Fatalf("%d consumes succeeded, want exactly 1", successes) + } + }) + + t.Run("expired, invalidated, superseded, unknown, and wrong-purpose tokens are not consumable", func(t *testing.T) { + reset(t) + tokens := fixture.store.EmailTokens() + purpose := domain.EmailTokenPurposeEmailVerification + user := fixture.createUser(t, "states@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "other@example.com", domain.ScenarioEmployer, fixture.now) + + expired, _ := fixture.issueToken(t, user, fixture.now.Add(-2*time.Hour), time.Hour) + assertConsumeError(ctx, t, tokens, expired, fixture.now, outbound.ErrEmailTokenExpired) + // The deadline itself is already past. + atDeadline, deadlineToken := fixture.issueToken(t, user, fixture.now, time.Hour) + assertConsumeError(ctx, t, tokens, atDeadline, deadlineToken.ExpiresAt, outbound.ErrEmailTokenExpired) + + unknown, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + assertConsumeError(ctx, t, tokens, unknown, fixture.now, outbound.ErrEmailTokenNotFound) + if _, err := tokens.Consume(ctx, atDeadline.Hash(), "password_reset", fixture.now); !errors.Is(err, outbound.ErrEmailTokenNotFound) { + t.Fatalf("Consume(wrong purpose) error = %v, want ErrEmailTokenNotFound", err) + } + + consumed, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + if _, err := tokens.Consume(ctx, consumed.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume() error = %v", err) + } + // A consumed token stays consumed after its deadline. + assertConsumeError(ctx, t, tokens, consumed, fixture.now.Add(2*tokenLifetime), outbound.ErrEmailTokenConsumed) + + first, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + second, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + otherToken, _ := fixture.issueToken(t, other, fixture.now, tokenLifetime) + // The two active tokens and the expired, unmarked ones are invalidated; + // the consumed token and the other user's token are not. + invalidated, err := tokens.InvalidateActive(ctx, user.ID, purpose, fixture.now) + if err != nil { + t.Fatalf("InvalidateActive() error = %v", err) + } + if invalidated != 4 { + t.Fatalf("InvalidateActive() = %d, want 4", invalidated) + } + assertConsumeError(ctx, t, tokens, first, fixture.now, outbound.ErrEmailTokenInvalidated) + assertConsumeError(ctx, t, tokens, second, fixture.now, outbound.ErrEmailTokenInvalidated) + assertConsumeError(ctx, t, tokens, consumed, fixture.now, outbound.ErrEmailTokenConsumed) + if again, err := tokens.InvalidateActive(ctx, user.ID, purpose, fixture.now); err != nil || again != 0 { + t.Fatalf("second InvalidateActive() = %d, %v, want 0", again, err) + } + // A token issued after the invalidation works. + fresh, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + if _, err := tokens.Consume(ctx, fresh.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume(fresh) error = %v", err) + } + if _, err := tokens.Consume(ctx, otherToken.Hash(), purpose, fixture.now); err != nil { + t.Fatalf("Consume(other user's token) error = %v", err) + } + + // A token bound to an earlier registration version never confirms the + // newer registration, even when nobody invalidated it. + superseded, _ := fixture.issueToken(t, other, fixture.now, tokenLifetime) + reRegistered, err := other.ReRegister(fixture.registration(t, "other@example.com", domain.ScenarioCandidate, fixture.now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + if _, err := fixture.store.Users().UpdateRegistration(ctx, reRegistered); err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + assertConsumeError(ctx, t, tokens, superseded, fixture.now, outbound.ErrEmailTokenInvalidated) + }) + + t.Run("tokens and sessions for a missing account report ErrUserNotFound", func(t *testing.T) { + reset(t) + missing := uuid.New() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: missing, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: 1, IssuedAt: fixture.now, Lifetime: tokenLifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + if err := fixture.store.EmailTokens().Insert(ctx, token); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("Insert(missing user) error = %v, want ErrUserNotFound", err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: missing, TokenHash: raw.Hash(), StartedAt: fixture.now, AbsoluteLifetime: sessionLifetime, + }) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + if err := fixture.store.Sessions().Create(ctx, session); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("Create(missing user) error = %v, want ErrUserNotFound", err) + } + }) + + t.Run("duplicate token hashes are rejected", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "duplicate@example.com", domain.ScenarioCandidate, fixture.now) + _, first := fixture.issueToken(t, user, fixture.now, tokenLifetime) + second := first + second.ID = uuid.New() + if err := fixture.store.EmailTokens().Insert(ctx, second); !errors.Is(err, outbound.ErrTokenHashConflict) { + t.Fatalf("Insert(duplicate hash) error = %v, want ErrTokenHashConflict", err) + } + _, session := fixture.startSession(t, user, fixture.now) + duplicateSession := session + duplicateSession.ID = uuid.New() + if err := fixture.store.Sessions().Create(ctx, duplicateSession); !errors.Is(err, outbound.ErrTokenHashConflict) { + t.Fatalf("Create(duplicate session hash) error = %v, want ErrTokenHashConflict", err) + } + }) + + t.Run("sessions are found while active and stop at idle, absolute, and revocation limits", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "session@example.com", domain.ScenarioCandidate, fixture.now) + raw, session := fixture.startSession(t, user, fixture.now) + + found, err := sessions.FindActive(ctx, raw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive() error = %v", err) + } + assertSameSession(t, found, session) + + touchedAt := fixture.now.Add(23 * time.Hour) + if err := sessions.Touch(ctx, session.ID, touchedAt, sessionIdleTimeout); err != nil { + t.Fatalf("Touch() error = %v", err) + } + // An older activity time does not move last_seen_at back. + if err := sessions.Touch(ctx, session.ID, fixture.now.Add(time.Hour), sessionIdleTimeout); err != nil { + t.Fatalf("Touch(older) error = %v", err) + } + found, err = sessions.FindActive(ctx, raw.Hash(), touchedAt.Add(sessionIdleTimeout-time.Second), sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive(before idle deadline) error = %v", err) + } + if !found.LastSeenAt.Equal(touchedAt) { + t.Fatalf("LastSeenAt = %v, want %v", found.LastSeenAt, touchedAt) + } + idleAt := touchedAt.Add(sessionIdleTimeout) + if _, err := sessions.FindActive(ctx, raw.Hash(), idleAt, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(idle) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, session.ID, idleAt, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(idle) error = %v, want ErrSessionNotFound", err) + } + + // Activity never extends the absolute deadline. + if _, err := sessions.FindActive(ctx, raw.Hash(), session.ExpiresAt, sessionLifetime); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(at absolute deadline) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, session.ID, session.ExpiresAt, sessionLifetime); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(at absolute deadline) error = %v, want ErrSessionNotFound", err) + } + + unknown, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + if _, err := sessions.FindActive(ctx, unknown.Hash(), fixture.now, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(unknown) error = %v, want ErrSessionNotFound", err) + } + + revokedRaw, revokedSession := fixture.startSession(t, user, fixture.now) + if err := sessions.Revoke(ctx, revokedSession.ID, fixture.now.Add(time.Minute)); err != nil { + t.Fatalf("Revoke() error = %v", err) + } + if _, err := sessions.FindActive(ctx, revokedRaw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(revoked) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Touch(ctx, revokedSession.ID, fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(revoked) error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Revoke(ctx, revokedSession.ID, fixture.now.Add(time.Minute)); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("second Revoke() error = %v, want ErrSessionNotFound", err) + } + if err := sessions.Revoke(ctx, uuid.New(), fixture.now); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Revoke(unknown) error = %v, want ErrSessionNotFound", err) + } + }) + + t.Run("revoking all of a user's sessions leaves other users signed in", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "everywhere@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "bystander@example.com", domain.ScenarioEmployer, fixture.now) + userTokens := make([]domain.SecretToken, 0, signedInSessions) + for range signedInSessions { + raw, _ := fixture.startSession(t, user, fixture.now) + userTokens = append(userTokens, raw) + } + _, alreadyRevoked := fixture.startSession(t, user, fixture.now) + if err := sessions.Revoke(ctx, alreadyRevoked.ID, fixture.now); err != nil { + t.Fatalf("Revoke() error = %v", err) + } + otherRaw, _ := fixture.startSession(t, other, fixture.now) + + revoked, err := sessions.RevokeAllForUser(ctx, user.ID, fixture.now.Add(time.Minute)) + if err != nil { + t.Fatalf("RevokeAllForUser() error = %v", err) + } + if revoked != int64(len(userTokens)) { + t.Fatalf("RevokeAllForUser() = %d, want %d", revoked, len(userTokens)) + } + for _, raw := range userTokens { + if _, err := sessions.FindActive(ctx, raw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("FindActive(revoked by RevokeAllForUser) error = %v, want ErrSessionNotFound", err) + } + } + if _, err := sessions.FindActive(ctx, otherRaw.Hash(), fixture.now.Add(time.Minute), sessionIdleTimeout); err != nil { + t.Fatalf("FindActive(other user) error = %v", err) + } + }) + + t.Run("cleanup deletes stale unverified accounts in batches with their tokens and sessions", func(t *testing.T) { + reset(t) + users := fixture.store.Users() + cutoff := fixture.now.Add(-7 * 24 * time.Hour) + stale := make([]domain.User, 0, staleAccounts) + for index := range staleAccounts { + registeredAt := cutoff.Add(-time.Duration(staleAccounts-index) * time.Hour) + user := fixture.createUser(t, fmt.Sprintf("stale%d@example.com", index), domain.ScenarioCandidate, registeredAt) + fixture.issueToken(t, user, registeredAt, tokenLifetime) + fixture.startSession(t, user, registeredAt) + stale = append(stale, user) + } + recent := fixture.createUser(t, "recent@example.com", domain.ScenarioCandidate, cutoff.Add(time.Hour)) + verified := fixture.createUser(t, "verified@example.com", domain.ScenarioCandidate, cutoff.Add(-24*time.Hour)) + if _, err := users.MarkEmailVerified(ctx, verified.ID, verified.RegistrationVersion, cutoff.Add(-23*time.Hour)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + fixture.startSession(t, verified, fixture.now) + + deleted, err := users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, cleanupBatch) + if err != nil || deleted != cleanupBatch { + t.Fatalf("first DeleteUnverifiedRegisteredBefore() = %d, %v, want 2", deleted, err) + } + // The oldest go first. + for _, user := range stale[:cleanupBatch] { + if _, err := users.GetByID(ctx, user.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(deleted) error = %v, want ErrUserNotFound", err) + } + } + deleted, err = users.DeleteUnverifiedRegisteredBefore(ctx, cutoff, cleanupBatch) + if err != nil || deleted != staleAccounts-cleanupBatch { + t.Fatalf("second DeleteUnverifiedRegisteredBefore() = %d, %v, want 1", deleted, err) + } + for _, kept := range []domain.User{recent, verified} { + if _, err := users.GetByID(ctx, kept.ID); err != nil { + t.Fatalf("GetByID(kept) error = %v", err) + } + } + assertRowCount(ctx, t, pool, usersTable, 2) + assertRowCount(ctx, t, pool, emailTokensTable, 0) + assertRowCount(ctx, t, pool, sessionsTable, 1) + }) + + t.Run("deleting an account cascades to its tokens and sessions", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "cascade@example.com", domain.ScenarioCandidate, fixture.now) + other := fixture.createUser(t, "survivor@example.com", domain.ScenarioCandidate, fixture.now) + for _, owner := range []domain.User{user, other} { + fixture.issueToken(t, owner, fixture.now, tokenLifetime) + fixture.startSession(t, owner, fixture.now) + } + if _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, user.ID); err != nil { + t.Fatalf("delete user: %v", err) + } + assertRowCount(ctx, t, pool, emailTokensTable, 1) + assertRowCount(ctx, t, pool, sessionsTable, 1) + var orphans int + err := pool.QueryRow(ctx, ` + SELECT (SELECT count(*) FROM email_tokens WHERE user_id = $1) + + (SELECT count(*) FROM sessions WHERE user_id = $1)`, user.ID).Scan(&orphans) + if err != nil || orphans != 0 { + t.Fatalf("rows of the deleted user = %d, %v, want 0", orphans, err) + } + }) + + t.Run("repositories commit and roll back with the surrounding transaction", func(t *testing.T) { + reset(t) + writeAll := func(user domain.User) func(context.Context, outbound.UnitOfWork) error { + return func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, user); err != nil { + return err + } + _, token := fixture.newToken(t, user, fixture.now, tokenLifetime) + if err := unit.EmailTokens().Insert(ctx, token); err != nil { + return err + } + _, session := fixture.newSession(t, user, fixture.now) + if err := unit.Sessions().Create(ctx, session); err != nil { + return err + } + // Reads inside the transaction see its own writes. + if _, err := unit.Users().GetByID(ctx, user.ID); err != nil { + return err + } + return nil + } + } + + rolledBack := fixture.newUser(t, "rollback@example.com", domain.ScenarioCandidate, fixture.now) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := writeAll(rolledBack)(ctx, unit); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the callback error", err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 0) + } + + committed := fixture.newUser(t, "commit@example.com", domain.ScenarioCandidate, fixture.now) + if err := transactor.WithinTransaction(ctx, writeAll(committed)); err != nil { + t.Fatalf("WithinTransaction() error = %v", err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 1) + } + + // A failed statement aborts the transaction: the duplicate email rolls + // back the account written before it. + first := fixture.newUser(t, "first@example.com", domain.ScenarioCandidate, fixture.now) + duplicate := fixture.newUser(t, "COMMIT@example.com", domain.ScenarioCandidate, fixture.now) + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Users().Create(ctx, first); err != nil { + return err + } + return unit.Users().Create(ctx, duplicate) + }) + if !errors.Is(err, outbound.ErrEmailTaken) { + t.Fatalf("WithinTransaction(duplicate) error = %v, want ErrEmailTaken", err) + } + if _, err := fixture.store.Users().GetByID(ctx, first.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(rolled back) error = %v, want ErrUserNotFound", err) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("touch writes at most once per interval and reports inactive sessions", func(t *testing.T) { + reset(t) + sessions := fixture.store.Sessions() + user := fixture.createUser(t, "throttle@example.com", domain.ScenarioCandidate, fixture.now) + raw, session := fixture.startSession(t, user, fixture.now) + lastSeen := func(at time.Time) time.Time { + t.Helper() + found, err := sessions.FindActive(ctx, raw.Hash(), at, sessionIdleTimeout) + if err != nil { + t.Fatalf("FindActive() error = %v", err) + } + return found.LastSeenAt + } + soon := fixture.now.Add(30 * time.Second) + if err := sessions.Touch(ctx, session.ID, soon, sessionIdleTimeout); err != nil { + t.Fatalf("Touch(within interval) error = %v", err) + } + if got := lastSeen(soon); !got.Equal(fixture.now) { + t.Fatalf("LastSeenAt after a touch within the interval = %v, want the unchanged %v", got, fixture.now) + } + later := fixture.now.Add(2 * time.Minute) + if err := sessions.Touch(ctx, session.ID, later, sessionIdleTimeout); err != nil { + t.Fatalf("Touch(after interval) error = %v", err) + } + if got := lastSeen(later); !got.Equal(later) { + t.Fatalf("LastSeenAt after a touch past the interval = %v, want %v", got, later) + } + if err := sessions.Touch(ctx, uuid.New(), later, sessionIdleTimeout); !errors.Is(err, outbound.ErrSessionNotFound) { + t.Fatalf("Touch(unknown) error = %v, want ErrSessionNotFound", err) + } + }) + + t.Run("a waiting consume fails after the holder commits and succeeds after it rolls back", func(t *testing.T) { + for _, variant := range []struct { + name string + commitFirst bool + wantSecond error + }{ + {name: "commit", commitFirst: true, wantSecond: outbound.ErrEmailTokenConsumed}, + {name: "rollback", commitFirst: false, wantSecond: nil}, + } { + t.Run(variant.name, func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "lockwait@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + applicationName := "identity_consume_waiter_" + variant.name + holder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + return err + }, variant.commitFirst) + holder.awaitHeld(ctx, t) + + var waiterErr error + waiterDone := make(chan struct{}) + go func() { + defer close(waiterDone) + waiterErr = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // Label the session so the test can observe its lock wait. + if _, err := integrationTx(t, unit).Exec(ctx, "SET LOCAL application_name = '"+applicationName+"'"); err != nil { + return fmt.Errorf("label waiter: %w", err) + } + _, err := unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, fixture.now) + return err + }) + }() + waitEvent, observed := waitForLockWait(ctx, pool, applicationName) + holderErr := holder.finish() + <-waiterDone + if !observed { + t.Fatalf("the second consume was not observed waiting on a lock (last wait event %q)", waitEvent) + } + t.Logf("observed the second consume waiting on a lock: wait_event=%s", waitEvent) + if variant.commitFirst && holderErr != nil { + t.Fatalf("holder error = %v, want a commit", holderErr) + } + if !variant.commitFirst && !errors.Is(holderErr, errForcedRollback) { + t.Fatalf("holder error = %v, want the forced rollback", holderErr) + } + if (variant.wantSecond == nil && waiterErr != nil) || !errors.Is(waiterErr, variant.wantSecond) { + t.Fatalf("second consume error = %v, want %v", waiterErr, variant.wantSecond) + } + var consumed int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM email_tokens WHERE consumed_at IS NOT NULL`).Scan(&consumed); err != nil || consumed != 1 { + t.Fatalf("consumed tokens = %d, %v, want exactly 1", consumed, err) + } + }) + } + }) + + t.Run("a token issued before a concurrent re-registration cannot verify the new credentials", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "race@example.com", domain.ScenarioCandidate, fixture.now) + raw, _ := fixture.issueToken(t, user, fixture.now, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + at := fixture.now.Add(time.Minute) + + // The confirmation consumes the token, holds its transaction open, and + // verifies the account with the token's registration version on finish. + var token domain.EmailToken + confirmation := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + token, err = unit.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at) + return err + }, true) + confirmation.afterRelease = func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Users().MarkEmailVerified(ctx, token.UserID, token.RegistrationVersion, at) + return err + } + confirmation.awaitHeld(ctx, t) + + // The re-registration commits between Consume and MarkEmailVerified. It + // skips InvalidateActive on purpose, so only the version check in + // MarkEmailVerified stands between the old token and the new password. + reRegistered, err := user.ReRegister(fixture.registration(t, "race@example.com", domain.ScenarioEmployer, at)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + stored, err := fixture.store.Users().UpdateRegistration(ctx, reRegistered) + if err != nil { + t.Fatalf("UpdateRegistration() error = %v", err) + } + if err := confirmation.finish(); !errors.Is(err, outbound.ErrUserVersionConflict) { + t.Fatalf("confirmation error = %v, want ErrUserVersionConflict", err) + } + current, err := fixture.store.Users().GetByID(ctx, user.ID) + if err != nil { + t.Fatalf("GetByID() error = %v", err) + } + if current.EmailVerified() || current.RegistrationVersion != stored.RegistrationVersion || current.Scenario != domain.ScenarioEmployer { + t.Fatalf("account after the race = %+v, want the unverified re-registration", current) + } + // The rollback restored the token, which is now superseded. + assertConsumeError(ctx, t, fixture.store.EmailTokens(), raw, at, outbound.ErrEmailTokenInvalidated) + }) + + t.Run("cleanup skips accounts locked by open transactions without waiting", func(t *testing.T) { + reset(t) + cutoff := fixture.now.Add(-7 * 24 * time.Hour) + registeredAt := cutoff.Add(-time.Hour) + reRegistering := fixture.createUser(t, "reregistering@example.com", domain.ScenarioCandidate, registeredAt) + confirming := fixture.createUser(t, "confirming@example.com", domain.ScenarioCandidate, registeredAt) + idle := fixture.createUser(t, "idle@example.com", domain.ScenarioCandidate, registeredAt) + confirmingToken, _ := fixture.issueToken(t, confirming, registeredAt, tokenLifetime) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + + // One transaction holds the account row, the other only a token row. + changed, err := reRegistering.ReRegister(fixture.registration(t, "reregistering@example.com", domain.ScenarioEmployer, fixture.now)) + if err != nil { + t.Fatalf("ReRegister() error = %v", err) + } + accountHolder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Users().UpdateRegistration(ctx, changed) + return err + }, false) + accountHolder.awaitHeld(ctx, t) + tokenHolder := startHeldTransaction(ctx, t, concurrentTransactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.EmailTokens().Consume(ctx, confirmingToken.Hash(), domain.EmailTokenPurposeEmailVerification, registeredAt.Add(time.Minute)) + return err + }, false) + tokenHolder.awaitHeld(ctx, t) + + // A lock wait longer than the timeout would fail the statement. + impatientPool := env.newPoolWithLockTimeout(ctx, t, cleanupLockTimeout) + var lockTimeout string + if err := impatientPool.QueryRow(ctx, "SHOW lock_timeout").Scan(&lockTimeout); err != nil || lockTimeout != fmt.Sprintf("%dms", cleanupLockTimeout.Milliseconds()) { + t.Fatalf("cleanup session lock_timeout = %q, %v, want %s", lockTimeout, err, cleanupLockTimeout) + } + impatientStore := postgresadapter.NewIdentityStore(impatientPool) + deleted, err := impatientStore.Users().DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil { + t.Fatalf("DeleteUnverifiedRegisteredBefore() with locked accounts error = %v", err) + } + if deleted != 1 { + t.Fatalf("DeleteUnverifiedRegisteredBefore() = %d, want only the unlocked account", deleted) + } + if _, err := fixture.store.Users().GetByID(ctx, idle.ID); !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("GetByID(unlocked stale account) error = %v, want ErrUserNotFound", err) + } + if err := accountHolder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("account holder error = %v, want the forced rollback", err) + } + if err := tokenHolder.finish(); !errors.Is(err, errForcedRollback) { + t.Fatalf("token holder error = %v, want the forced rollback", err) + } + + // Once the locks are gone, the next run removes the skipped accounts. + deleted, err = impatientStore.Users().DeleteUnverifiedRegisteredBefore(ctx, cutoff, staleAccounts) + if err != nil || deleted != 2 { + t.Fatalf("second DeleteUnverifiedRegisteredBefore() = %d, %v, want 2", deleted, err) + } + for _, table := range identityTables { + assertRowCount(ctx, t, pool, table, 0) + } + }) + + t.Run("pool repositories refuse a transaction context", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "nested@example.com", domain.ScenarioCandidate, fixture.now) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, _ outbound.UnitOfWork) error { + _, err := fixture.store.Users().GetByID(ctx, user.ID) + return err + }) + if !errors.Is(err, outbound.ErrNestedTransaction) { + t.Fatalf("IdentityStore inside WithinTransaction error = %v, want ErrNestedTransaction", err) + } + }) + + t.Run("the transactor reports a deadlock as a retryable conflict", func(t *testing.T) { + reset(t) + first := fixture.createUser(t, "deadlock1@example.com", domain.ScenarioCandidate, fixture.now) + second := fixture.createUser(t, "deadlock2@example.com", domain.ScenarioCandidate, fixture.now) + concurrentTransactor := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, heldTransactionConns)) + // Each transaction locks one account and then the other's. + crossLock := func(own, other uuid.UUID, locked chan<- struct{}, otherLocked <-chan struct{}) transactionFn { + return func(ctx context.Context, unit outbound.UnitOfWork) error { + update := `UPDATE users SET updated_at = updated_at WHERE id = $1` + if _, err := integrationTx(t, unit).Exec(ctx, update, own); err != nil { + return err + } + close(locked) + <-otherLocked + _, err := integrationTx(t, unit).Exec(ctx, update, other) + return err + } + } + firstLocked, secondLocked := make(chan struct{}), make(chan struct{}) + errs := make([]error, 2) + var group sync.WaitGroup + group.Go(func() { + errs[0] = concurrentTransactor.WithinTransaction(ctx, crossLock(first.ID, second.ID, firstLocked, secondLocked)) + }) + group.Go(func() { + errs[1] = concurrentTransactor.WithinTransaction(ctx, crossLock(second.ID, first.ID, secondLocked, firstLocked)) + }) + group.Wait() + conflicts := 0 + for index, err := range errs { + switch { + case err == nil: + case errors.Is(err, outbound.ErrTransactionConflict): + conflicts++ + default: + t.Fatalf("transaction %d error = %v, want nil or ErrTransactionConflict", index, err) + } + } + if conflicts != 1 { + t.Fatalf("%d transactions reported a conflict, want exactly 1: %v", conflicts, errs) + } + }) + + t.Run("database constraints back the domain rules", func(t *testing.T) { + reset(t) + user := fixture.createUser(t, "constraints@example.com", domain.ScenarioCandidate, fixture.now) + tests := []struct { + constraint string + statement string + args []any + }{ + { + constraint: "users_scenario_onboarding_step", + statement: `UPDATE users SET onboarding_step = 'employer_company' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_scenario_onboarding_step", + statement: `UPDATE users SET scenario = 'admin' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = 'correct horse battery staple' WHERE id = $1`, + args: []any{user.ID}, + }, + { + // The domain regex rejects zero and leading-zero parameters too. + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=0,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_password_hash_format", + statement: `UPDATE users SET password_hash = '$argon2id$v=19$m=019456,t=2,p=1$c2FsdHNhbHRzYWx0$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaA' WHERE id = $1`, + args: []any{user.ID}, + }, + { + // The key matches the address, so only the ASCII rule fails. + constraint: "users_email_ascii", + statement: "UPDATE users SET email = 'Jos\u00e9@example.com', email_normalized = 'jos\u00e9@example.com' WHERE id = $1", + args: []any{user.ID}, + }, + { + constraint: "users_email_normalized_rule", + statement: `UPDATE users SET email_normalized = 'CONSTRAINTS@example.com' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "users_timestamps_after_creation", + statement: `UPDATE users SET email_verified_at = created_at - interval '1 second' WHERE id = $1`, + args: []any{user.ID}, + }, + { + constraint: "email_tokens_outcome_after_creation", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at, consumed_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5, $6)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour), fixture.now.Add(-time.Second)}, + }, + { + constraint: "sessions_revoked_after_creation", + statement: `INSERT INTO sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at, revoked_at) + VALUES ($1, $2, $3, $4, $4, $5, $6)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour), fixture.now.Add(-time.Second)}, + }, + { + constraint: "email_tokens_token_hash_sha256", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5)`, + args: []any{uuid.New(), user.ID, []byte("raw-token-is-not-a-digest"), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "email_tokens_purpose_known", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at) + VALUES ($1, $2, 'magic_link', $3, 1, $4, $5)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "email_tokens_single_outcome", + statement: `INSERT INTO email_tokens (id, user_id, purpose, token_hash, registration_version, created_at, expires_at, consumed_at, invalidated_at) + VALUES ($1, $2, 'email_verification', $3, 1, $4, $5, $4, $4)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now, fixture.now.Add(time.Hour)}, + }, + { + constraint: "sessions_expiry_after_creation", + statement: `INSERT INTO sessions (id, user_id, token_hash, created_at, last_seen_at, expires_at) + VALUES ($1, $2, $3, $4, $4, $4)`, + args: []any{uuid.New(), user.ID, make([]byte, sha256.Size), fixture.now}, + }, + } + for _, test := range tests { + _, err := pool.Exec(ctx, test.statement, test.args...) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("statement violating %s error = %v, want a check violation", test.constraint, err) + } + } + }) +} + +func (fixture identityFixture) registration(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.Registration { + t.Helper() + passwordHash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + return domain.Registration{Email: mustEmail(t, rawEmail), PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: at} +} + +func (fixture identityFixture) newUser(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.User { + t.Helper() + user, err := domain.NewUser(fixture.registration(t, rawEmail, scenario, at)) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + return user +} + +func (fixture identityFixture) createUser(t *testing.T, rawEmail string, scenario domain.Scenario, at time.Time) domain.User { + t.Helper() + user := fixture.newUser(t, rawEmail, scenario, at) + if err := fixture.store.Users().Create(fixture.ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", rawEmail, err) + } + return user +} + +func (fixture identityFixture) newToken(t *testing.T, user domain.User, at time.Time, lifetime time.Duration) (domain.SecretToken, domain.EmailToken) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, TokenHash: raw.Hash(), + RegistrationVersion: user.RegistrationVersion, IssuedAt: at, Lifetime: lifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + return raw, token +} + +func (fixture identityFixture) issueToken(t *testing.T, user domain.User, at time.Time, lifetime time.Duration) (domain.SecretToken, domain.EmailToken) { + t.Helper() + raw, token := fixture.newToken(t, user, at, lifetime) + if err := fixture.store.EmailTokens().Insert(fixture.ctx, token); err != nil { + t.Fatalf("Insert() error = %v", err) + } + return raw, token +} + +func (fixture identityFixture) newSession(t *testing.T, user domain.User, at time.Time) (domain.SecretToken, domain.Session) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, TokenHash: raw.Hash(), StartedAt: at, AbsoluteLifetime: sessionLifetime, + }) + if err != nil { + t.Fatalf("NewSession() error = %v", err) + } + return raw, session +} + +func (fixture identityFixture) startSession(t *testing.T, user domain.User, at time.Time) (domain.SecretToken, domain.Session) { + t.Helper() + raw, session := fixture.newSession(t, user, at) + if err := fixture.store.Sessions().Create(fixture.ctx, session); err != nil { + t.Fatalf("Create(session) error = %v", err) + } + return raw, session +} + +func mustEmail(t *testing.T, raw string) domain.EmailAddress { + t.Helper() + email, err := domain.NewEmailAddress(raw) + if err != nil { + t.Fatalf("NewEmailAddress(%q) error = %v", raw, err) + } + return email +} + +func assertConsumeError( + ctx context.Context, + t *testing.T, + tokens outbound.EmailTokenRepository, + raw domain.SecretToken, + at time.Time, + want error, +) { + t.Helper() + if _, err := tokens.Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, at); !errors.Is(err, want) { + t.Fatalf("Consume() error = %v, want %v", err, want) + } +} + +func assertSameUser(t *testing.T, got, want domain.User) { + t.Helper() + sameVerification := (got.EmailVerifiedAt == nil) == (want.EmailVerifiedAt == nil) && + (got.EmailVerifiedAt == nil || got.EmailVerifiedAt.Equal(*want.EmailVerifiedAt)) + if got.ID != want.ID || got.Email.Address() != want.Email.Address() || got.Email.Normalized() != want.Email.Normalized() || + got.PasswordHash.PHC() != want.PasswordHash.PHC() || + got.Scenario != want.Scenario || got.OnboardingStep != want.OnboardingStep || !sameVerification || + got.RegistrationVersion != want.RegistrationVersion || !got.LastRegisteredAt.Equal(want.LastRegisteredAt) || + got.Version != want.Version || !got.CreatedAt.Equal(want.CreatedAt) || !got.UpdatedAt.Equal(want.UpdatedAt) { + t.Fatalf("user = %+v, want %+v", got, want) + } +} + +func assertSameSession(t *testing.T, got, want domain.Session) { + t.Helper() + if got.ID != want.ID || got.UserID != want.UserID || got.TokenHash != want.TokenHash || + !got.CreatedAt.Equal(want.CreatedAt) || !got.LastSeenAt.Equal(want.LastSeenAt) || + !got.ExpiresAt.Equal(want.ExpiresAt) || got.RevokedAt != nil { + t.Fatalf("session = %+v, want %+v", got, want) + } +} + +func assertRowCount(ctx context.Context, t *testing.T, pool *pgxpool.Pool, table pgx.Identifier, want int) { + t.Helper() + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM "+table.Sanitize()).Scan(&count); err != nil { + t.Fatalf("count rows in %s: %v", table.Sanitize(), err) + } + if count != want { + t.Fatalf("%s has %d rows, want %d", table.Sanitize(), count, want) + } +} + +// heldTransaction runs work in a transaction and keeps the transaction open +// until finish, so a test can act while its locks are held. +type heldTransaction struct { + held chan struct{} + release chan struct{} + finished chan struct{} + once sync.Once + err error + // afterRelease, when set before awaitHeld returns, runs in the same + // transaction after finish releases it. + afterRelease transactionFn +} + +// startHeldTransaction runs work in a transaction and then holds it open. +// After finish, the transaction runs afterRelease and commits when commit is +// true, or rolls back with errForcedRollback otherwise. +func startHeldTransaction( + ctx context.Context, + t *testing.T, + transactor outbound.Transactor, + work transactionFn, + commit bool, +) *heldTransaction { + t.Helper() + holder := &heldTransaction{ + held: make(chan struct{}), + release: make(chan struct{}), + finished: make(chan struct{}), + } + t.Cleanup(func() { _ = holder.finish() }) + go func() { + defer close(holder.finished) + holder.err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := work(ctx, unit); err != nil { + return err + } + close(holder.held) + select { + case <-holder.release: + case <-ctx.Done(): + return ctx.Err() + } + if holder.afterRelease != nil { + if err := holder.afterRelease(ctx, unit); err != nil { + return err + } + } + if !commit { + return errForcedRollback + } + return nil + }) + }() + return holder +} + +func (holder *heldTransaction) awaitHeld(ctx context.Context, t *testing.T) { + t.Helper() + select { + case <-holder.held: + case <-holder.finished: + t.Fatalf("held transaction finished before holding its locks: %v", holder.err) + case <-ctx.Done(): + t.Fatalf("wait for the held transaction: %v", ctx.Err()) + } +} + +// finish releases the transaction and returns its result. +func (holder *heldTransaction) finish() error { + holder.once.Do(func() { close(holder.release) }) + <-holder.finished + return holder.err +} diff --git a/backend/integration_test/invitation_accept_http_test.go b/backend/integration_test/invitation_accept_http_test.go new file mode 100644 index 0000000..a0fab53 --- /dev/null +++ b/backend/integration_test/invitation_accept_http_test.go @@ -0,0 +1,579 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationAcceptMigrationVersion adds the acceptance: its audit event, the + // contact grant, and the outcomes kept under the keys. + invitationAcceptMigrationVersion = 40 + invitationAcceptancesRetained = "invitation_acceptances_retained" + acceptTextVersion = "c4-2026-10-01" +) + +// candidateContactGrantHTTP is the contact grant as the candidate reads it. +type candidateContactGrantHTTP struct { + ID uuid.UUID `json:"id"` + Fields []string `json:"fields"` + Status string `json:"status"` + Readable bool `json:"readable"` + BlockedBy *string `json:"blocked_by"` + TermsVersion int64 `json:"terms_version"` + ConsentTextVersion string `json:"consent_text_version"` + GrantedAt string `json:"granted_at"` + RevokedAt *string `json:"revoked_at"` + RevocationReason *string `json:"revocation_reason"` +} + +func decodeContactGrantHTTP(t *testing.T, body candidateInvitationHTTPBody) candidateContactGrantHTTP { + t.Helper() + var grant candidateContactGrantHTTP + if err := json.Unmarshal(body.ContactGrant, &grant); err != nil { + t.Fatalf("decode contact grant %s: %v", body.ContactGrant, err) + } + return grant +} + +// invitationAcceptCounts are the rows that acceptances write for one +// invitation, the C4 consents of its candidate, and the outcomes kept under +// the keys. +type invitationAcceptCounts struct { + acceptedEvents, grants, c4Consents, outcomes int +} + +func readInvitationAcceptCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAcceptCounts { + t.Helper() + var counts invitationAcceptCounts + if err := harness.pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'accepted'), + (SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1), + (SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4'), + (SELECT count(*) FROM invitation_accept_results WHERE invitation_id = $1)`, + invitationID, candidateID).Scan(&counts.acceptedEvents, &counts.grants, &counts.c4Consents, &counts.outcomes); err != nil { + t.Fatalf("count the rows of an acceptance: %v", err) + } + return counts +} + +// parallelAcceptRequests sends every acceptance at once, each under its own +// key, and returns the responses in the order of the bodies. +func parallelAcceptRequests( + t *testing.T, + harness *invitationHTTPHarness, + path, origin string, + session organizationHTTPSession, + bodies, keys []string, +) []*httptest.ResponseRecorder { + t.Helper() + responses := make([]*httptest.ResponseRecorder, len(bodies)) + var group sync.WaitGroup + start := make(chan struct{}) + for index := range bodies { + group.Go(func() { + <-start + responses[index] = organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, bodies[index], origin, session, keys[index]) + }) + } + close(start) + group.Wait() + return responses +} + +// firstAcceptance is the acceptance that later cases of the test repeat. +type firstAcceptance struct { + candidate domain.User + invitation invitationHTTPBody + key string + body string +} + +func TestCandidateInvitationAcceptOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + owner := account("accept-owner@example.test", domain.ScenarioEmployer) + sessionOwner := loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionOwner, "accept-company") + var nameA string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil { + t.Fatalf("read organization name: %v", err) + } + + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, + organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} + // Every candidate publishes the card and holds a name, an email, and a phone + // number. Telegram is held by none of them. + publishCandidate := func(candidate domain.User) { + consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact), + Phone: confirmedDecision("+70000000000"), + Stack: privacyCohortConfirmedItems("go"), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary", + }), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}), + }, 0) + if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + } + // Seven published candidates form the visible cohort. Each case uses its own + // candidate, so the cases do not share the state of an invitation. + var candidates []domain.User + for index := range 7 { + candidate := account(fmt.Sprintf("accept-candidate-%d@example.test", index), domain.ScenarioCandidate) + candidates = append(candidates, candidate) + publishCandidate(candidate) + } + login := func(candidate domain.User) organizationHTTPSession { + return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + } + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("invitation-accept-key-%d", keySequence) + } + deliver := func(candidate domain.User) invitationHTTPBody { + t.Helper() + handle, err := harness.key.ForOrganization(orgA, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + draft := decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA), + invitationCreateJSON(t, handle, nil), sessionOwner, nextKey()), http.StatusCreated) + return decodeInvitationHTTP(t, request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations/%s/send", orgA, draft.ID), + fmt.Sprintf(`{"expected_version":%d}`, draft.Version), sessionOwner, nextKey()), http.StatusOK) + } + myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() } + acceptBody := func(version, terms int64, text string, fields ...string) string { + encoded, err := json.Marshal(map[string]any{ + "expected_version": version, "terms_version": terms, + "consent_c4": map[string]any{"text_version": text, "accepted": true, "fields": fields}, + }) + if err != nil { + t.Fatalf("marshal acceptance: %v", err) + } + return string(encoded) + } + accept := func(candidate domain.User, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder { + t.Helper() + return request(http.MethodPost, myPath(invitationID)+"/accept", body, login(candidate), key) + } + // raiseTerms stores the next terms version the way a later raise does, with + // a higher salary, and advances the invitation version by one. + raiseTerms := func(invitationID uuid.UUID) int64 { + t.Helper() + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO invitation_terms_versions (invitation_id, organization_id, version, terms, salary_from, salary_to, + salary_currency, salary_period, salary_tax_basis, created_at) + SELECT invitation_id, organization_id, 2, + jsonb_set(jsonb_set(terms, '{salary,salary_from}', '120000'::jsonb), '{salary,salary_to}', '160000'::jsonb), + 120000, 160000, salary_currency, salary_period, salary_tax_basis, $2 + FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, invitationID, harness.clock.Now()); err != nil { + t.Fatalf("store the raised terms: %v", err) + } + var version int64 + if err := harness.pool.QueryRow(ctx, ` + UPDATE invitations SET terms_version = 2, version = version + 1, updated_at = $2 + WHERE id = $1 RETURNING version`, invitationID, harness.clock.Now()).Scan(&version); err != nil { + t.Fatalf("raise the invitation: %v", err) + } + return version + } + candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker} + for _, candidate := range candidates { + candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address()) + } + requireNoCandidateData := func(label, text string) { + t.Helper() + for _, marker := range candidateMarkers { + if strings.Contains(text, marker) { + t.Errorf("%s contains the private marker %q: %s", label, marker, text) + } + } + for _, field := range []string{"candidate_id", "candidate_handle", "salary_fit", "salary_minimum", "full_name", "telegram", "email", "phone"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + + var first firstAcceptance + t.Run("an email-only acceptance stores one grant of that field and one consent", func(t *testing.T) { + candidate := candidates[0] + sent := deliver(candidate) + key := nextKey() + body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email") + response := accept(candidate, sent.ID, body, key) + accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("accept response", response.Body.String()) + grant := decodeContactGrantHTTP(t, accepted) + if accepted.State != "accepted" || accepted.Version != sent.Version+1 || accepted.TermsVersion != sent.TermsVersion || + accepted.RespondedAt == nil || accepted.Decline != nil || string(accepted.ContactConsent) != "null" || + accepted.ResponseDeadlineAt != *sent.ResponseDeadlineAt || accepted.Organization.Name != nameA { + t.Fatalf("accepted = %+v, want the accepted invitation with its deadline and no offer", accepted) + } + if !slices.Equal(grant.Fields, []string{"email"}) || grant.Status != "active" || grant.ConsentTextVersion != acceptTextVersion || + grant.TermsVersion != sent.TermsVersion || grant.RevokedAt != nil || grant.RevocationReason != nil { + t.Fatalf("grant = %+v, want the email only, active, under the current text", grant) + } + // The published profile is not hidden, so the grant is readable now. + if !grant.Readable || grant.BlockedBy != nil { + t.Fatalf("grant = %+v, want readable while the organization may read the profile", grant) + } + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 1}) { + t.Fatalf("acceptance stored %+v, want one event, one grant, one C4 consent, and one outcome", counts) + } + // The grant names the one selected kind, although the profile holds the + // phone number too, and the consent names the same kind. + var fields, consentFields []string + if err := harness.pool.QueryRow(ctx, ` + SELECT grant_row.fields, record.field_set + FROM contact_grants AS grant_row + JOIN consent_records AS record ON record.id = grant_row.consent_record_id + WHERE grant_row.source_invitation_id = $1`, sent.ID).Scan(&fields, &consentFields); err != nil { + t.Fatalf("read the grant and its consent: %v", err) + } + if !slices.Equal(fields, []string{"email"}) || !slices.Equal(consentFields, []string{"email"}) { + t.Fatalf("stored grant fields = %v and consent fields = %v, want the email only", fields, consentFields) + } + reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if decodeContactGrantHTTP(t, reread).ID != grant.ID || reread.Version != accepted.Version { + t.Fatalf("reread = %+v, want the same grant and version", reread) + } + first = firstAcceptance{candidate: candidate, invitation: sent, key: key, body: body} + }) + + t.Run("repeats replay the answer and a different choice is a state conflict", func(t *testing.T) { + if first.invitation.ID == uuid.Nil { + t.Fatal("the first acceptance did not run") + } + original := accept(first.candidate, first.invitation.ID, first.body, first.key) + if original.Code != http.StatusOK { + t.Fatalf("replay = %d %s, want the original 200", original.Code, original.Body.String()) + } + // The same request under a new key, with the older expected version, + // answers the accepted invitation without a second grant or event. + again := accept(first.candidate, first.invitation.ID, first.body, nextKey()) + if again.Code != http.StatusOK || again.Body.String() != original.Body.String() { + t.Fatalf("repeat = %d %s, want the same answer %s", again.Code, again.Body.String(), original.Body.String()) + } + // Another field set is a different acceptance that the grant refuses. + requireSessionProblem(t, accept(first.candidate, first.invitation.ID, + acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "email", "phone"), nextKey()), + http.StatusConflict, "state_conflict") + // A reused key with another body is refused and stores nothing. + requireSessionProblem(t, accept(first.candidate, first.invitation.ID, + acceptBody(first.invitation.Version, first.invitation.TermsVersion, acceptTextVersion, "phone"), first.key), + http.StatusUnprocessableEntity, "idempotency_key_reused") + // Three outcomes: the first acceptance, the repeat, and the refused field set. + if counts := readInvitationAcceptCounts(ctx, t, harness, first.invitation.ID, first.candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) { + t.Fatalf("repeats stored %+v, want the first acceptance, its repeat, and the refusal", counts) + } + }) + + t.Run("a stale terms version is refused and nothing is stored, and the raised terms are accepted", func(t *testing.T) { + candidate := candidates[1] + sent := deliver(candidate) + raisedVersion := raiseTerms(sent.ID) + // The candidate read the terms of version 1: 412, nothing stored. + requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()), + http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) { + t.Fatalf("a stale terms version stored %+v", counts) + } + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if read.TermsVersion != 2 || read.Version != raisedVersion || read.State != "delivered" { + t.Fatalf("read after the raise = %+v, want the new terms and the delivered state", read) + } + accepted := decodeCandidateInvitationHTTP(t, accept(candidate, sent.ID, acceptBody(raisedVersion, 2, acceptTextVersion, "email"), nextKey()), http.StatusOK) + if accepted.State != "accepted" || accepted.TermsVersion != 2 || decodeContactGrantHTTP(t, accepted).TermsVersion != 2 { + t.Fatalf("accepted = %+v, want the raised terms version accepted", accepted) + } + // The old terms version is a different acceptance once the grant exists. + requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(raisedVersion, sent.TermsVersion, acceptTextVersion, "email"), nextKey()), + http.StatusConflict, "state_conflict") + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 2}) { + t.Fatalf("raised acceptance stored %+v, want one acceptance, one grant, one consent, and the refusal", counts) + } + }) + + t.Run("concurrent acceptances make one transition and one grant", func(t *testing.T) { + candidate := candidates[2] + sent := deliver(candidate) + session := login(candidate) + path := myPath(sent.ID) + "/accept" + body := acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email") + responses := parallelAcceptRequests(t, harness, path, origin, session, + []string{body, body, body}, []string{nextKey(), nextKey(), nextKey()}) + var answers []string + for _, response := range responses { + accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + if accepted.State != "accepted" { + t.Fatalf("concurrent answer = %+v, want accepted", accepted) + } + answers = append(answers, response.Body.String()) + } + if !slices.Equal(answers[1:], answers[:len(answers)-1]) { + t.Fatalf("concurrent answers differ: %v", answers) + } + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{acceptedEvents: 1, grants: 1, c4Consents: 1, outcomes: 3}) { + t.Fatalf("concurrent acceptances stored %+v, want one transition, one grant, one consent", counts) + } + + // Two different field sets race: one transition, the other a conflict. + other := candidates[3] + raced := deliver(other) + responses = parallelAcceptRequests(t, harness, myPath(raced.ID)+"/accept", origin, login(other), + []string{ + acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "email"), + acceptBody(raced.Version, raced.TermsVersion, acceptTextVersion, "phone"), + }, []string{nextKey(), nextKey()}) + statuses := []int{responses[0].Code, responses[1].Code} + slices.Sort(statuses) + if !slices.Equal(statuses, []int{http.StatusOK, http.StatusConflict}) { + t.Fatalf("raced acceptances = %v, want one 200 and one 409 state_conflict", statuses) + } + if counts := readInvitationAcceptCounts(ctx, t, harness, raced.ID, other.ID); counts.acceptedEvents != 1 || counts.grants != 1 || counts.c4Consents != 1 { + t.Fatalf("raced acceptances stored %+v, want one transition, one grant, one consent", counts) + } + }) + + t.Run("a hidden organization accepts without changing the publication or the hiding", func(t *testing.T) { + candidate := candidates[4] + sent := deliver(candidate) + privacy.hide(t, candidate.ID, orgA, harness.clock.Now()) + publication := privacy.rawPublication(t, candidate.ID) + hidden := privacy.rawHidden(t, candidate.ID) + response := accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email"), nextKey()) + accepted := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + grant := decodeContactGrantHTTP(t, accepted) + if grant.Readable || grant.BlockedBy == nil || *grant.BlockedBy != "visibility" || len(grant.Fields) != 1 { + t.Fatalf("grant while hidden = %+v, want stored and blocked by visibility", grant) + } + if after := privacy.rawPublication(t, candidate.ID); after != publication { + t.Fatalf("the acceptance changed the publication: %s became %s", publication, after) + } + if after := privacy.rawHidden(t, candidate.ID); after != hidden { + t.Fatalf("the acceptance changed the hiding: %s became %s", hidden, after) + } + // The candidate removes the hiding; the same grant becomes readable. + if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, + candidate.ID, orgA); err != nil { + t.Fatalf("unhide the organization: %v", err) + } + reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if grantRead := decodeContactGrantHTTP(t, reread); grantRead.ID != grant.ID || !grantRead.Readable || grantRead.BlockedBy != nil { + t.Fatalf("grant after unhiding = %+v, want the same grant readable", grantRead) + } + }) + + t.Run("a late acceptance is refused under its key whatever the version", func(t *testing.T) { + candidate := candidates[5] + sent := deliver(candidate) + var deadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&deadline); err != nil { + t.Fatalf("read the deadline: %v", err) + } + harness.clock.Set(deadline.UTC()) + key := nextKey() + for range 2 { + requireSessionProblem(t, accept(candidate, sent.ID, acceptBody(sent.Version+5, sent.TermsVersion, acceptTextVersion, "email"), key), + http.StatusConflict, "state_conflict") + } + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{outcomes: 1}) { + t.Fatalf("late acceptances stored %+v, want one state_conflict outcome and nothing else", counts) + } + }) + + t.Run("the consent text and the held kinds are checked before anything is stored", func(t *testing.T) { + // The late case moved the clock to a deadline, which ends the owner session. + sessionOwner = loginOrganizationHTTP(t, harness.sessionHTTPHarness, owner.Email.Address()) + candidate := candidates[6] + sent := deliver(candidate) + requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, "c4-2025-01-01", "email"), nextKey()), + "/consent_c4/text_version", "") + requireInvitationValidation(t, accept(candidate, sent.ID, acceptBody(sent.Version, sent.TermsVersion, acceptTextVersion, "email", "telegram"), nextKey()), + "/consent_c4/fields/1", "") + if counts := readInvitationAcceptCounts(ctx, t, harness, sent.ID, candidate.ID); counts != (invitationAcceptCounts{}) { + t.Fatalf("refused consent stored %+v", counts) + } + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", login(candidate), ""), http.StatusOK) + if read.State != "delivered" || string(read.ContactGrant) != "null" { + t.Fatalf("read after the refusals = %+v, want the delivered invitation without a grant", read) + } + }) + + t.Run("the acceptance answers stay out of the server log", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + }) +} + +func TestInvitationAcceptMigrationGuardsAcceptancesAndRefusesRollback(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + // The fixture creates an organization with the schema of the current head. + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + // Migrations added after this one are not part of this guard: the test + // rolls them back, so that this migration is the one rolled back below. + rollBackAboveVersion(ctx, t, migrator, invitationAcceptMigrationVersion) + store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error { + t.Helper() + return fixture.transactor.WithinTransaction(ctx, work) + } + deliverDraft := func(t *testing.T) domain.Invitation { + t.Helper() + draft := fixture.draft(t) + delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + return delivered + } + + delivered := deliverDraft(t) + acceptedAt := delivered.UpdatedAt().Add(time.Minute) + accepted, err := delivered.Accept(delivered.TermsVersion(), acceptedAt) + if err != nil { + t.Fatalf("Accept() error = %v", err) + } + acceptEvent, err := accepted.AnswerEvent(fixture.candidate.ID) + if err != nil { + t.Fatalf("AnswerEvent() error = %v", err) + } + fields, err := domain.NewContactFieldSet(domain.ContactFieldEmail) + if err != nil { + t.Fatalf("NewContactFieldSet() error = %v", err) + } + consents := consent.NewService(fixture.transactor, func() time.Time { return acceptedAt }) + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Invitations().Accept(ctx, delivered.Version(), accepted, acceptEvent); err != nil { + return err + } + granted, err := consents.GrantContact(ctx, unit, consent.ContactGrantInput{ + SubjectID: fixture.candidate.ID, OrganizationID: fixture.organization.ID(), OrganizationName: fixture.organization.Profile().Name(), + Fields: fields, InvitationID: delivered.ID(), InvitationTermsVersion: delivered.TermsVersion(), TextVersion: acceptTextVersion, + }) + if err != nil { + return err + } + grant, err := domain.NewContactGrant(granted.Record, accepted) + if err != nil { + return err + } + return unit.ContactGrants().Create(ctx, grant) + }); err != nil { + t.Fatalf("accept through the repositories error = %v", err) + } + + // The database guards the acceptance and its grant against other writers. + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', responded_at = NULL, version = version + 1 WHERE id = $1`, delivered.ID()) + assertPgError(t, "leave the acceptance", err, privacyIntegrityViolation, "invitations_answer_immutable") + _, err = pool.Exec(ctx, `UPDATE contact_grants SET fields = '{phone}' WHERE source_invitation_id = $1`, delivered.ID()) + assertPgError(t, "change the grant", err, privacyIntegrityViolation, "contact_grants_immutable") + _, err = pool.Exec(ctx, `DELETE FROM contact_grants WHERE source_invitation_id = $1`, delivered.ID()) + assertPgError(t, "delete the grant", err, privacyIntegrityViolation, "contact_grants_immutable") + _, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at) + SELECT $1, id, organization_id, version + 1, terms_version, 'accepted', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), delivered.ID()) + assertPgError(t, "accepted event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field") + + // An acceptance without its grant cannot commit. + other := deliverDraft(t) + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'accepted', responded_at = delivered_at + interval '1 minute', + updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID()) + assertPgError(t, "accepted without a grant", err, privacyIntegrityViolation, "invitations_acceptance_recorded") + + _, err = migrator.DownOne(ctx) + assertPgError(t, "DownOne() with an accepted invitation", err, privacyIntegrityViolation, invitationAcceptancesRetained) + // The database is isolated to this test: CASCADE also clears the tables that + // refer to the consent ledger, such as the publication history of C2. + if _, err := pool.Exec(ctx, `TRUNCATE consent_records, invitations, invitation_accept_results, invitation_decline_results, + invitation_send_results, invitation_creation_results CASCADE`); err != nil { + t.Fatalf("clear the invitation tables: %v", err) + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != invitationAcceptMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAcceptMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('contact_grants', 'invitation_accept_results')`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("acceptance tables left after the rollback: %d, %v", remaining, err) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/invitation_answer_http_test.go b/backend/integration_test/invitation_answer_http_test.go new file mode 100644 index 0000000..eb443c9 --- /dev/null +++ b/backend/integration_test/invitation_answer_http_test.go @@ -0,0 +1,672 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationAnswerMigrationVersion adds the view and the decline: their + // audit events, the stored decline, and the stored decline outcomes. + invitationAnswerMigrationVersion = 39 + invitationAnswersRetained = "invitation_answers_retained" + // invitationDeclineComment is the candidate's private comment. It is + // read back by the candidate only. + invitationDeclineComment = "Private decline comment of the candidate" +) + +// candidateInvitationHTTPBody is the invitation as the candidate reads it. +type candidateInvitationHTTPBody struct { + ID uuid.UUID `json:"id"` + Organization struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + } `json:"organization"` + State string `json:"state"` + ExpiryReason *string `json:"expiry_reason"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + Terms json.RawMessage `json:"terms"` + ResponseDeadlineAt string `json:"response_deadline_at"` + DeliveredAt string `json:"delivered_at"` + ViewedAt *string `json:"viewed_at"` + RespondedAt *string `json:"responded_at"` + UpdatedAt string `json:"updated_at"` + ContactConsent json.RawMessage `json:"contact_consent"` + Decline *struct { + Reason string `json:"reason"` + Comment *string `json:"comment"` + DeclinedAt string `json:"declined_at"` + } `json:"decline"` + ContactGrant json.RawMessage `json:"contact_grant"` +} + +func decodeCandidateInvitationHTTP(t *testing.T, response *httptest.ResponseRecorder, wantStatus int) candidateInvitationHTTPBody { + t.Helper() + if response.Code != wantStatus { + t.Fatalf("response = %d %s, want %d", response.Code, response.Body.String(), wantStatus) + } + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + var body candidateInvitationHTTPBody + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode candidate invitation %s: %v", response.Body.String(), err) + } + return body +} + +// invitationAnswerCounts are the rows that a view or a decline may write for +// one invitation, and the C4 consents of its candidate, which neither may +// create. +type invitationAnswerCounts struct { + viewedEvents, declinedEvents, declines, c4Consents int +} + +func readInvitationAnswerCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationAnswerCounts { + t.Helper() + var counts invitationAnswerCounts + if err := harness.pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'viewed'), + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'declined'), + (SELECT count(*) FROM invitation_declines WHERE invitation_id = $1), + (SELECT count(*) FROM consent_records WHERE subject_id = $2 AND purpose = 'c4')`, + invitationID, candidateID).Scan(&counts.viewedEvents, &counts.declinedEvents, &counts.declines, &counts.c4Consents); err != nil { + t.Fatalf("count the rows of an answer: %v", err) + } + return counts +} + +func TestCandidateInvitationViewAndDeclineOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA, ownerB := account("answer-owner-a@example.test", domain.ScenarioEmployer), account("answer-owner-b@example.test", domain.ScenarioEmployer) + sessionA := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()) + sessionB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "answer-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "answer-company-b") + var nameA string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil { + t.Fatalf("read organization name: %v", err) + } + + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, + organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} + publishCandidate := func(candidate domain.User) { + consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact), + Stack: privacyCohortConfirmedItems("go"), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary", + }), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}), + }, 0) + if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + } + // Seven published candidates form the visible cohort. The first three + // can sign in. + target := account("answer-target@example.test", domain.ScenarioCandidate) + other := account("answer-other@example.test", domain.ScenarioCandidate) + hider := account("answer-hider@example.test", domain.ScenarioCandidate) + cohort := []domain.User{target, other, hider} + for index := range 4 { + candidate := privacy.candidate(t, fmt.Sprintf("answer-visible-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, privacy, candidate) + cohort = append(cohort, candidate) + } + for _, candidate := range cohort { + publishCandidate(candidate) + } + login := func(candidate domain.User) organizationHTTPSession { + return loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address()) + } + sessionTarget, sessionOther, sessionHider := login(target), login(other), login(hider) + + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("invitation-answer-key-%d", keySequence) + } + alias := func(organizationID uuid.UUID, candidate domain.User) string { + t.Helper() + handle, err := harness.key.ForOrganization(organizationID, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle + } + organizationPath := func(organizationID, invitationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) + } + draftFor := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + response := request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID), + invitationCreateJSON(t, alias(organizationID, candidate), change), session, nextKey()) + return decodeInvitationHTTP(t, response, http.StatusCreated) + } + deliver := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + draft := draftFor(organizationID, session, candidate, change) + response := request(http.MethodPost, organizationPath(organizationID, draft.ID)+"/send", fmt.Sprintf(`{"expected_version":%d}`, draft.Version), session, nextKey()) + return decodeInvitationHTTP(t, response, http.StatusOK) + } + myPath := func(invitationID uuid.UUID) string { return "/api/v1/me/invitations/" + invitationID.String() } + declineBody := func(version int64, reason string, comment *string) string { + body := map[string]any{"expected_version": version, "reason": reason} + if comment != nil { + body["comment"] = *comment + } + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal decline: %v", err) + } + return string(encoded) + } + decline := func(session organizationHTTPSession, invitationID uuid.UUID, body, key string) *httptest.ResponseRecorder { + return request(http.MethodPost, myPath(invitationID)+"/decline", body, session, key) + } + candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker} + for _, candidate := range cohort { + candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address()) + } + requireNoCandidateData := func(label, text string) { + t.Helper() + for _, marker := range candidateMarkers { + if strings.Contains(text, marker) { + t.Errorf("%s contains the private marker %q: %s", label, marker, text) + } + } + for _, field := range []string{"candidate_id", "candidate_handle", "salary_fit", "email", "phone", "telegram", "full_name", "salary_minimum"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + requireNoDeclineDetails := func(label, text string) { + t.Helper() + for _, private := range []string{invitationDeclineComment, `"decline"`, `"reason"`, `"comment"`} { + if strings.Contains(text, private) { + t.Errorf("%s discloses the decline detail %s: %s", label, private, text) + } + } + } + + t.Run("opening the terms records the view and keeps the deadline", func(t *testing.T) { + sent := deliver(orgA, sessionA, target, nil) + read := request(http.MethodGet, myPath(sent.ID), "", sessionTarget, "") + opened := decodeCandidateInvitationHTTP(t, read, http.StatusOK) + requireNoCandidateData("candidate read", read.Body.String()) + // While an acceptance is possible the read offers the consent C4 with + // the kinds that the profile holds, and no grant exists yet. + var offer struct { + Text struct { + TextVersion string `json:"text_version"` + Text string `json:"text"` + } `json:"text"` + AvailableFields []string `json:"available_fields"` + } + if err := json.Unmarshal(opened.ContactConsent, &offer); err != nil { + t.Fatalf("decode contact consent %s: %v", opened.ContactConsent, err) + } + if strings.Contains(offer.Text.Text, "{organization}") || !strings.Contains(offer.Text.Text, nameA) || + offer.Text.TextVersion != "c4-2026-10-01" || !slices.Equal(offer.AvailableFields, []string{"full_name", "email"}) { + t.Fatalf("contact consent = %+v, want the C4 text for the organization and the held kinds", offer) + } + if opened.State != "delivered" || opened.Version != sent.Version || opened.ViewedAt != nil || opened.Organization.ID != orgA || + opened.Organization.Name != nameA || opened.ResponseDeadlineAt != *sent.ResponseDeadlineAt || opened.Decline != nil || + string(opened.ContactGrant) != "null" || len(opened.Terms) == 0 { + t.Fatalf("read = %+v, want the delivered invitation with its terms and no side effect", opened) + } + // A read records nothing: it is free of side effects by contract. + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts.viewedEvents != 0 { + t.Fatalf("a read stored %+v", counts) + } + + harness.clock.Advance(time.Hour) + response := request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionTarget, "") + viewed := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("view response", response.Body.String()) + if viewed.State != "viewed" || viewed.Version != sent.Version+1 || viewed.TermsVersion != sent.TermsVersion || viewed.ViewedAt == nil || + viewed.ResponseDeadlineAt != opened.ResponseDeadlineAt || viewed.DeliveredAt != opened.DeliveredAt { + t.Fatalf("viewed = %+v, want viewed with the same deadline %s", viewed, opened.ResponseDeadlineAt) + } + var storedDeadline, storedDelivered time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at, delivered_at FROM invitations WHERE id = $1`, sent.ID). + Scan(&storedDeadline, &storedDelivered); err != nil || !storedDeadline.Equal(storedDelivered.Add(7*24*time.Hour)) { + t.Fatalf("stored deadline = %s after %s, %v; want seven days after the delivery", storedDeadline, storedDelivered, err) + } + + // Repeats, concurrent ones included, change nothing and record one + // event. + harness.clock.Advance(time.Hour) + for _, repeat := range parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/view", "", origin, sessionTarget, "", 3) { + again := decodeCandidateInvitationHTTP(t, repeat, http.StatusOK) + if again.Version != viewed.Version || *again.ViewedAt != *viewed.ViewedAt { + t.Fatalf("repeated view = %+v, want the first view", again) + } + } + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1}) { + t.Fatalf("views stored %+v, want one view event", counts) + } + // The organization sees the state and the time of the view only. + organization := decodeInvitationHTTP(t, request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, ""), http.StatusOK) + if organization.State != "viewed" || organization.ViewedAt == nil || *organization.ViewedAt != *viewed.ViewedAt || + organization.ResponseDeadlineAt == nil || *organization.ResponseDeadlineAt != viewed.ResponseDeadlineAt { + t.Fatalf("organization reads %+v, want the view and the same deadline", organization) + } + // The inbox shows the view as well. + listed := request(http.MethodGet, "/api/v1/me/invitations", "", sessionTarget, "") + if listed.Code != http.StatusOK || !strings.Contains(listed.Body.String(), `"state":"viewed"`) { + t.Fatalf("inbox = %d %s, want the viewed invitation", listed.Code, listed.Body.String()) + } + }) + + t.Run("a decline with the reason other and no comment is an answer without a grant", func(t *testing.T) { + sent := deliver(orgA, sessionA, other, nil) + harness.clock.Advance(time.Minute) + key := nextKey() + response := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), key) + declined := decodeCandidateInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("decline response", response.Body.String()) + if declined.State != "declined" || declined.Version != sent.Version+1 || declined.RespondedAt == nil || declined.Decline == nil || + declined.Decline.Reason != "other" || declined.Decline.Comment != nil || declined.Decline.DeclinedAt != *declined.RespondedAt || + string(declined.ContactConsent) != "null" || string(declined.ContactGrant) != "null" || + declined.ResponseDeadlineAt != *sent.ResponseDeadlineAt { + t.Fatalf("declined = %+v, want declined with the reason other, no comment, and no grant", declined) + } + counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID) + if counts != (invitationAnswerCounts{declinedEvents: 1, declines: 1}) { + t.Fatalf("decline stored %+v, want one decline event, one decline, and no C4 consent", counts) + } + // The stored answer event is the response that the responsiveness + // metrics count: in time, by the candidate, without a reason. + var actor uuid.UUID + var occurred, deadline time.Time + var fields int + if err := harness.pool.QueryRow(ctx, ` + SELECT event.actor_id, event.occurred_at, invitation.response_deadline_at, cardinality(event.changed_fields) + FROM invitation_events AS event JOIN invitations AS invitation ON invitation.id = event.invitation_id + WHERE event.invitation_id = $1 AND event.kind = 'declined'`, sent.ID).Scan(&actor, &occurred, &deadline, &fields); err != nil { + t.Fatalf("read the decline event: %v", err) + } + if actor != other.ID || !occurred.Before(deadline) || fields != 0 { + t.Fatalf("decline event by the candidate %v at %s before %s with %d fields", actor == other.ID, occurred, deadline, fields) + } + + // Repeats: the same key replays the original, and the same decline + // with a new key and the older version answers 200 without a second + // event. Another reason or a reused key with another body does not. + original := response.Body.String() + harness.clock.Advance(time.Hour) + if replay := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), key); replay.Code != http.StatusOK || replay.Body.String() != original { + t.Fatalf("replay = %d %s, want the original 200", replay.Code, replay.Body.String()) + } + if again := decline(sessionOther, sent.ID, declineBody(sent.Version, "other", nil), nextKey()); again.Code != http.StatusOK || again.Body.String() != original { + t.Fatalf("the same decline with a new key = %d %s, want the original answer", again.Code, again.Body.String()) + } + requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(declined.Version, "salary", nil), nextKey()), http.StatusConflict, "state_conflict") + requireSessionProblem(t, decline(sessionOther, sent.ID, declineBody(sent.Version, "stack", nil), key), http.StatusUnprocessableEntity, "idempotency_key_reused") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, other.ID); counts != (invitationAnswerCounts{declinedEvents: 1, declines: 1}) { + t.Fatalf("repeats stored %+v, want the first decline only", counts) + } + // A view of a declined invitation changes nothing. + if viewed := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionOther, ""), http.StatusOK); viewed.State != "declined" || viewed.Version != declined.Version { + t.Fatalf("view of a declined invitation = %+v", viewed) + } + + // The organization sees the state and the time of the answer only. + organizationRead := request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, "") + organization := decodeInvitationHTTP(t, organizationRead, http.StatusOK) + requireNoDeclineDetails("organization read", organizationRead.Body.String()) + listed := request(http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/invitations", orgA), "", sessionA, "") + requireNoDeclineDetails("organization list", listed.Body.String()) + if organization.State != "declined" || organization.RespondedAt == nil || *organization.RespondedAt != *declined.RespondedAt || + organization.ContactAccess.Status != "not_granted" { + t.Fatalf("organization reads %+v, want declined with the time of the answer and no access", organization) + } + }) + + t.Run("a decline from viewed keeps the comment for the candidate only", func(t *testing.T) { + sent := deliver(orgA, sessionA, target, nil) + viewed := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", sessionTarget, ""), http.StatusOK) + comment := invitationDeclineComment + key := nextKey() + // Concurrent requests with one key answer once. + responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/decline", + declineBody(viewed.Version, "salary", &comment), origin, sessionTarget, key, 2) + if responses[0].Code != http.StatusOK || responses[0].Body.String() != responses[1].Body.String() { + t.Fatalf("concurrent declines = %d %s and %d %s, want one identical 200", + responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + declined := decodeCandidateInvitationHTTP(t, responses[0], http.StatusOK) + if declined.State != "declined" || declined.Decline == nil || declined.Decline.Reason != "salary" || + declined.Decline.Comment == nil || *declined.Decline.Comment != comment { + t.Fatalf("declined = %+v, want the reason and the comment read back", declined) + } + reread := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", sessionTarget, ""), http.StatusOK) + if reread.Decline == nil || reread.Decline.Comment == nil || *reread.Decline.Comment != comment || reread.Version != declined.Version { + t.Fatalf("reread = %+v, want the stored decline", reread) + } + organizationRead := request(http.MethodGet, organizationPath(orgA, sent.ID), "", sessionA, "") + requireNoDeclineDetails("organization read", organizationRead.Body.String()) + var events string + if err := harness.pool.QueryRow(ctx, `SELECT string_agg(row_to_json(invitation_events)::text, ' ') FROM invitation_events WHERE invitation_id = $1`, sent.ID).Scan(&events); err != nil { + t.Fatalf("read the audit events: %v", err) + } + if strings.Contains(events, comment) || strings.Contains(events, "salary") { + t.Fatalf("audit events hold the decline details: %s", events) + } + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{viewedEvents: 1, declinedEvents: 1, declines: 1}) { + t.Fatalf("decline from viewed stored %+v", counts) + } + // The comment rules of the contract and an unstorable value. The pause + // after the declines above holds their candidates for thirty days, so + // the new invitation goes to a cohort candidate that never declined. + fresh := deliver(orgA, sessionA, cohort[len(cohort)-1], nil) + tooLong := strings.Repeat("я", 501) + for name, body := range map[string]string{ + "white space": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":" "}`, + "unicode spaces": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":"  "}`, + "NUL": `{"expected_version":` + fmt.Sprint(fresh.Version) + `,"reason":"other","comment":"a\u0000b"}`, + "too long": declineBody(fresh.Version, "other", &tooLong), + } { + response := decline(sessionTarget, fresh.ID, body, nextKey()) + if response.Code != http.StatusBadRequest { + t.Errorf("%s: decline = %d %s, want 400", name, response.Code, response.Body.String()) + } + } + requireInvitationValidation(t, decline(sessionTarget, fresh.ID, `{"expected_version":1,"reason":"rude"}`, nextKey()), "/reason", "") + requireInvitationValidation(t, decline(sessionTarget, fresh.ID, `{"expected_version":1,"reason":"other","state":"declined"}`, nextKey()), "", "") + requireInvitationValidation(t, decline(sessionTarget, fresh.ID, declineBody(fresh.Version, "other", nil), ""), "/Idempotency-Key", "") + if counts := readInvitationAnswerCounts(ctx, t, harness, fresh.ID, target.ID); counts.declines != 0 { + t.Fatalf("an invalid decline stored %+v", counts) + } + }) + + t.Run("another candidate and an employer learn nothing of the invitation", func(t *testing.T) { + // The sent invitation goes to a cohort candidate that never declined, so + // the pause after the declines above does not apply to it. Only the draft + // below is addressed to the candidate who declined. + sent := deliver(orgA, sessionA, cohort[len(cohort)-2], nil) + draft := draftFor(orgA, sessionA, target, nil) + for name, invitationID := range map[string]uuid.UUID{"another candidate's": sent.ID, "unknown": uuid.New()} { + for _, response := range []*httptest.ResponseRecorder{ + request(http.MethodGet, myPath(invitationID), "", sessionOther, ""), + request(http.MethodPost, myPath(invitationID)+"/view", "", sessionOther, ""), + decline(sessionOther, invitationID, declineBody(sent.Version, "other", nil), nextKey()), + } { + requireSessionProblem(t, response, http.StatusNotFound, "not_found") + if strings.Contains(response.Body.String(), "role_title") || strings.Contains(response.Body.String(), nameA) { + t.Errorf("%s invitation: the refusal shows the terms: %s", name, response.Body.String()) + } + } + } + // A draft is not in the candidate's inbox, even for its candidate. + requireSessionProblem(t, request(http.MethodGet, myPath(draft.ID), "", sessionTarget, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPost, myPath(draft.ID)+"/view", "", sessionTarget, ""), http.StatusNotFound, "not_found") + // The sending organization and another one have no candidate inbox. + for _, session := range []organizationHTTPSession{sessionA, sessionB} { + requireSessionProblem(t, request(http.MethodGet, myPath(sent.ID), "", session, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", session, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, decline(session, sent.ID, declineBody(sent.Version, "other", nil), nextKey()), http.StatusForbidden, "forbidden") + } + // Unsafe commands need the session's CSRF token and the exact Origin. + withoutToken := organizationHTTPSession{cookie: sessionTarget.cookie} + requireSessionProblem(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", withoutToken, ""), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, decline(withoutToken, sent.ID, declineBody(sent.Version, "other", nil), nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, myPath(sent.ID)+"/decline", + declineBody(sent.Version, "other", nil), "https://attacker.example", sessionTarget, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodGet, myPath(sent.ID), "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") + requireInvitationValidation(t, request(http.MethodGet, "/api/v1/me/invitations/1", "", sessionTarget, ""), "/invitation_id", "") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, target.ID); counts != (invitationAnswerCounts{}) { + t.Fatalf("refused callers stored %+v", counts) + } + // The candidate's own list never names another candidate's invitation. + listed := request(http.MethodGet, "/api/v1/me/invitations?limit=100", "", sessionOther, "") + if listed.Code != http.StatusOK || strings.Contains(listed.Body.String(), sent.ID.String()) || strings.Contains(listed.Body.String(), draft.ID.String()) { + t.Fatalf("another candidate's list = %d %s", listed.Code, listed.Body.String()) + } + }) + + t.Run("the hiding of the organization does not hide it from the candidate", func(t *testing.T) { + sent := deliver(orgB, sessionB, hider, nil) + privacy.hide(t, hider.ID, orgB, harness.clock.Now()) + read := decodeCandidateInvitationHTTP(t, request(http.MethodGet, myPath(sent.ID), "", sessionHider, ""), http.StatusOK) + if read.Organization.ID != orgB || read.Organization.Name == "" { + t.Fatalf("read after the hiding = %+v, want the sending organization", read.Organization) + } + declined := decodeCandidateInvitationHTTP(t, decline(sessionHider, sent.ID, declineBody(sent.Version, "company", nil), nextKey()), http.StatusOK) + if declined.State != "declined" { + t.Fatalf("decline after the hiding = %+v", declined) + } + }) + + t.Run("a stale version is not stored and a late decline is refused whatever the version", func(t *testing.T) { + // Hider has no other invitation of this organization, so the pause after + // the declines above does not apply to it. + sent := deliver(orgA, sessionA, hider, func(body, terms map[string]any) { body["response_period_days"] = 3 }) + key := nextKey() + requireSessionProblem(t, decline(sessionHider, sent.ID, declineBody(sent.Version+1, "tasks", nil), key), http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, hider.ID); counts.declines != 0 { + t.Fatalf("a stale decline stored %+v", counts) + } + var stored int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1`, sent.ID).Scan(&stored); err != nil || stored != 0 { + t.Fatalf("stale outcomes = %d, %v; want none", stored, err) + } + + // At the deadline the view changes nothing and the decline is late: + // 409 even with a stale version, stored under its key. + // The response shows whole seconds, so the exact stored deadline is + // read from the database. + var exactDeadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT response_deadline_at FROM invitations WHERE id = $1`, sent.ID).Scan(&exactDeadline); err != nil { + t.Fatalf("read the deadline: %v", err) + } + harness.clock.Set(exactDeadline.UTC()) + lateSession := login(hider) + // The late view applies the due expiry, so it answers with the expired + // invitation and records no view. + late := decodeCandidateInvitationHTTP(t, request(http.MethodPost, myPath(sent.ID)+"/view", "", lateSession, ""), http.StatusOK) + if late.State != "expired" || late.ExpiryReason == nil || *late.ExpiryReason != "invitation_timeout" || + late.Version != sent.Version+1 || late.ViewedAt != nil { + t.Fatalf("late view = %+v, want the invitation expired by the timeout without a view", late) + } + lateKey := nextKey() + for range 2 { + requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(late.Version+2, "tasks", nil), lateKey), http.StatusConflict, "state_conflict") + } + requireSessionProblem(t, decline(lateSession, sent.ID, declineBody(sent.Version, "tasks", nil), key), http.StatusConflict, "state_conflict") + if counts := readInvitationAnswerCounts(ctx, t, harness, sent.ID, hider.ID); counts != (invitationAnswerCounts{}) { + t.Fatalf("late commands stored %+v", counts) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitation_decline_results WHERE invitation_id = $1 AND outcome = 'state_conflict'`, sent.ID).Scan(&stored); err != nil || stored != 2 { + t.Fatalf("stored late refusals = %d, %v; want one per key", stored, err) + } + }) + + t.Run("keeps the decline comment and candidate values out of logs", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + if strings.Contains(harness.logs.String(), invitationDeclineComment) { + t.Fatal("the server log holds the decline comment") + } + }) +} + +func TestInvitationAnswerMigrationGuardsAnswersAndRefusesRollback(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + rollBackAboveVersion(ctx, t, migrator, invitationAnswerMigrationVersion) + + store := func(t *testing.T, work func(context.Context, outbound.UnitOfWork) error) error { + t.Helper() + return fixture.transactor.WithinTransaction(ctx, work) + } + deliverDraft := func(t *testing.T) domain.Invitation { + t.Helper() + draft := fixture.draft(t) + delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + return delivered + } + + delivered := deliverDraft(t) + viewed, _, err := delivered.RecordView(delivered.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("RecordView() error = %v", err) + } + viewEvent, err := viewed.AnswerEvent(fixture.candidate.ID) + if err != nil { + t.Fatalf("AnswerEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().RecordView(ctx, delivered.Version(), viewed, viewEvent) + }); err != nil { + t.Fatalf("RecordView() through the repository error = %v", err) + } + // A second view of the same version loses the race. + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().RecordView(ctx, delivered.Version(), viewed, viewEvent) + }); !errors.Is(err, outbound.ErrInvitationVersionConflict) { + t.Fatalf("second RecordView() error = %v, want ErrInvitationVersionConflict", err) + } + comment := "Synthetic decline comment" + declined, declineRecord, err := viewed.Decline(domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther, Comment: &comment}, viewed.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Decline() error = %v", err) + } + declineEvent, err := declined.AnswerEvent(fixture.candidate.ID) + if err != nil { + t.Fatalf("AnswerEvent() error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Decline(ctx, viewed.Version(), declined, declineRecord, declineEvent) + }); err != nil { + t.Fatalf("Decline() through the repository error = %v", err) + } + if err := store(t, func(ctx context.Context, unit outbound.UnitOfWork) error { + read, err := unit.Invitations().GetDecline(ctx, declined.OrganizationID(), declined.ID()) + if err == nil && (!read.Choice.Equal(declineRecord.Choice) || !read.DeclinedAt.Equal(declineRecord.DeclinedAt)) { + return fmt.Errorf("stored decline differs: %v", read.Choice.Reason) + } + return err + }); err != nil { + t.Fatalf("GetDecline() error = %v", err) + } + + // The database guards the answers against other writers. + _, err = pool.Exec(ctx, `UPDATE invitations SET viewed_at = viewed_at + interval '1 second', version = version + 1 WHERE id = $1`, declined.ID()) + assertPgError(t, "move the view", err, privacyIntegrityViolation, "invitations_answer_immutable") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'viewed', responded_at = NULL, version = version + 1 WHERE id = $1`, declined.ID()) + assertPgError(t, "leave the decline", err, privacyIntegrityViolation, "invitations_answer_immutable") + _, err = pool.Exec(ctx, `UPDATE invitation_declines SET reason = 'salary' WHERE invitation_id = $1`, declined.ID()) + assertPgError(t, "change the decline", err, privacyIntegrityViolation, "invitation_declines_immutable") + _, err = pool.Exec(ctx, `DELETE FROM invitation_declines WHERE invitation_id = $1`, declined.ID()) + assertPgError(t, "delete the decline", err, privacyIntegrityViolation, "invitation_declines_immutable") + other := deliverDraft(t) + _, err = pool.Exec(ctx, `INSERT INTO invitation_declines (invitation_id, organization_id, reason, declined_at) VALUES ($1, $2, 'other', now())`, + other.ID(), other.OrganizationID()) + assertPgError(t, "decline row of an undeclined invitation", err, privacyIntegrityViolation, "invitation_declines_match_invitation") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'declined', responded_at = delivered_at + interval '1 minute', updated_at = delivered_at + interval '1 minute', version = version + 1 WHERE id = $1`, other.ID()) + assertPgError(t, "decline without its record", err, privacyIntegrityViolation, "invitations_decline_recorded") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'viewed', version = version + 1 WHERE id = $1`, other.ID()) + assertPgError(t, "viewed without a view", err, privacyCheckViolation, "invitations_answer_matches_state") + _, err = pool.Exec(ctx, `INSERT INTO invitation_events (id, invitation_id, organization_id, version, terms_version, kind, actor_id, changed_fields, occurred_at) + SELECT $1, id, organization_id, version + 1, terms_version, 'viewed', created_by, ARRAY['terms'], now() FROM invitations WHERE id = $2`, uuid.New(), other.ID()) + assertPgError(t, "view event with a field", err, privacyCheckViolation, "invitation_events_answer_changes_no_field") + + _, err = migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a declined invitation", err, privacyIntegrityViolation, invitationAnswersRetained) + if _, err := pool.Exec(ctx, `TRUNCATE invitation_decline_results, invitation_declines, invitation_send_results, company_invitation_quota_usage, + invitation_creation_results, invitation_events, invitation_terms_versions, invitations`); err != nil { + t.Fatalf("clear the invitation tables: %v", err) + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != invitationAnswerMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationAnswerMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name IN ('invitation_declines', 'invitation_decline_results')`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("answer tables left after the rollback: %d, %v", remaining, err) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/invitation_expiry_test.go b/backend/integration_test/invitation_expiry_test.go new file mode 100644 index 0000000..1427e0b --- /dev/null +++ b/backend/integration_test/invitation_expiry_test.go @@ -0,0 +1,555 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" + identityusecase "lincodex/backend/internal/usecase/identity" + invitationusecase "lincodex/backend/internal/usecase/invitation" + "lincodex/backend/internal/usecase/policy" + "lincodex/backend/internal/worker/jobrunner" + "lincodex/backend/internal/worker/retry" +) + +const ( + // invitationExpiryMigrationVersion adds the pending limit, the pause, and + // the expiry at the response deadline. + invitationExpiryMigrationVersion = 43 + // invitationExpiryJobKind is the kind of the response deadline job. + invitationExpiryJobKind = "invitation.response_deadline" +) + +// noopDeliveryNotifier stands in for the notification outbox: these tests +// check the invitation rules, not the events of a delivery. +type noopDeliveryNotifier struct{} + +func (noopDeliveryNotifier) InvitationDelivered(context.Context, outbound.UnitOfWork, domain.Invitation) error { + return nil +} + +// invitationLimitsFixture drives the invitation usecases against one isolated +// database with the real repositories, quota, consent ledger, and scheduled +// job store. Candidates resolve through a table of handles, because the card +// visibility rules are tested elsewhere. +type invitationLimitsFixture struct { + ctx context.Context + databaseURL string + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + identity identityFixture + organizations organizationFixture + clock *testClock + service *invitationusecase.Service + key domain.CandidateViewPseudonymKey + handles map[string]uuid.UUID + organization domain.Organization + owner domain.User + secondOwner domain.User +} + +func newInvitationLimitsFixture(ctx context.Context, t *testing.T, env *testEnvironment, databaseURL string) invitationLimitsFixture { + t.Helper() + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + // The policy takes effect when it is stored, after the first read of the + // clock, as in the HTTP harness. + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)} + transactor := postgresadapter.NewTransactor(pool) + identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()} + organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()} + owner := organizations.employer(t, "limits-owner@example.test") + confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute)) + organization := organizations.create(t, owner, organizations.completeProfile(t, "Limits company"), clock.Now()) + secondOwner := identities.createUser(t, "limits-second-owner@example.test", domain.ScenarioEmployer, clock.Now().Add(-time.Hour)) + confirmEmail(ctx, t, pool, secondOwner, clock.Now().Add(-time.Minute)) + insertOwnerMembership(ctx, t, transactor, organization.ID(), secondOwner.ID, clock.Now()) + + keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + fixture := invitationLimitsFixture{ + ctx: ctx, databaseURL: databaseURL, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock, + key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, secondOwner: secondOwner, + } + quota := companyquota.NewService(clock.Now) + service, err := invitationusecase.NewService(invitationusecase.Dependencies{ + Transactor: transactor, Keyring: keyring, PseudonymKey: key, + Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) { + candidateID, ok := fixture.handles[handle] + if !ok || organizationID != organization.ID() { + return uuid.Nil, candidateview.ErrCandidateCardNotFound + } + return candidateID, nil + }, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveInvitation(ctx, unit, organization, invitationID) + }, + Notifier: noopDeliveryNotifier{}, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now, + }) + if err != nil { + t.Fatalf("invitation.NewService() error = %v", err) + } + fixture.service = service + return fixture +} + +// insertOwnerMembership adds an active owner, which the MVP allows beside the +// first one: every owner may send and answer for the organization. +func insertOwnerMembership(ctx context.Context, t *testing.T, transactor *postgresadapter.Transactor, organizationID, userID uuid.UUID, at time.Time) { + t.Helper() + membership, err := domain.NewOwnerMembership(organizationID, userID, at) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + if err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Memberships().Insert(ctx, membership) + }); err != nil { + t.Fatalf("insert owner membership: %v", err) + } +} + +// confirmEmail marks the account's email confirmed at the given time. The +// invitation commands require a confirmed email of both the employer and the +// candidate. +func confirmEmail(ctx context.Context, t *testing.T, pool *pgxpool.Pool, user domain.User, at time.Time) { + t.Helper() + if _, err := pool.Exec(ctx, ` + UPDATE users SET email_verified_at = $2, version = version + 1 WHERE id = $1`, user.ID, at); err != nil { + t.Fatalf("confirm the email of %s: %v", user.ID, err) + } +} + +// candidate makes a candidate account that can sign in and gives it a card +// handle for the organization. +func (fixture *invitationLimitsFixture) candidate(t *testing.T, email string) domain.User { + t.Helper() + user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour)) + confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute)) + handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + fixture.handles[handle] = user.ID + return user +} + +func (fixture *invitationLimitsFixture) handleOf(t *testing.T, candidateID uuid.UUID) string { + t.Helper() + handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle +} + +// need stores a need of the organization with its first requirements version. +func (fixture *invitationLimitsFixture) need(t *testing.T, title string) domain.InvitationNeedRef { + t.Helper() + need := newIntegrationNeed(t, fixture.organization.ID(), title, fixture.clock.Now()) + fixture.organizations.createNeed(t, need) + return domain.InvitationNeedRef{NeedID: need.ID(), RequirementsVersion: need.RequirementsVersion()} +} + +// draft creates a draft for the candidate, under the need when one is given. +func (fixture *invitationLimitsFixture) draft( + t *testing.T, + actor domain.User, + candidateID uuid.UUID, + need *domain.InvitationNeedRef, + period *int32, +) domain.OrganizationInvitationView { + t.Helper() + key := "create-" + uuid.NewString() + view, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{ + ActorID: actor.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key, + CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID), + Need: need, ResponsePeriodDays: period, Terms: invitationStorageTerms(), + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + return view +} + +func (fixture *invitationLimitsFixture) sendCommand(actor domain.User, view domain.OrganizationInvitationView) invitationusecase.SendCommand { + return invitationusecase.SendCommand{ + ActorID: actor.ID, OrganizationID: fixture.organization.ID(), InvitationID: view.ID, + IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: view.Version, + } +} + +// send delivers a draft and fails the test when the send is refused. +func (fixture *invitationLimitsFixture) send(t *testing.T, actor domain.User, view domain.OrganizationInvitationView) domain.OrganizationInvitationView { + t.Helper() + sent, err := fixture.service.Send(fixture.ctx, fixture.sendCommand(actor, view)) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + return sent +} + +// count reads one number of the database, scoped to the organization. +func (fixture *invitationLimitsFixture) count(t *testing.T, query string, args ...any) int64 { + t.Helper() + var value int64 + if err := fixture.pool.QueryRow(fixture.ctx, query, args...).Scan(&value); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return value +} + +// enlargeQuota makes the organization E1, whose weekly invitation quota is +// larger than the E0 quota of the demo policy, so that the pending limit is +// the rule under test. +func (fixture *invitationLimitsFixture) enlargeQuota(t *testing.T) { + t.Helper() + if _, err := fixture.pool.Exec(fixture.ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, fixture.organization.ID(), fixture.clock.Now()); err != nil { + t.Fatalf("raise the organization to E1: %v", err) + } +} + +func TestInvitationPendingLimitAdmitsOneOfTwoConcurrentSendsOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + fixture.enlargeQuota(t) + candidate := fixture.candidate(t, "limits-candidate-pending@example.test") + need := fixture.need(t, "Pending need") + needRef := need + + for index := range 19 { + draft := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil) + fixture.send(t, fixture.owner, draft) + if index == 18 && fixture.count(t, `SELECT count(*) FROM invitations WHERE need_id = $1 AND state = 'delivered'`, need.NeedID) != 19 { + t.Fatal("nineteen invitations are not waiting") + } + } + first := fixture.draft(t, fixture.owner, candidate.ID, &needRef, nil) + second := fixture.draft(t, fixture.secondOwner, candidate.ID, &needRef, nil) + + var group sync.WaitGroup + results := make([]error, 2) + for index, sender := range []struct { + actor domain.User + view domain.OrganizationInvitationView + }{{fixture.owner, first}, {fixture.secondOwner, second}} { + group.Go(func() { + _, results[index] = fixture.service.Send(ctx, fixture.sendCommand(sender.actor, sender.view)) + }) + } + group.Wait() + + admitted, refused := 0, 0 + for _, err := range results { + switch { + case err == nil: + admitted++ + case errors.Is(err, invitationusecase.ErrSendBlocked): + refused++ + default: + t.Fatalf("concurrent Send() error = %v, want success or ErrSendBlocked", err) + } + } + if admitted != 1 || refused != 1 { + t.Fatalf("admitted %d and refused %d of two sends with nineteen waiting; want one each", admitted, refused) + } + waiting := fixture.count(t, ` + SELECT count(*) FROM invitations + WHERE need_id = $1 AND state IN ('delivered', 'viewed', 'counter')`, need.NeedID) + if waiting != 20 { + t.Fatalf("waiting invitations under the need = %d, want exactly the limit of 20", waiting) + } + if charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, fixture.organization.ID()); charges != 20 { + t.Fatalf("quota charges = %d, want one per admitted send", charges) + } + // The refused draft is still a draft and carries no charge. + refusedDraftState := fixture.count(t, ` + SELECT count(*) FROM invitations + WHERE need_id = $1 AND state = 'draft'`, need.NeedID) + if refusedDraftState != 1 { + t.Fatalf("drafts under the need = %d, want the refused draft only", refusedDraftState) + } +} + +func TestInvitationPauseAfterADeclineHoldsForThirtyDaysOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + candidate := fixture.candidate(t, "limits-candidate-pause@example.test") + firstNeed := fixture.need(t, "Declined need") + secondNeed := fixture.need(t, "Another need") + + // The candidate receives and declines an invitation under the first need. + first := fixture.draft(t, fixture.owner, candidate.ID, &firstNeed, nil) + sent := fixture.send(t, fixture.owner, first) + declinedAt := sent.DeliveredAt.Add(time.Hour) + fixture.clock.Set(declinedAt) + if _, err := fixture.service.DeclineMine(ctx, invitationusecase.DeclineCommand{ + ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "decline-pause", ExpectedVersion: sent.Version, + Choice: domain.InvitationDeclineChoice{Reason: domain.InvitationDeclineOther}, + }); err != nil { + t.Fatalf("DeclineMine() error = %v", err) + } + + // Another owner of the same organization sends under another need. + next := fixture.draft(t, fixture.secondOwner, candidate.ID, &secondNeed, nil) + fixture.clock.Set(declinedAt.Add(29 * 24 * time.Hour)) + if _, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); !errors.Is(err, invitationusecase.ErrSendBlocked) { + t.Fatalf("Send(day 29 after the decline) error = %v, want ErrSendBlocked", err) + } + if state := fixture.count(t, `SELECT count(*) FROM invitations WHERE id = $1 AND state = 'draft'`, next.ID); state != 1 { + t.Fatal("a send refused by the pause changed the draft") + } + + // The same draft goes out on day 30, with a new key. + fixture.clock.Set(declinedAt.Add(30 * 24 * time.Hour)) + if view, err := fixture.service.Send(ctx, fixture.sendCommand(fixture.secondOwner, next)); err != nil || view.State != domain.InvitationDelivered { + t.Fatalf("Send(day 30 after the decline) = %v, %v; want delivered", view.State, err) + } +} + +func TestInvitationAcceptAtTheDeadlineRacesTheExpiryJobOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + threeDays := int32(3) + + // Each round delivers a fresh invitation with a three-day deadline and lets + // an acceptance at the deadline race the expiry job. + for round := range 3 { + candidate := fixture.candidate(t, fmt.Sprintf("limits-candidate-race-%d@example.test", round)) + draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays) + sent := fixture.send(t, fixture.owner, draft) + deadline := *sent.ResponseDeadlineAt + charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID) + + worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock) + fixture.clock.Set(deadline) + acceptCommand := invitationusecase.AcceptCommand{ + ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-" + uuid.NewString(), + ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01", + Fields: []domain.ContactField{domain.ContactFieldEmail}, + } + var group sync.WaitGroup + var acceptErr error + var runErr error + group.Go(func() { + _, acceptErr = fixture.service.AcceptMine(ctx, acceptCommand) + }) + group.Go(func() { + _, runErr = worker.RunDue(ctx) + }) + group.Wait() + if runErr != nil { + t.Fatalf("round %d: RunDue() error = %v", round, runErr) + } + if !errors.Is(acceptErr, invitationusecase.ErrAnswerBlocked) { + t.Fatalf("round %d: AcceptMine(at the deadline) error = %v, want ErrAnswerBlocked", round, acceptErr) + } + + assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges) + if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 { + t.Fatalf("round %d: %d contact grants after a late acceptance, want none", round, grants) + } + if consents := fixture.count(t, `SELECT count(*) FROM consent_records WHERE invitation_id = $1 AND purpose = 'c4'`, sent.ID); consents != 0 { + t.Fatalf("round %d: %d consent C4 records after a late acceptance, want none", round, consents) + } + var jobStatus string + var jobError *string + if err := fixture.pool.QueryRow(ctx, `SELECT status, last_error_class FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`, + invitationExpiryJobKind, sent.ID.String()).Scan(&jobStatus, &jobError); err != nil { + t.Fatalf("round %d: read the deadline job: %v", round, err) + } + if jobStatus != "done" { + t.Fatalf("round %d: the deadline job is %s with error %v, want done", round, jobStatus, jobError) + } + } +} + +func TestInvitationDeadlineJobFirstLeavesALateAcceptanceWithoutAGrantOverPostgres(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + fixture := newInvitationLimitsFixture(ctx, t, env, env.createIsolatedDatabase(ctx, t)) + threeDays := int32(3) + candidate := fixture.candidate(t, "limits-candidate-job-first@example.test") + draft := fixture.draft(t, fixture.owner, candidate.ID, nil, &threeDays) + sent := fixture.send(t, fixture.owner, draft) + deadline := *sent.ResponseDeadlineAt + charges := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, sent.ID) + + // The job runs first at its due time and expires the invitation. + fixture.clock.Set(deadline) + worker := newDeadlineJobWorker(ctx, t, fixture.databaseURL, fixture.clock) + if _, err := worker.RunDue(ctx); err != nil { + t.Fatalf("RunDue() error = %v", err) + } + assertExpiredAtDeadline(t, fixture, sent.ID, deadline, charges) + + // The acceptance that arrives afterwards finds the expiry and grants nothing. + _, err := fixture.service.AcceptMine(ctx, invitationusecase.AcceptCommand{ + ActorID: candidate.ID, InvitationID: sent.ID, IdempotencyKey: "accept-after-job", + ExpectedVersion: sent.Version, TermsVersion: sent.TermsVersion, TextVersion: "c4-2026-10-01", + Fields: []domain.ContactField{domain.ContactFieldEmail}, + }) + if !errors.Is(err, invitationusecase.ErrAnswerBlocked) { + t.Fatalf("AcceptMine(after the job) error = %v, want ErrAnswerBlocked", err) + } + if grants := fixture.count(t, `SELECT count(*) FROM contact_grants WHERE source_invitation_id = $1`, sent.ID); grants != 0 { + t.Fatalf("contact grants = %d after the job won, want none", grants) + } + if events := fixture.count(t, `SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'expired'`, sent.ID); events != 1 { + t.Fatalf("expiry events = %d, want one", events) + } +} + +// newDeadlineJobWorker builds the scheduled job worker with the response +// deadline handler, against the store of the isolated test database and the +// fixture clock, as the application does. +func newDeadlineJobWorker(ctx context.Context, t *testing.T, databaseURL string, clock *testClock) *jobrunner.Worker { + t.Helper() + pool := newPoolFor(ctx, t, databaseURL) + settings := jobrunner.Settings{ + BatchSize: 10, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3, + Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, + ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second, + } + worker, err := jobrunner.New( + []inbound.JobHandler{invitationusecase.NewResponseDeadlineJob(clock.Now)}, + postgresadapter.NewScheduledJobStore(pool, settings.Lease), prometheus.New(), slog.New(slog.DiscardHandler), settings, clock.Now, + ) + if err != nil { + t.Fatalf("jobrunner.New() error = %v", err) + } + return worker +} + +// assertExpiredAtDeadline checks the stored state of an expired invitation: the +// deadline and terms are kept, the timeout reason is set, the audit event has +// no actor, and the quota charge is unchanged. +func assertExpiredAtDeadline(t *testing.T, fixture invitationLimitsFixture, invitationID uuid.UUID, deadline time.Time, charges int64) { + t.Helper() + var state, reason string + var storedDeadline time.Time + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT state, expiry_reason, response_deadline_at FROM invitations WHERE id = $1`, invitationID).Scan(&state, &reason, &storedDeadline); err != nil { + t.Fatalf("read invitation: %v", err) + } + if state != string(domain.InvitationExpired) || reason != string(domain.InvitationExpiryTimeout) || !storedDeadline.Equal(deadline) { + t.Fatalf("invitation = %s/%s deadline %v, want expired by the timeout at %v", state, reason, storedDeadline, deadline) + } + events := fixture.count(t, ` + SELECT count(*) FROM invitation_events + WHERE invitation_id = $1 AND kind = 'expired' AND actor_id IS NULL AND cardinality(changed_fields) = 0`, invitationID) + if events != 1 { + t.Fatalf("expiry events without an actor = %d, want one", events) + } + if stored := fixture.count(t, `SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1`, invitationID); stored != charges { + t.Fatalf("quota charges of the invitation = %d, want the %d of the send", stored, charges) + } +} + +func TestInvitationExpiryMigrationBackfillsDeadlineJobsAndGuardsExpiries(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion-1) + + // A delivery made before the migration has no deadline job yet. + draft := fixture.draft(t) + delivered, err := draft.Deliver(draft.UpdatedAt().Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + deadline := *delivered.Snapshot().ResponseDeadlineAt + + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up(43) error = %v", err) + } + var jobs int + var dueAt time.Time + if err := pool.QueryRow(ctx, ` + SELECT count(*), coalesce(max(due_at), now()) + FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2 AND status = 'pending'`, + invitationExpiryJobKind, delivered.ID().String()).Scan(&jobs, &dueAt); err != nil { + t.Fatalf("read the backfilled job: %v", err) + } + if jobs != 1 || !dueAt.Equal(deadline) { + t.Fatalf("backfilled jobs = %d due %v, want one due at the deadline %v", jobs, dueAt, deadline) + } + + // The trigger refuses an expiry that is recorded before the deadline, and + // an expiry of an invitation that is not waiting for an answer. + if _, err := pool.Exec(ctx, ` + UPDATE invitations + SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2 + WHERE id = $1`, delivered.ID(), deadline.Add(-time.Second)); err == nil { + t.Fatal("an expiry before the deadline was stored") + } + if _, err := pool.Exec(ctx, ` + UPDATE invitations + SET state = 'expired', expiry_reason = 'invitation_timeout', version = version + 1, updated_at = $2 + WHERE id = $1`, delivered.ID(), deadline); err != nil { + t.Fatalf("expiry at the deadline error = %v", err) + } + + // A rollback keeps the expiry, which the previous schema cannot represent. + // Migrations 44 and 45 sit above this one; they hold no rows that the + // expiry depends on, so they are rolled back first and the rollback of 43 + // is the one that must be refused. + rollBackAboveVersion(ctx, t, migrator, invitationExpiryMigrationVersion) + if _, err := migrator.DownOne(ctx); err == nil { + t.Fatal("rollback with an expired invitation succeeded, want it refused") + } + var expired int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE state = 'expired'`).Scan(&expired); err != nil || expired != 1 { + t.Fatalf("expired invitations after the refused rollback = %d, %v; want the stored expiry", expired, err) + } +} diff --git a/backend/integration_test/invitation_http_test.go b/backend/integration_test/invitation_http_test.go new file mode 100644 index 0000000..743d2c7 --- /dev/null +++ b/backend/integration_test/invitation_http_test.go @@ -0,0 +1,1140 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + invitationusecase "lincodex/backend/internal/usecase/invitation" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/organization" + "lincodex/backend/internal/usecase/policy" +) + +const invitationHTTPTimeout = 10 * time.Minute + +// Private values of the visible candidates. None of them may appear in any +// response, problem, or log of the organization's invitation operations. +const ( + invitationCandidateName = "Hidden Candidate Name" + invitationCandidateContact = "hidden-candidate-contact@example.test" + invitationCandidateMarker = "Hidden Candidate Employer" +) + +type invitationHTTPHarness struct { + *sessionHTTPHarness + + key domain.CandidateViewPseudonymKey +} + +func newInvitationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *invitationHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock.Now}) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needusecase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock.Now}) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + quota := companyquota.NewService(clock.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: transactor, Projector: anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(pool), key, clock.Now), + PseudonymKey: key, Clock: clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(templates), clock.Now)) + if err != nil { + t.Fatalf("NewInvitationNotifier() error = %v", err) + } + invitationService, err := invitationusecase.NewService(invitationusecase.Dependencies{ + Transactor: transactor, Keyring: keyring, PseudonymKey: key, Candidates: views.ResolveCandidateHandle, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveInvitation(ctx, unit, organization, invitationID) + }, + Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now, + }) + if err != nil { + t.Fatalf("invitation.NewService() error = %v", err) + } + inbox, err := notification.NewInboxService(transactor, + notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(false)), clock.Now) + if err != nil { + t.Fatalf("notification.NewInboxService() error = %v", err) + } + // The consent and the visibility operations are served too, so the contact + // read can be revoked through the same routes a candidate uses. + privacySettings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessionService), v1.WithPublicOrigin(env.Config.AppPublicURL)) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + consentHandler := v1.NewConsentHandler(consent.NewQueryService(postgresadapter.NewConsentStore(pool), clock.Now), consent.NewService(transactor, clock.Now)) + privacyHandler := v1.NewPrivacyHandler(views, privacySettings, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), + v1.WithNeed(v1.NewNeedHandler(needService)), v1.WithInvitation(v1.NewInvitationHandler(invitationService)), + v1.WithNotifications(v1.NewNotificationHandler(inbox)), + v1.WithConsent(consentHandler), v1.WithPrivacy(privacyHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &invitationHTTPHarness{ + sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, + key: key, + } +} + +// invitationHTTPBody is the part of the organization's invitation that the +// tests read. Fields that must be absent have no member, so a leak shows up as +// an unknown key in the raw text that the tests also scan. +type invitationHTTPBody struct { + ID uuid.UUID `json:"id"` + OrganizationID uuid.UUID `json:"organization_id"` + CandidateHandle string `json:"candidate_handle"` + Need *struct { + NeedID uuid.UUID `json:"need_id"` + RequirementsVersion int64 `json:"requirements_version"` + } `json:"need"` + State string `json:"state"` + ExpiryReason *string `json:"expiry_reason"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + Terms json.RawMessage `json:"terms"` + ResponsePeriodDays int `json:"response_period_days"` + ResponseDeadlineAt *string `json:"response_deadline_at"` + SalaryRaiseUsed bool `json:"salary_raise_used"` + SalaryFit string `json:"salary_fit"` + ContactAccess struct { + Status string `json:"status"` + Fields []string `json:"fields"` + } `json:"contact_access"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + DeliveredAt *string `json:"delivered_at"` + ViewedAt *string `json:"viewed_at"` + RespondedAt *string `json:"responded_at"` +} + +type invitationHTTPPage struct { + Items []struct { + ID uuid.UUID `json:"id"` + CandidateHandle string `json:"candidate_handle"` + State string `json:"state"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + RoleTitle string `json:"role_title"` + Salary struct { + SalaryFrom int64 `json:"salary_from"` + SalaryTo int64 `json:"salary_to"` + TaxBasis string `json:"tax_basis"` + } `json:"salary"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +type invitationHTTPProblem struct { + Code string `json:"code"` + Errors []struct { + In string `json:"in"` + Pointer string `json:"pointer"` + Code string `json:"code"` + } `json:"errors"` +} + +func invitationTermsMap() map[string]any { + return map[string]any{ + "role_title": "Middle Go developer in the payments team", + "specialization": "backend", + "grade": "middle", + "offer_type": "full_time", + "tasks": []any{"Move the payout service to an event model", "Review the changes of the team"}, + "team": "Six engineers and a team lead\nwho work in two-week iterations", + "tech_stack": []any{"Go", "PostgreSQL"}, + "work_formats": []any{"remote"}, + "location": nil, + "communication_method": map[string]any{ + "channel": "email", "details": nil, + }, + "salary": map[string]any{ + "salary_from": 100000, "salary_to": 140000, "currency": "RUB", "period": "month", "tax_basis": "net", + }, + "package": map[string]any{ + "bonus": map[string]any{"status": "provided", "description": "Quarterly bonus up to 20% of the salary"}, + "equipment": map[string]any{"status": "provided", "description": "Laptop of the employee's choice"}, + "training": map[string]any{"status": "not_provided"}, + "health_insurance": map[string]any{"status": "not_provided"}, + }, + } +} + +// invitationCreateJSON builds a create request for the handle and lets the +// caller change the request or its terms before it is encoded. +func invitationCreateJSON(t *testing.T, handle string, change func(body, terms map[string]any)) string { + t.Helper() + terms := invitationTermsMap() + body := map[string]any{"candidate_handle": handle, "terms": terms} + if change != nil { + change(body, terms) + } + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal invitation request: %v", err) + } + return string(encoded) +} + +func invitationSalary(terms map[string]any) map[string]any { return terms["salary"].(map[string]any) } + +func decodeInvitationHTTP(t *testing.T, response *httptest.ResponseRecorder, wantStatus int) invitationHTTPBody { + t.Helper() + if response.Code != wantStatus { + t.Fatalf("response = %d %s, want %d", response.Code, response.Body.String(), wantStatus) + } + if response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("Cache-Control = %q, want no-store", response.Header().Get("Cache-Control")) + } + var body invitationHTTPBody + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode invitation %s: %v", response.Body.String(), err) + } + return body +} + +func requireInvitationValidation(t *testing.T, response *httptest.ResponseRecorder, wantPointer, wantFieldCode string) { + t.Helper() + if response.Code != http.StatusBadRequest { + t.Fatalf("response = %d %s, want 400 validation_failed at %s", response.Code, response.Body.String(), wantPointer) + } + var body invitationHTTPProblem + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode problem %s: %v", response.Body.String(), err) + } + if body.Code != "validation_failed" { + t.Fatalf("problem code = %q in %s, want validation_failed", body.Code, response.Body.String()) + } + for _, field := range body.Errors { + if field.Pointer == wantPointer && (wantFieldCode == "" || field.Code == wantFieldCode) { + return + } + } + t.Fatalf("problem %s has no error at %s with code %q", response.Body.String(), wantPointer, wantFieldCode) +} + +func invitationCount(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, table string) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&count); err != nil { + t.Fatalf("count %s: %v", table, err) + } + return count +} + +type invitationStoredCounts struct{ invitations, termsVersions, events, results int } + +func readInvitationCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness) invitationStoredCounts { + t.Helper() + return invitationStoredCounts{ + invitations: invitationCount(ctx, t, harness, "invitations"), + termsVersions: invitationCount(ctx, t, harness, "invitation_terms_versions"), + events: invitationCount(ctx, t, harness, "invitation_events"), + results: invitationCount(ctx, t, harness, "invitation_creation_results"), + } +} + +func TestOrganizationInvitationDraftsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + // The policy takes effect when it is stored, after the clock of the + // harness was first read. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA, ownerB, ownerC := account("invite-owner-a@example.test", domain.ScenarioEmployer), + account("invite-owner-b@example.test", domain.ScenarioEmployer), account("invite-owner-c@example.test", domain.ScenarioEmployer) + recruiter := account("invite-recruiter@example.test", domain.ScenarioEmployer) + candidateAccount := account("invite-candidate-account@example.test", domain.ScenarioCandidate) + sessionA, sessionB, sessionC := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()), + loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerC.Email.Address()) + sessionRecruiter := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiter.Email.Address()) + sessionCandidate := loginOrganizationHTTP(t, harness.sessionHTTPHarness, candidateAccount.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "invite-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "invite-company-b") + orgC := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionC, "invite-company-c") + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiter.ID, "recruiter", "active", now) + + // The candidates of the cards. Seven identical published candidates form + // the visible cohort; the hiding and the revocation below remove them from + // one organization at a time. + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, + organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} + newVisibleCandidate := func(email string, publish bool) domain.User { + candidate := privacy.candidate(t, email) + verifyPrivacyCohortCandidate(t, privacy, candidate) + consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) + if publish { + privacy.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility) + } + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact), + Stack: privacyCohortConfirmedItems("go"), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary", + }), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}), + }, 0) + if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + return candidate + } + cohort := make([]domain.User, 0, 7) + for index := range 7 { + cohort = append(cohort, newVisibleCandidate(fmt.Sprintf("invite-visible-%d@example.test", index), true)) + } + unpublished := newVisibleCandidate("invite-unpublished@example.test", false) + revoked := newVisibleCandidate("invite-revoked@example.test", true) + privacy.revokeC2(t, revoked.ID, now.Add(time.Minute)) + hiddenFromA, hiddenFromB := cohort[0], cohort[1] + privacy.hide(t, hiddenFromA.ID, orgA, now) + privacy.hide(t, hiddenFromB.ID, orgB, now) + for _, candidate := range cohort[2:5] { + privacy.hide(t, candidate.ID, orgC, now) + } + alias := func(organizationID uuid.UUID, candidate domain.User) string { + t.Helper() + handle, err := harness.key.ForOrganization(organizationID, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle + } + // Organization C sees four candidates, below the minimum cohort of five, + // so none of its cards exists. + suppressedForC := alias(orgC, cohort[5]) + // A usable candidate of organization A, and the same person as B sees them. + target := cohort[3] + handleA, handleB := alias(orgA, target), alias(orgB, target) + if handleA == handleB { + t.Fatal("the same candidate has one handle in two organizations") + } + + createPath := func(organizationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID) + } + itemPath := func(organizationID, invitationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) + } + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("invitation-http-key-%d", keySequence) + } + createDraft := func(organizationID uuid.UUID, session organizationHTTPSession, handle string, change func(body, terms map[string]any)) *httptest.ResponseRecorder { + t.Helper() + return request(http.MethodPost, createPath(organizationID), invitationCreateJSON(t, handle, change), session, nextKey()) + } + mustCreate := func(change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + return decodeInvitationHTTP(t, createDraft(orgA, sessionA, handleA, change), http.StatusCreated) + } + candidateMarkers := []string{ + invitationCandidateName, invitationCandidateContact, invitationCandidateMarker, + target.ID.String(), unpublished.ID.String(), revoked.ID.String(), hiddenFromA.ID.String(), + } + requireNoCandidateData := func(label string, text string) { + t.Helper() + for _, marker := range candidateMarkers { + if strings.Contains(text, marker) { + t.Errorf("%s contains the private marker %q: %s", label, marker, text) + } + } + for _, field := range []string{"candidate_id", "email", "phone", "telegram", "full_name", "salary_minimum", "minimum"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + + t.Run("stores a complete draft with its first terms version and audit", func(t *testing.T) { + response := createDraft(orgA, sessionA, handleA, nil) + created := decodeInvitationHTTP(t, response, http.StatusCreated) + if created.ID == uuid.Nil || created.OrganizationID != orgA || created.State != "draft" || created.Version != 1 || created.TermsVersion != 1 || + created.ResponsePeriodDays != 7 || created.ResponseDeadlineAt != nil || created.DeliveredAt != nil || created.ViewedAt != nil || + created.RespondedAt != nil || created.ExpiryReason != nil || created.Need != nil || created.SalaryRaiseUsed { + t.Fatalf("created draft = %+v, want an unsent version 1 with the default period", created) + } + if created.CandidateHandle != handleA || created.SalaryFit != "not_available" || + created.ContactAccess.Status != "not_granted" || len(created.ContactAccess.Fields) != 0 { + t.Fatalf("created draft names %q, fit %q, access %+v; want the card handle, no indicator, and no access", created.CandidateHandle, created.SalaryFit, created.ContactAccess) + } + requireNoCandidateData("created draft", response.Body.String()) + + var candidateID uuid.UUID + var state string + var version, termsVersion int64 + if err := harness.pool.QueryRow(ctx, `SELECT candidate_id, state, version, terms_version FROM invitations WHERE id = $1`, created.ID). + Scan(&candidateID, &state, &version, &termsVersion); err != nil { + t.Fatalf("read the stored draft: %v", err) + } + if candidateID != target.ID || state != "draft" || version != 1 || termsVersion != 1 { + t.Fatalf("stored draft = candidate %s state %s version %d/%d, want the resolved candidate in a version 1 draft", candidateID, state, version, termsVersion) + } + var from, to int64 + var currency, period, basis string + if err := harness.pool.QueryRow(ctx, `SELECT salary_from, salary_to, salary_currency, salary_period, salary_tax_basis + FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, created.ID).Scan(&from, &to, ¤cy, &period, &basis); err != nil { + t.Fatalf("read the stored terms version: %v", err) + } + if from != 100000 || to != 140000 || currency != "RUB" || period != "month" || basis != "net" { + t.Fatalf("stored money = %d-%d %s %s %s, want whole rubles with their base", from, to, currency, period, basis) + } + var kind string + var eventVersion, eventTerms int64 + var actor uuid.UUID + var changed []string + if err := harness.pool.QueryRow(ctx, `SELECT kind, version, terms_version, actor_id, changed_fields FROM invitation_events WHERE invitation_id = $1`, created.ID). + Scan(&kind, &eventVersion, &eventTerms, &actor, &changed); err != nil { + t.Fatalf("read the audit event: %v", err) + } + if kind != "draft_created" || eventVersion != 1 || eventTerms != 1 || actor != ownerA.ID || len(changed) != 0 { + t.Fatalf("audit event = %s %d/%d by %s changed %v, want a creation by the owner", kind, eventVersion, eventTerms, actor, changed) + } + + read := request(http.MethodGet, itemPath(orgA, created.ID), "", sessionA, "") + reread := decodeInvitationHTTP(t, read, http.StatusOK) + requireNoCandidateData("read draft", read.Body.String()) + if string(reread.Terms) != string(created.Terms) || reread.Version != 1 || reread.CandidateHandle != handleA { + t.Fatalf("read draft differs from the created one: %s", read.Body.String()) + } + }) + + t.Run("accepts an explicit package of conditions that are not provided and refuses a left-out condition", func(t *testing.T) { + none := func(body, terms map[string]any) { + terms["package"] = map[string]any{ + "bonus": map[string]any{"status": "not_provided"}, "equipment": map[string]any{"status": "not_provided"}, + "training": map[string]any{"status": "not_provided"}, "health_insurance": map[string]any{"status": "not_provided"}, + } + } + created := mustCreate(none) + if !strings.Contains(string(created.Terms), `"training":{"status":"not_provided"}`) { + t.Fatalf("stored package = %s, want the explicit choice back", created.Terms) + } + before := readInvitationCounts(ctx, t, harness) + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + delete(terms["package"].(map[string]any), "training") + }), "/terms/package/training", "required") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["package"].(map[string]any)["bonus"] = map[string]any{"status": "provided"} + }), "/terms/package/bonus/description", "required") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["package"].(map[string]any)["equipment"] = map[string]any{"status": "not_provided", "description": "Laptop"} + }), "/terms/package/equipment", "invalid") + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused packages stored rows: %+v -> %+v", before, after) + } + }) + + t.Run("requires the base, the currency, whole thousands, and a width of 10 to 40 percent", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + cases := []struct { + name string + change func(terms map[string]any) + pointer string + }{ + {"no tax basis", func(terms map[string]any) { delete(invitationSalary(terms), "tax_basis") }, "/terms/salary/tax_basis"}, + {"unknown tax basis", func(terms map[string]any) { invitationSalary(terms)["tax_basis"] = "before_tax" }, "/terms/salary/tax_basis"}, + {"zero lower bound", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 0 }, "/terms/salary/salary_from"}, + {"lower bound off the step", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 100500 }, "/terms/salary/salary_from"}, + {"upper bound off the step", func(terms map[string]any) { invitationSalary(terms)["salary_to"] = 140500 }, "/terms/salary/salary_to"}, + {"fractional bound", func(terms map[string]any) { invitationSalary(terms)["salary_from"] = 100000.5 }, "/terms/salary/salary_from"}, + {"foreign currency", func(terms map[string]any) { invitationSalary(terms)["currency"] = "USD" }, "/terms/salary/currency"}, + {"yearly period", func(terms map[string]any) { invitationSalary(terms)["period"] = "year" }, "/terms/salary/period"}, + {"equal bounds", func(terms map[string]any) { invitationSalary(terms)["salary_to"] = 100000 }, "/terms/salary/salary_to"}, + {"reversed bounds", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 140000, 100000 + }, "/terms/salary/salary_to"}, + {"just below 10 percent", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 95000, 104000 + }, "/terms/salary/salary_to"}, + {"just above 40 percent", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 80000, 121000 + }, "/terms/salary/salary_to"}, + {"far too wide", func(terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = 1000, 100000000 + }, "/terms/salary/salary_to"}, + } + for _, test := range cases { + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { test.change(terms) }), test.pointer, "") + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused ranges stored rows: %+v -> %+v", before, after) + } + + // The exact boundaries are accepted and stored without rounding. + for _, boundary := range []struct{ from, to int }{{95000, 105000}, {80000, 120000}, {100000, 140000}} { + created := mustCreate(func(body, terms map[string]any) { + invitationSalary(terms)["salary_from"], invitationSalary(terms)["salary_to"] = boundary.from, boundary.to + }) + var from, to int64 + if err := harness.pool.QueryRow(ctx, `SELECT salary_from, salary_to FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 1`, created.ID).Scan(&from, &to); err != nil { + t.Fatalf("read the stored range: %v", err) + } + if from != int64(boundary.from) || to != int64(boundary.to) { + t.Fatalf("stored range = %d-%d, want %d-%d", from, to, boundary.from, boundary.to) + } + } + // The gross base is as valid as the net base and is kept as chosen. + gross := mustCreate(func(body, terms map[string]any) { invitationSalary(terms)["tax_basis"] = "gross" }) + if !strings.Contains(string(gross.Terms), `"tax_basis":"gross"`) { + t.Fatalf("gross draft terms = %s", gross.Terms) + } + }) + + t.Run("applies the other rules of the terms with the pointer of the field", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["work_formats"] = []any{"remote", "office"} + }), "/terms/location", "") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["tech_stack"] = []any{"Go", "PostgreSQL", "GO"} + }), "/terms/tech_stack/2", "") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + terms["role_title"] = "Bad\u0000title" + }), "/terms/role_title", "") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + delete(terms, "communication_method") + }), "/terms/communication_method", "required") + requireInvitationValidation(t, createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { + body["response_period_days"] = 5 + }), "/response_period_days", "") + // A request cannot name the candidate by anything but the handle, set + // the state, a version, an indicator, or the candidate's minimum. + for _, field := range []string{"candidate_email", "state", "version", "salary_fit", "salary_minimum", "candidate_id"} { + response := createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body[field] = "x" }) + if response.Code != http.StatusBadRequest { + t.Errorf("a request with %s = %d %s, want 400", field, response.Code, response.Body.String()) + } + } + withLocation := mustCreate(func(body, terms map[string]any) { + terms["work_formats"] = []any{"remote", "hybrid"} + terms["location"] = "Kazan" + body["response_period_days"] = 14 + }) + if withLocation.ResponsePeriodDays != 14 || !strings.Contains(string(withLocation.Terms), `"location":"Kazan"`) { + t.Fatalf("draft with a place of work = %+v", withLocation) + } + if after := readInvitationCounts(ctx, t, harness); after.invitations != before.invitations+1 { + t.Fatalf("rules stored %d invitations, want only the valid one", after.invitations-before.invitations) + } + }) + + t.Run("resolves the handle through the visibility barrier and shows nothing of a refused card", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + refused := map[string]string{ + "a handle of another organization": handleB, + "a candidate hidden from the company": alias(orgA, hiddenFromA), + "a candidate who revoked C2": alias(orgA, revoked), + "a candidate who never published": alias(orgA, unpublished), + "an unknown handle": "cv1_" + strings.Repeat("Z", 43), + } + var shapes []string + for name, handle := range refused { + response := createDraft(orgA, sessionA, handle, nil) + requireInvitationValidation(t, response, "/candidate_handle", "") + requireNoCandidateData(name, response.Body.String()) + var body invitationHTTPProblem + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode refusal: %v", err) + } + shapes = append(shapes, fmt.Sprint(body)) + } + // Every refusal looks the same, so the answer does not tell which case + // applied. + for _, shape := range shapes[1:] { + if shape != shapes[0] { + t.Fatalf("refusals differ: %s and %s", shapes[0], shape) + } + } + // The cohort of organization C is below the minimum, so no card of it + // exists and its handles are refused. + requireInvitationValidation(t, createDraft(orgC, sessionC, suppressedForC, nil), "/candidate_handle", "") + // A malformed handle is refused by the schema. + if response := createDraft(orgA, sessionA, "not-a-handle", nil); response.Code != http.StatusBadRequest { + t.Fatalf("malformed handle = %d %s, want 400", response.Code, response.Body.String()) + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused handles stored rows: %+v -> %+v", before, after) + } + // The organization that owns the handle can use it, for its own + // invitation only. + own := decodeInvitationHTTP(t, createDraft(orgB, sessionB, handleB, nil), http.StatusCreated) + if own.OrganizationID != orgB || own.CandidateHandle != handleB { + t.Fatalf("organization B draft = %+v, want its own handle", own) + } + // The same person is a different pseudonym for each organization. + if own.CandidateHandle == handleA { + t.Fatal("two organizations share a handle") + } + }) + + t.Run("replays an idempotent create and refuses a reused key", func(t *testing.T) { + before := readInvitationCounts(ctx, t, harness) + path := createPath(orgA) + body := invitationCreateJSON(t, handleA, func(body, terms map[string]any) { terms["role_title"] = "Idempotent role" }) + responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, path, body, origin, sessionA, "invitation-replay-key", 2) + if responses[0].Code != http.StatusCreated || responses[1].Code != http.StatusCreated || + responses[0].Body.String() != responses[1].Body.String() { + t.Fatalf("concurrent creates = %d %s and %d %s, want one identical 201", responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + original := responses[0].Body.String() + created := decodeInvitationHTTP(t, responses[0], http.StatusCreated) + after := readInvitationCounts(ctx, t, harness) + if after.invitations != before.invitations+1 || after.events != before.events+1 || after.results != before.results+1 { + t.Fatalf("two creates with one key stored %+v -> %+v, want one draft", before, after) + } + + // A change of the draft does not change the replayed response. + update := `{"expected_version":1,"response_period_days":3}` + decodeInvitationHTTP(t, request(http.MethodPatch, itemPath(orgA, created.ID), update, sessionA, ""), http.StatusOK) + replay := request(http.MethodPost, path, body, sessionA, "invitation-replay-key") + if replay.Code != http.StatusCreated || replay.Body.String() != original { + t.Fatalf("replay = %d %s, want the original 201", replay.Code, replay.Body.String()) + } + // The candidate stops being visible: the stored response is replayed, + // while a new key is refused. + privacy.hide(t, target.ID, orgA, now) + defer func() { + if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, target.ID, orgA); err != nil { + t.Errorf("lift the hiding: %v", err) + } + }() + if replay := request(http.MethodPost, path, body, sessionA, "invitation-replay-key"); replay.Code != http.StatusCreated || replay.Body.String() != original { + t.Fatalf("replay after hiding = %d %s, want the original 201", replay.Code, replay.Body.String()) + } + requireInvitationValidation(t, request(http.MethodPost, path, body, sessionA, "invitation-after-hiding"), "/candidate_handle", "") + + changed := invitationCreateJSON(t, handleA, func(body, terms map[string]any) { terms["role_title"] = "Another role" }) + requireSessionProblem(t, request(http.MethodPost, path, changed, sessionA, "invitation-replay-key"), http.StatusUnprocessableEntity, "idempotency_key_reused") + if final := readInvitationCounts(ctx, t, harness); final.invitations != after.invitations { + t.Fatalf("replays and refusals stored %d invitations", final.invitations-after.invitations) + } + // The key is scoped by organization: the same key in B is a new request. + fromB := createDraft(orgB, sessionB, handleB, nil) + if fromB.Code != http.StatusCreated { + t.Fatalf("organization B create = %d %s", fromB.Code, fromB.Body.String()) + } + missingKey := request(http.MethodPost, path, body, sessionA, "") + requireInvitationValidation(t, missingKey, "/Idempotency-Key", "") + }) + + t.Run("answers every unauthorized caller without revealing an invitation", func(t *testing.T) { + created := mustCreate(nil) + own := itemPath(orgA, created.ID) + before := readInvitationCounts(ctx, t, harness) + + requireSessionProblem(t, request(http.MethodGet, own, "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") + requireSessionProblem(t, request(http.MethodGet, own, "", sessionCandidate, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodGet, own, "", sessionRecruiter, ""), http.StatusForbidden, "forbidden") + // The owner of another organization and an unknown invitation both + // answer 404 not_found with the same body shape. + foreignRead := request(http.MethodGet, own, "", sessionB, "") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + unknownRead := request(http.MethodGet, itemPath(orgA, uuid.New()), "", sessionA, "") + requireSessionProblem(t, unknownRead, http.StatusNotFound, "not_found") + // An invitation of organization A is not readable through organization + // B's own path either. + requireSessionProblem(t, request(http.MethodGet, itemPath(orgB, created.ID), "", sessionB, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionB, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionCandidate, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodGet, createPath(orgA), "", sessionRecruiter, ""), http.StatusForbidden, "forbidden") + if foreignRead.Code != unknownRead.Code { + t.Fatalf("foreign and unknown invitations answer %d and %d", foreignRead.Code, unknownRead.Code) + } + if response := request(http.MethodGet, itemPath(orgA, uuid.Nil), "", sessionA, ""); response.Code != http.StatusNotFound { + t.Fatalf("nil invitation identifier = %d %s, want 404", response.Code, response.Body.String()) + } + if response := request(http.MethodGet, createPath(orgA)+"/not-a-uuid", "", sessionA, ""); response.Code != http.StatusBadRequest { + t.Fatalf("malformed invitation identifier = %d %s, want 400", response.Code, response.Body.String()) + } + + // Commands: the CSRF token and the origin are required, and a role that + // does not own the organization changes nothing. + body := invitationCreateJSON(t, handleA, nil) + noCSRF := organizationHTTPSession{cookie: sessionA.cookie} + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, noCSRF, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, createPath(orgA), body, + "https://attacker.example", sessionA, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionRecruiter, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionCandidate, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, sessionB, nextKey()), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPost, createPath(orgA), body, organizationHTTPSession{}, nextKey()), http.StatusUnauthorized, "unauthenticated") + patch := `{"expected_version":1,"response_period_days":3}` + requireSessionProblem(t, request(http.MethodPatch, own, patch, noCSRF, ""), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionRecruiter, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionCandidate, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPatch, own, patch, sessionB, ""), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, uuid.New()), patch, sessionA, ""), http.StatusNotFound, "not_found") + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("unauthorized calls stored rows: %+v -> %+v", before, after) + } + current := decodeInvitationHTTP(t, request(http.MethodGet, own, "", sessionA, ""), http.StatusOK) + if current.Version != 1 || current.ResponsePeriodDays != 7 { + t.Fatalf("an unauthorized patch changed the draft: %+v", current) + } + }) + + t.Run("lists the invitations of the organization newest first with a bound cursor", func(t *testing.T) { + list := func(organizationID uuid.UUID, session organizationHTTPSession, query string) (*httptest.ResponseRecorder, invitationHTTPPage) { + t.Helper() + response := request(http.MethodGet, createPath(organizationID)+query, "", session, "") + var page invitationHTTPPage + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode page %s: %v", response.Body.String(), err) + } + } + return response, page + } + total := invitationCount(ctx, t, harness, "invitations WHERE organization_id = '"+orgA.String()+"'") + seen := map[uuid.UUID]bool{} + var previous time.Time + query := "?limit=3" + for { + response, page := list(orgA, sessionA, query) + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) == 0 { + t.Fatalf("list = %d %s", response.Code, response.Body.String()) + } + requireNoCandidateData("list", response.Body.String()) + for _, item := range page.Items { + if seen[item.ID] || !strings.HasPrefix(item.CandidateHandle, "cv1_") || item.State != "draft" || item.RoleTitle == "" || item.Salary.TaxBasis == "" { + t.Fatalf("listed item %+v is repeated or incomplete", item) + } + var createdAt time.Time + if err := harness.pool.QueryRow(ctx, `SELECT created_at FROM invitations WHERE id = $1 AND organization_id = $2`, item.ID, orgA).Scan(&createdAt); err != nil { + t.Fatalf("listed item %s is not an invitation of the organization: %v", item.ID, err) + } + if !previous.IsZero() && createdAt.After(previous) { + t.Fatalf("list is not newest first: %s after %s", createdAt, previous) + } + previous = createdAt + seen[item.ID] = true + } + if !page.Page.HasMore { + break + } + if page.Page.NextCursor == nil { + t.Fatal("a page with more items has no cursor") + } + query = "?limit=3&cursor=" + url.QueryEscape(*page.Page.NextCursor) + } + if len(seen) != total { + t.Fatalf("pages listed %d invitations, want %d", len(seen), total) + } + // A cursor belongs to its reader and organization. + _, first := list(orgA, sessionA, "?limit=1") + if first.Page.NextCursor == nil { + t.Fatal("no cursor to test") + } + for name, response := range map[string]*httptest.ResponseRecorder{ + "another organization": request(http.MethodGet, createPath(orgB)+"?cursor="+url.QueryEscape(*first.Page.NextCursor), "", sessionB, ""), + "a forged cursor": request(http.MethodGet, createPath(orgA)+"?cursor="+url.QueryEscape(*first.Page.NextCursor+"AA"), "", sessionA, ""), + } { + if response.Code != http.StatusBadRequest { + t.Errorf("%s: list = %d %s, want 400", name, response.Code, response.Body.String()) + } + } + if response, _ := list(orgA, sessionA, "?limit=0"); response.Code != http.StatusBadRequest { + t.Errorf("limit 0 = %d, want 400", response.Code) + } + // Organization B sees only its own invitations. + _, others := list(orgB, sessionB, "") + for _, item := range others.Items { + if seen[item.ID] { + t.Fatalf("organization B lists the invitation %s of organization A", item.ID) + } + } + }) + + t.Run("updates a draft with versions, immutable terms versions, and a no-op rule", func(t *testing.T) { + draft := mustCreate(func(body, terms map[string]any) { terms["role_title"] = "Versioned role" }) + path := itemPath(orgA, draft.ID) + harness.clock.Advance(time.Minute) + + newTerms := invitationTermsMap() + newTerms["role_title"] = "Versioned role, second terms" + invitationSalary(newTerms)["salary_to"] = 150000 + body, err := json.Marshal(map[string]any{"expected_version": 1, "terms": newTerms}) + if err != nil { + t.Fatalf("marshal update: %v", err) + } + updated := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(body), sessionA, ""), http.StatusOK) + if updated.Version != 2 || updated.TermsVersion != 2 || !strings.Contains(string(updated.Terms), "second terms") || !updated.UpdatedAt.After(draft.UpdatedAt) { + t.Fatalf("updated draft = %+v, want version 2 with terms version 2", updated) + } + + // Both terms versions are stored; the first is the original text. + var firstRole, secondRole string + var firstTo, secondTo int64 + for version, target := range map[int]struct { + role *string + to *int64 + }{1: {&firstRole, &firstTo}, 2: {&secondRole, &secondTo}} { + if err := harness.pool.QueryRow(ctx, `SELECT terms ->> 'role_title', salary_to FROM invitation_terms_versions WHERE invitation_id = $1 AND version = $2`, + draft.ID, version).Scan(target.role, target.to); err != nil { + t.Fatalf("read terms version %d: %v", version, err) + } + } + if firstRole != "Versioned role" || firstTo != 140000 || secondRole != "Versioned role, second terms" || secondTo != 150000 { + t.Fatalf("terms versions = (%q, %d) and (%q, %d), want the original and the new terms", firstRole, firstTo, secondRole, secondTo) + } + var kind string + var changed []string + var termsOfEvent int64 + if err := harness.pool.QueryRow(ctx, `SELECT kind, changed_fields, terms_version FROM invitation_events WHERE invitation_id = $1 AND version = 2`, draft.ID). + Scan(&kind, &changed, &termsOfEvent); err != nil { + t.Fatalf("read the update event: %v", err) + } + if kind != "draft_updated" || !slices.Equal(changed, []string{"terms"}) || termsOfEvent != 2 { + t.Fatalf("update event = %s %v terms %d, want draft_updated for the terms", kind, changed, termsOfEvent) + } + + // A body that changes nothing answers 200 with the current draft, even + // with a stale version, and creates no version. + before := readInvitationCounts(ctx, t, harness) + for _, stale := range []int{1, 2} { + noop, err := json.Marshal(map[string]any{"expected_version": stale, "terms": newTerms}) + if err != nil { + t.Fatalf("marshal no-op: %v", err) + } + repeated := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(noop), sessionA, ""), http.StatusOK) + if repeated.Version != 2 || repeated.TermsVersion != 2 { + t.Fatalf("no-op with version %d = %+v, want the current version 2", stale, repeated) + } + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("no-op updates stored rows: %+v -> %+v", before, after) + } + + // A stale version is a 412 and nothing is changed or stored. + stale, err := json.Marshal(map[string]any{"expected_version": 1, "response_period_days": 3}) + if err != nil { + t.Fatalf("marshal stale update: %v", err) + } + requireSessionProblem(t, request(http.MethodPatch, path, string(stale), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") + // A stale version beats a rule violation. + invalidTerms := invitationTermsMap() + invitationSalary(invalidTerms)["salary_to"] = 500000 + staleInvalid, _ := json.Marshal(map[string]any{"expected_version": 1, "terms": invalidTerms}) + requireSessionProblem(t, request(http.MethodPatch, path, string(staleInvalid), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") + // A current version with a rule violation is a field error. + currentInvalid, _ := json.Marshal(map[string]any{"expected_version": 2, "terms": invalidTerms}) + requireInvitationValidation(t, request(http.MethodPatch, path, string(currentInvalid), sessionA, ""), "/terms/salary/salary_to", "") + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused updates stored rows: %+v -> %+v", before, after) + } + + // A change of the period or the need keeps the terms version. + period, _ := json.Marshal(map[string]any{"expected_version": 2, "response_period_days": 14}) + withPeriod := decodeInvitationHTTP(t, request(http.MethodPatch, path, string(period), sessionA, ""), http.StatusOK) + if withPeriod.Version != 3 || withPeriod.TermsVersion != 2 || withPeriod.ResponsePeriodDays != 14 { + t.Fatalf("period update = %+v, want version 3 with terms version 2", withPeriod) + } + if got := invitationCount(ctx, t, harness, "invitation_terms_versions WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { + t.Fatalf("stored %d terms versions, want 2", got) + } + // The candidate and the other fixed fields cannot be changed. + for _, field := range []string{"candidate_handle", "state", "salary_fit", "organization_id"} { + response := request(http.MethodPatch, path, fmt.Sprintf(`{"expected_version":3,%q:"x"}`, field), sessionA, "") + if response.Code != http.StatusBadRequest { + t.Errorf("update with %s = %d %s, want 400", field, response.Code, response.Body.String()) + } + } + if response := request(http.MethodPatch, path, `{"response_period_days":3}`, sessionA, ""); response.Code != http.StatusBadRequest { + t.Errorf("update without expected_version = %d, want 400", response.Code) + } + }) + + t.Run("links a draft only to a need of the organization that has had the requirements version", func(t *testing.T) { + needA := createNeedForInvitation(t, harness.sessionHTTPHarness, origin, sessionA, orgA, "Invitation need A") + needB := createNeedForInvitation(t, harness.sessionHTTPHarness, origin, sessionB, orgB, "Invitation need B") + linked := mustCreate(func(body, terms map[string]any) { + body["need"] = map[string]any{"need_id": needA.ID, "requirements_version": needA.RequirementsVersion} + }) + if linked.Need == nil || linked.Need.NeedID != needA.ID || linked.Need.RequirementsVersion != needA.RequirementsVersion { + t.Fatalf("linked draft = %+v, want the need reference back", linked.Need) + } + // Renaming the need makes version 2 without a new requirements version, + // so version 2 is not a requirements version the need has had. + renamed := request(http.MethodPatch, fmt.Sprintf("/api/v1/organizations/%s/needs/%s", orgA, needA.ID), `{"expected_version":1,"title":"Renamed invitation need A"}`, sessionA, "") + var renamedNeed struct { + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + if err := json.Unmarshal(renamed.Body.Bytes(), &renamedNeed); err != nil || renamed.Code != http.StatusOK || + renamedNeed.Version != 2 || renamedNeed.RequirementsVersion != needA.RequirementsVersion { + t.Fatalf("rename need = %d %s, want version 2 with the same requirements version", renamed.Code, renamed.Body.String()) + } + before := readInvitationCounts(ctx, t, harness) + for name, ref := range map[string]map[string]any{ + "a version that only renamed the need": {"need_id": needA.ID, "requirements_version": 2}, + "a need of another organization": {"need_id": needB.ID, "requirements_version": needB.RequirementsVersion}, + "an unknown need": {"need_id": uuid.New(), "requirements_version": 1}, + "a version the need never had": {"need_id": needA.ID, "requirements_version": needA.RequirementsVersion + 5}, + } { + response := createDraft(orgA, sessionA, handleA, func(body, terms map[string]any) { body["need"] = ref }) + if response.Code != http.StatusBadRequest { + t.Errorf("link to %s = %d %s, want 400", name, response.Code, response.Body.String()) + continue + } + requireInvitationValidation(t, response, "/need", "") + } + if after := readInvitationCounts(ctx, t, harness); after != before { + t.Fatalf("refused links stored rows: %+v -> %+v", before, after) + } + // The link is informational and can be removed or changed in the draft. + path := itemPath(orgA, linked.ID) + unlink := decodeInvitationHTTP(t, request(http.MethodPatch, path, `{"expected_version":1,"need":null}`, sessionA, ""), http.StatusOK) + if unlink.Need != nil || unlink.Version != 2 || unlink.TermsVersion != 1 { + t.Fatalf("unlinked draft = %+v, want version 2 without a need and the same terms version", unlink) + } + relink := fmt.Sprintf(`{"expected_version":2,"need":{"need_id":%q,"requirements_version":%d}}`, needA.ID, needA.RequirementsVersion) + if relinked := decodeInvitationHTTP(t, request(http.MethodPatch, path, relink, sessionA, ""), http.StatusOK); relinked.Need == nil || relinked.Version != 3 { + t.Fatalf("relinked draft = %+v", relinked) + } + foreign := fmt.Sprintf(`{"expected_version":3,"need":{"need_id":%q,"requirements_version":%d}}`, needB.ID, needB.RequirementsVersion) + requireInvitationValidation(t, request(http.MethodPatch, path, foreign, sessionA, ""), "/need", "") + }) + + t.Run("refuses to change an invitation that is no longer a draft", func(t *testing.T) { + draft := mustCreate(nil) + if _, err := harness.pool.Exec(ctx, `UPDATE invitations SET state = 'withdrawn', version = version + 1, updated_at = updated_at WHERE id = $1`, draft.ID); err != nil { + t.Fatalf("withdraw the draft: %v", err) + } + changed, _ := json.Marshal(map[string]any{"expected_version": 2, "response_period_days": 14}) + requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, draft.ID), string(changed), sessionA, ""), http.StatusConflict, "state_conflict") + // The stale version is compared before the state. + stale, _ := json.Marshal(map[string]any{"expected_version": 1, "response_period_days": 14}) + requireSessionProblem(t, request(http.MethodPatch, itemPath(orgA, draft.ID), string(stale), sessionA, ""), http.StatusPreconditionFailed, "version_conflict") + read := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) + if read.State != "withdrawn" || read.Version != 2 || read.ResponsePeriodDays != 7 { + t.Fatalf("withdrawn invitation = %+v, want it unchanged", read) + } + }) + + t.Run("lets only one of two concurrent updates from the same version win", func(t *testing.T) { + draft := mustCreate(nil) + path := itemPath(orgA, draft.ID) + first, second := invitationTermsMap(), invitationTermsMap() + first["role_title"], second["role_title"] = "Concurrent role one", "Concurrent role two" + bodies := make([]string, 0, 2) + for _, terms := range []map[string]any{first, second} { + encoded, _ := json.Marshal(map[string]any{"expected_version": 1, "terms": terms}) + bodies = append(bodies, string(encoded)) + } + responses := parallelNeedRequestsWithBodies(t, harness.sessionHTTPHarness, http.MethodPatch, path, bodies, origin, sessionA) + statuses := []int{responses[0].Code, responses[1].Code} + slices.Sort(statuses) + if !slices.Equal(statuses, []int{http.StatusOK, http.StatusPreconditionFailed}) { + t.Fatalf("concurrent updates answered %d %s and %d %s, want one 200 and one 412", + responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + if got := invitationCount(ctx, t, harness, "invitation_terms_versions WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { + t.Fatalf("stored %d terms versions, want 2", got) + } + if got := invitationCount(ctx, t, harness, "invitation_events WHERE invitation_id = '"+draft.ID.String()+"'"); got != 2 { + t.Fatalf("stored %d events, want 2", got) + } + }) + + t.Run("queues concurrent creates and updates of one organization without a deadlock", func(t *testing.T) { + // Creates lock the organization, the membership, and the visible cohort; + // updates lock the organization, the membership, and the invitation. Both + // take the organization lock first, so mixing them never deadlocks + // (SQLSTATE 40P01 would surface as a 500). + const pairs = 4 + drafts := make([]invitationHTTPBody, 0, pairs) + for range pairs { + drafts = append(drafts, mustCreate(nil)) + } + before := readInvitationCounts(ctx, t, harness) + responses := make([]*httptest.ResponseRecorder, 2*pairs) + var group sync.WaitGroup + start := make(chan struct{}) + for index, draft := range drafts { + createBody := invitationCreateJSON(t, handleA, nil) + createKey := nextKey() + updateTerms := invitationTermsMap() + updateTerms["role_title"] = fmt.Sprintf("Concurrent update %d", index) + updateBody, err := json.Marshal(map[string]any{"expected_version": 1, "terms": updateTerms}) + if err != nil { + t.Fatalf("marshal update: %v", err) + } + group.Go(func() { + <-start + responses[2*index] = request(http.MethodPost, createPath(orgA), createBody, sessionA, createKey) + }) + group.Go(func() { + <-start + responses[2*index+1] = request(http.MethodPatch, itemPath(orgA, draft.ID), string(updateBody), sessionA, "") + }) + } + close(start) + group.Wait() + for index, response := range responses { + want := http.StatusCreated + if index%2 == 1 { + want = http.StatusOK + } + if response.Code != want { + t.Fatalf("concurrent command %d = %d %s, want %d", index, response.Code, response.Body.String(), want) + } + } + after := readInvitationCounts(ctx, t, harness) + if after.invitations != before.invitations+pairs || after.events != before.events+2*pairs { + t.Fatalf("concurrent commands stored %+v -> %+v, want %d drafts and %d events", before, after, pairs, 2*pairs) + } + }) + + t.Run("keeps every candidate value out of responses and logs", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + var stored string + if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(terms::text, ' '), '') || ' ' || coalesce((SELECT string_agg(snapshot::text, ' ') FROM invitation_creation_results), '') + FROM invitation_terms_versions`).Scan(&stored); err != nil { + t.Fatalf("read stored terms: %v", err) + } + requireNoCandidateData("stored terms and replay responses", stored) + }) +} + +type invitationNeedBody struct { + ID uuid.UUID `json:"id"` + RequirementsVersion int64 `json:"requirements_version"` +} + +func createNeedForInvitation(t *testing.T, harness *sessionHTTPHarness, origin string, session organizationHTTPSession, organizationID uuid.UUID, title string) invitationNeedBody { + t.Helper() + response := organizationHTTPRequest(t, harness, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", organizationID), + fmt.Sprintf(`{"title":%q}`, title), origin, session, "need-for-"+strings.ReplaceAll(strings.ToLower(title), " ", "-")) + if response.Code != http.StatusCreated { + t.Fatalf("create need = %d %s, want 201", response.Code, response.Body.String()) + } + var need invitationNeedBody + if err := json.Unmarshal(response.Body.Bytes(), &need); err != nil || need.ID == uuid.Nil { + t.Fatalf("decode need %s: %v", response.Body.String(), err) + } + return need +} diff --git a/backend/integration_test/invitation_send_http_test.go b/backend/integration_test/invitation_send_http_test.go new file mode 100644 index 0000000..b2e0a55 --- /dev/null +++ b/backend/integration_test/invitation_send_http_test.go @@ -0,0 +1,676 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationSendMigrationVersion adds sending: the delivery event, the + // stored send outcomes, and the key of quota usage to invitations. + invitationSendMigrationVersion = 38 + invitationDeliveriesRetained = "invitation_deliveries_retained" + // invitationSendE0Quota is the weekly invitation quota of an E0 + // organization in the demo product policy. + invitationSendE0Quota = 10 +) + +// candidateInvitationPage is the part of the candidate's inbox that the tests +// read. A field that must be absent has no member, and the raw text is +// scanned as well. +type candidateInvitationPage struct { + Items []struct { + ID uuid.UUID `json:"id"` + Organization struct { + ID uuid.UUID `json:"id"` + Name string `json:"name"` + } `json:"organization"` + State string `json:"state"` + Version int64 `json:"version"` + TermsVersion int64 `json:"terms_version"` + RoleTitle string `json:"role_title"` + WorkFormats []string `json:"work_formats"` + ResponseDeadlineAt time.Time `json:"response_deadline_at"` + DeliveredAt time.Time `json:"delivered_at"` + ViewedAt *string `json:"viewed_at"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +// invitationSendCounts are the rows that one send may create, for one +// invitation: the invitation, its audit events, the outbox events of the +// notification, the charge, and the email request of its candidate. +type invitationSendCounts struct { + invitations, events, deliveredEvents, outboxDelivered, charges, mailRequests int +} + +func readInvitationSendCounts(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, invitationID, candidateID uuid.UUID) invitationSendCounts { + t.Helper() + var counts invitationSendCounts + if err := harness.pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM invitations WHERE id = $1), + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1), + (SELECT count(*) FROM invitation_events WHERE invitation_id = $1 AND kind = 'delivered'), + (SELECT count(*) FROM outbox_events WHERE event_type = 'invitation.delivered' AND aggregate_type = 'invitation' AND aggregate_id = $1), + (SELECT count(*) FROM company_invitation_quota_usage WHERE invitation_id = $1), + (SELECT count(*) FROM outbox_events WHERE event_type = 'notification.mail_requested' AND ( + aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $2) + OR aggregate_id IN (SELECT id FROM deliveries WHERE recipient_user_id = $2)))`, + invitationID, candidateID).Scan(&counts.invitations, &counts.events, &counts.deliveredEvents, &counts.outboxDelivered, + &counts.charges, &counts.mailRequests); err != nil { + t.Fatalf("count the rows of a send: %v", err) + } + return counts +} + +// outboxEnvelope reads one stored outbox event as the envelope a consumer +// receives for it. +func outboxEnvelope(ctx context.Context, t *testing.T, harness *invitationHTTPHarness, where string, args ...any) outbound.ConsumedEvent { + t.Helper() + var event outbound.ConsumedEvent + var payload string + if err := harness.pool.QueryRow(ctx, ` + SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at + FROM outbox_events WHERE `+where, args...).Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, + &event.AggregateID, &event.AggregateVersion, &payload, &event.OccurredAt); err != nil { + t.Fatalf("read the outbox event: %v", err) + } + event.Payload = []byte(payload) + event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond) + return event +} + +func TestOrganizationInvitationSendOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), invitationHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolated := *env + isolated.Config.DatabaseURL = databaseURL + setupPool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(setupPool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + harness := newInvitationHTTPHarness(ctx, t, &isolated) + // The policy takes effect when it is stored, after the clock of the + // harness was first read. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)) + origin := env.Config.AppPublicURL + now := harness.clock.Now() + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + account := func(email string, scenario domain.Scenario) domain.User { + return createOrganizationHTTPUser(ctx, t, harness.sessionHTTPHarness, email, passwordHash, scenario, true, now) + } + ownerA, ownerB := account("send-owner-a@example.test", domain.ScenarioEmployer), account("send-owner-b@example.test", domain.ScenarioEmployer) + recruiter := account("send-recruiter@example.test", domain.ScenarioEmployer) + sessionA, sessionB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerA.Email.Address()), loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + sessionRecruiter := loginOrganizationHTTP(t, harness.sessionHTTPHarness, recruiter.Email.Address()) + orgA := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionA, "send-company-a") + orgB := createCompanyForContextTest(t, harness.sessionHTTPHarness, origin, sessionB, "send-company-b") + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA, recruiter.ID, "recruiter", "active", now) + var nameA string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, orgA).Scan(&nameA); err != nil { + t.Fatalf("read organization name: %v", err) + } + + // Seven published candidates form the visible cohort of both + // organizations. The first two can sign in to read their inbox. + identityFixture := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identityFixture, + organizations: organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture, transactor: postgresadapter.NewTransactor(harness.pool), now: now}, + ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + profiles := candidateProfileFixture{ctx: ctx, pool: harness.pool, queries: privacy.queries, identity: identityFixture, now: now} + publishCandidate := func(candidate domain.User) { + consent := privacy.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision(invitationCandidateName), Email: confirmedDecision(invitationCandidateContact), + Stack: privacyCohortConfirmedItems("go"), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: invitationCandidateMarker, Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private summary", + }), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{Amount: 777_000, TaxBasis: domain.ProfileTaxNet}), + }, 0) + if _, err := privacy.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + } + target := account("send-target@example.test", domain.ScenarioCandidate) + other := account("send-other@example.test", domain.ScenarioCandidate) + cohort := []domain.User{target, other} + for index := range 5 { + candidate := privacy.candidate(t, fmt.Sprintf("send-visible-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, privacy, candidate) + cohort = append(cohort, candidate) + } + for _, candidate := range cohort { + publishCandidate(candidate) + } + sessionTarget := loginOrganizationHTTP(t, harness.sessionHTTPHarness, target.Email.Address()) + sessionOther := loginOrganizationHTTP(t, harness.sessionHTTPHarness, other.Email.Address()) + alias := func(organizationID uuid.UUID, candidate domain.User) string { + t.Helper() + handle, err := harness.key.ForOrganization(organizationID, candidate.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle + } + + request := func(method, path, body string, session organizationHTTPSession, key string) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness.sessionHTTPHarness, method, path, body, origin, session, key) + } + var keySequence int + nextKey := func() string { + keySequence++ + return fmt.Sprintf("invitation-send-key-%d", keySequence) + } + itemPath := func(organizationID, invitationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/invitations/%s", organizationID, invitationID) + } + sendPath := func(organizationID, invitationID uuid.UUID) string { + return itemPath(organizationID, invitationID) + "/send" + } + sendBody := func(version int64) string { return fmt.Sprintf(`{"expected_version":%d}`, version) } + draftFor := func(organizationID uuid.UUID, session organizationHTTPSession, candidate domain.User, change func(body, terms map[string]any)) invitationHTTPBody { + t.Helper() + response := request(http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invitations", organizationID), + invitationCreateJSON(t, alias(organizationID, candidate), change), session, nextKey()) + return decodeInvitationHTTP(t, response, http.StatusCreated) + } + inbox := func(session organizationHTTPSession, query string) (*httptest.ResponseRecorder, candidateInvitationPage) { + t.Helper() + response := request(http.MethodGet, "/api/v1/me/invitations"+query, "", session, "") + var page candidateInvitationPage + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode inbox %s: %v", response.Body.String(), err) + } + } + return response, page + } + candidateMarkers := []string{invitationCandidateName, invitationCandidateContact, invitationCandidateMarker} + for _, candidate := range cohort { + candidateMarkers = append(candidateMarkers, candidate.ID.String(), candidate.Email.Address()) + } + requireNoCandidateData := func(label, text string) { + t.Helper() + for _, marker := range candidateMarkers { + if strings.Contains(text, marker) { + t.Errorf("%s contains the private marker %q: %s", label, marker, text) + } + } + for _, field := range []string{"candidate_id", "email", "phone", "telegram", "full_name", "salary_minimum"} { + if strings.Contains(text, `"`+field+`":`) { + t.Errorf("%s contains the key %q: %s", label, field, text) + } + } + } + consumers := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL) + + t.Run("delivers a draft into the candidate's inbox before any email", func(t *testing.T) { + draft := draftFor(orgA, sessionA, target, nil) + response := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()) + sent := decodeInvitationHTTP(t, response, http.StatusOK) + requireNoCandidateData("send response", response.Body.String()) + if sent.State != "delivered" || sent.Version != draft.Version+1 || sent.TermsVersion != draft.TermsVersion || + sent.DeliveredAt == nil || sent.ResponseDeadlineAt == nil || sent.CandidateHandle != draft.CandidateHandle { + t.Fatalf("sent invitation = %+v, want the delivered next version of the draft", sent) + } + deliveredAt, deadline := mustParseTimestamp(t, *sent.DeliveredAt), mustParseTimestamp(t, *sent.ResponseDeadlineAt) + if !deadline.Equal(deliveredAt.Add(7 * 24 * time.Hour)) { + t.Fatalf("deadline = %s, want the default 7 days after the delivery %s", deadline, deliveredAt) + } + + // The candidate reads it at once: the commit of the send is the + // delivery, and no email exists yet. + listed, page := inbox(sessionTarget, "") + if listed.Code != http.StatusOK || listed.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("inbox = %d %s", listed.Code, listed.Body.String()) + } + requireNoCandidateData("candidate inbox", listed.Body.String()) + if strings.Contains(listed.Body.String(), "candidate_handle") || strings.Contains(listed.Body.String(), "salary_fit") || + strings.Contains(listed.Body.String(), `"need"`) { + t.Fatalf("candidate inbox shows organization-only fields: %s", listed.Body.String()) + } + if len(page.Items) != 1 { + t.Fatalf("inbox lists %d invitations, want the one delivered", len(page.Items)) + } + item := page.Items[0] + if item.ID != draft.ID || item.State != "delivered" || item.Organization.ID != orgA || item.Organization.Name != nameA || + item.Version != sent.Version || item.RoleTitle == "" || len(item.WorkFormats) != 1 || item.ViewedAt != nil || + !item.DeliveredAt.Equal(deliveredAt) || !item.ResponseDeadlineAt.Equal(deadline) { + t.Fatalf("inbox entry = %+v, want the delivered invitation of organization A", item) + } + var deliveries int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM deliveries WHERE recipient_user_id = $1`, target.ID).Scan(&deliveries); err != nil || deliveries != 0 { + t.Fatalf("deliveries for the candidate = %d, %v; want none before the email job ran", deliveries, err) + } + counts := readInvitationSendCounts(ctx, t, harness, draft.ID, target.ID) + if counts != (invitationSendCounts{invitations: 1, events: 2, deliveredEvents: 1, outboxDelivered: 1, charges: 1, mailRequests: 1}) { + t.Fatalf("send stored %+v, want one invitation, delivery event, outbox event, charge, and email request", counts) + } + var state string + var storedDelivered, storedDeadline time.Time + if err := harness.pool.QueryRow(ctx, `SELECT state, delivered_at, response_deadline_at FROM invitations WHERE id = $1`, draft.ID). + Scan(&state, &storedDelivered, &storedDeadline); err != nil || state != "delivered" || + !storedDelivered.Truncate(time.Second).Equal(deliveredAt) || !storedDeadline.Truncate(time.Second).Equal(deadline) || + !storedDeadline.Equal(storedDelivered.Add(7*24*time.Hour)) { + t.Fatalf("stored invitation = %s %s %s, %v", state, storedDelivered, storedDeadline, err) + } + + // Another candidate and an employer see nothing of it. + if _, others := inbox(sessionOther, ""); len(others.Items) != 0 { + t.Fatalf("another candidate lists %d invitations", len(others.Items)) + } + requireSessionProblem(t, request(http.MethodGet, "/api/v1/me/invitations", "", sessionA, ""), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodGet, "/api/v1/me/invitations", "", organizationHTTPSession{}, ""), http.StatusUnauthorized, "unauthenticated") + if response, _ := inbox(sessionTarget, "?limit=0"); response.Code != http.StatusBadRequest { + t.Fatalf("inbox with limit 0 = %d, want 400", response.Code) + } + + // The in-platform notification arrives through the outbox, and its + // content names the sender and the role, never the candidate. + event := outboxEnvelope(ctx, t, harness, `event_type = 'invitation.delivered' AND aggregate_id = $1`, draft.ID) + if !strings.Contains(string(event.Payload), target.ID.String()) || event.AggregateVersion != sent.Version { + t.Fatalf("outbox event = %+v, want the recipient and the delivered version", event) + } + if !deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) { + t.Fatal("the inbox consumer did not apply the event") + } + notifications := decodeNotificationPage(t, request(http.MethodGet, "/api/v1/me/notifications", "", sessionTarget, "")) + if len(notifications.Items) != 1 || notifications.Items[0].Kind != "invitation_delivered" || notifications.Items[0].Content == nil || + !strings.Contains(notifications.Items[0].Content.Summary, nameA) || notifications.Items[0].Content.LinkPath == nil || + *notifications.Items[0].Content.LinkPath != "/candidate/invitations" { + t.Fatalf("candidate notifications = %+v, want the invitation notice", notifications.Items) + } + }) + + t.Run("a repeated send stores one invitation, inbox entry, outbox event, and charge", func(t *testing.T) { + draft := draftFor(orgA, sessionA, other, nil) + key := nextKey() + responses := parallelNeedRequests(t, harness.sessionHTTPHarness, http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), origin, sessionA, key, 2) + if responses[0].Code != http.StatusOK || responses[1].Code != http.StatusOK || responses[0].Body.String() != responses[1].Body.String() { + t.Fatalf("concurrent sends with one key = %d %s and %d %s, want one identical 200", + responses[0].Code, responses[0].Body.String(), responses[1].Code, responses[1].Body.String()) + } + original := responses[0].Body.String() + sent := decodeInvitationHTTP(t, responses[0], http.StatusOK) + harness.clock.Advance(time.Hour) + if replay := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key); replay.Code != http.StatusOK || replay.Body.String() != original { + t.Fatalf("replay = %d %s, want the original 200", replay.Code, replay.Body.String()) + } + // A new key with the version of the draft answers with the invitation + // as it is now, without a version conflict or a second charge. + again := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK) + if again.State != "delivered" || again.Version != sent.Version || *again.DeliveredAt != *sent.DeliveredAt || *again.ResponseDeadlineAt != *sent.ResponseDeadlineAt { + t.Fatalf("send with a new key = %s %d %s %s, want %s %d %s %s", again.State, again.Version, *again.DeliveredAt, *again.ResponseDeadlineAt, + sent.State, sent.Version, *sent.DeliveredAt, *sent.ResponseDeadlineAt) + } + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version+1), sessionA, key), + http.StatusUnprocessableEntity, "idempotency_key_reused") + + counts := readInvitationSendCounts(ctx, t, harness, draft.ID, other.ID) + if counts != (invitationSendCounts{invitations: 1, events: 2, deliveredEvents: 1, outboxDelivered: 1, charges: 1, mailRequests: 1}) { + t.Fatalf("repeated sends stored %+v, want exactly one of each", counts) + } + if _, page := inbox(sessionOther, ""); len(page.Items) != 1 || page.Items[0].ID != draft.ID { + t.Fatalf("candidate inbox = %+v, want exactly one entry", page.Items) + } + // The outbox event reaches the inbox once, however often it is + // delivered. + event := outboxEnvelope(ctx, t, harness, `event_type = 'invitation.delivered' AND aggregate_id = $1`, draft.ID) + deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) + deliverToInbox(ctx, t, consumers, notification.InboxConsumerName, event) + deliverToInbox(ctx, t, consumers, inboxRenamedConsumer, event) + var rows int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM notification_inbox_events WHERE source_id = $1`, draft.ID).Scan(&rows); err != nil || rows != 1 { + t.Fatalf("notification rows for the invitation = %d, %v; want 1", rows, err) + } + }) + + t.Run("fixes the deadline at the delivery while the mail is stopped and its job is retried", func(t *testing.T) { + candidate := cohort[2] + draft := draftFor(orgA, sessionA, candidate, func(body, terms map[string]any) { body["response_period_days"] = 3 }) + sendKey := nextKey() + response := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, sendKey) + sent := decodeInvitationHTTP(t, response, http.StatusOK) + deliveredAt, deadline := mustParseTimestamp(t, *sent.DeliveredAt), mustParseTimestamp(t, *sent.ResponseDeadlineAt) + if sent.ResponsePeriodDays != 3 || !deadline.Equal(deliveredAt.Add(3*24*time.Hour)) { + t.Fatalf("sent = %d days, deadline %s; want 3 days after %s", sent.ResponsePeriodDays, deadline, deliveredAt) + } + + // The mail transport is stopped: deliveries are pinned to the + // disabled provider and nothing is sent. The email job fails once, + // is retried later, and is delivered again by the bus. + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + stopped, err := domain.NewMailProviderAccount("disabled", "default") + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + mailJob := notification.NewDeliveryHandler(notification.NewTemplateRenderer(templates), stopped, harness.clock.Now, slog.New(slog.DiscardHandler)) + event := outboxEnvelope(ctx, t, harness, + `event_type = 'notification.mail_requested' AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidate.ID) + failure := errors.New("the mail job failed") + harness.clock.Advance(2 * time.Hour) + if _, err := consumers.ApplyOnce(ctx, notification.DeliveryConsumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := mailJob.Handle(ctx, unit, event); err != nil { + return err + } + return failure + }); !errors.Is(err, failure) { + t.Fatalf("failed mail job error = %v, want the injected failure", err) + } + harness.clock.Advance(time.Hour) + for attempt, want := range []bool{true, false} { + applied, err := consumers.ApplyOnce(ctx, notification.DeliveryConsumerName, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return mailJob.Handle(ctx, unit, event) + }) + if err != nil || applied != want { + t.Fatalf("mail job attempt %d = %v, %v; want applied %v", attempt, applied, err, want) + } + } + var status, provider, subject, textBody, htmlBody string + if err := harness.pool.QueryRow(ctx, `SELECT status, provider, subject, text_body, html_body FROM deliveries WHERE recipient_user_id = $1`, candidate.ID). + Scan(&status, &provider, &subject, &textBody, &htmlBody); err != nil { + t.Fatalf("read the email delivery: %v", err) + } + if status != "pending" || provider != "disabled" { + t.Fatalf("email delivery = %s via %s, want a pending delivery of the stopped transport", status, provider) + } + requireNoCandidateData("email", subject+"\n"+textBody+"\n"+htmlBody) + if !strings.Contains(textBody, "/candidate/invitations") { + t.Fatalf("email text has no link to the inbox: %s", textBody) + } + + // The business answer stays a success, and the deadline is still the + // one fixed at the delivery. + if replay := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, sendKey); replay.Code != http.StatusOK || replay.Body.String() != response.Body.String() { + t.Fatalf("replay after the mail job = %d %s, want the original 200", replay.Code, replay.Body.String()) + } + read := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) + if read.State != "delivered" || *read.DeliveredAt != *sent.DeliveredAt || *read.ResponseDeadlineAt != *sent.ResponseDeadlineAt || read.Version != sent.Version { + t.Fatalf("invitation after the mail job = %s %d %s %s, want %s %d %s %s", read.State, read.Version, *read.DeliveredAt, *read.ResponseDeadlineAt, + sent.State, sent.Version, *sent.DeliveredAt, *sent.ResponseDeadlineAt) + } + // The database refuses to move a delivery or a deadline. + _, err = harness.pool.Exec(ctx, `UPDATE invitations SET response_deadline_at = response_deadline_at + interval '1 day', version = version + 1 WHERE id = $1`, draft.ID) + assertPgError(t, "move the deadline", err, privacyIntegrityViolation, "invitations_history_immutable") + }) + + t.Run("rechecks the visibility of the candidate and stores the refusal", func(t *testing.T) { + candidate := cohort[3] + draft := draftFor(orgA, sessionA, candidate, nil) + privacy.hide(t, candidate.ID, orgA, now) + key := nextKey() + refused := request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key) + requireSessionProblem(t, refused, http.StatusConflict, "state_conflict") + requireNoCandidateData("refusal", refused.Body.String()) + counts := readInvitationSendCounts(ctx, t, harness, draft.ID, candidate.ID) + if counts != (invitationSendCounts{invitations: 1, events: 1}) { + t.Fatalf("a refused send stored %+v, want only the draft", counts) + } + if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1 AND organization_id = $2`, candidate.ID, orgA); err != nil { + t.Fatalf("lift the hiding: %v", err) + } + // The refusal is stored under its key; a new key sends the draft once + // the candidate is visible again. + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key), http.StatusConflict, "state_conflict") + if sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK); sent.State != "delivered" { + t.Fatalf("send after the hiding was lifted = %+v", sent) + } + + // A revoked publication answers the same way. + revokedCandidate := cohort[4] + revokedDraft := draftFor(orgA, sessionA, revokedCandidate, nil) + privacy.revokeC2(t, revokedCandidate.ID, now.Add(time.Minute)) + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, revokedDraft.ID), sendBody(revokedDraft.Version), sessionA, nextKey()), http.StatusConflict, "state_conflict") + if counts := readInvitationSendCounts(ctx, t, harness, revokedDraft.ID, revokedCandidate.ID); counts.deliveredEvents != 0 || counts.charges != 0 || counts.outboxDelivered != 0 { + t.Fatalf("a send to a revoked publication stored %+v", counts) + } + }) + + t.Run("refuses a stale version without storing it and stores an unknown invitation", func(t *testing.T) { + draft := draftFor(orgA, sessionA, target, nil) + updated := decodeInvitationHTTP(t, request(http.MethodPatch, itemPath(orgA, draft.ID), `{"expected_version":1,"response_period_days":14}`, sessionA, ""), http.StatusOK) + key := nextKey() + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, key), http.StatusPreconditionFailed, "version_conflict") + if counts := readInvitationSendCounts(ctx, t, harness, draft.ID, target.ID); counts.deliveredEvents != 0 || counts.charges != 0 { + t.Fatalf("a stale send stored %+v", counts) + } + // Nothing was kept under the key, so the corrected request with the + // same key sends the terms that were read. + sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(updated.Version), sessionA, key), http.StatusOK) + if sent.ResponsePeriodDays != 14 || sent.State != "delivered" { + t.Fatalf("send of the read version = %+v", sent) + } + + unknownKey, unknownID := nextKey(), uuid.New() + for range 2 { + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, unknownID), sendBody(1), sessionA, unknownKey), http.StatusNotFound, "not_found") + } + foreign := draftFor(orgB, sessionB, target, nil) + requireSessionProblem(t, request(http.MethodPost, sendPath(orgA, foreign.ID), sendBody(foreign.Version), sessionA, nextKey()), http.StatusNotFound, "not_found") + if counts := readInvitationSendCounts(ctx, t, harness, foreign.ID, target.ID); counts.deliveredEvents != 0 { + t.Fatalf("a send through another organization delivered %+v", counts) + } + }) + + t.Run("only the active owner sends, with the CSRF token and a key", func(t *testing.T) { + draft := draftFor(orgA, sessionA, other, nil) + path, body := sendPath(orgA, draft.ID), sendBody(draft.Version) + requireSessionProblem(t, request(http.MethodPost, path, body, sessionRecruiter, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, path, body, sessionTarget, nextKey()), http.StatusForbidden, "forbidden") + requireSessionProblem(t, request(http.MethodPost, path, body, sessionB, nextKey()), http.StatusNotFound, "not_found") + requireSessionProblem(t, request(http.MethodPost, path, body, organizationHTTPSession{cookie: sessionA.cookie}, nextKey()), http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, organizationHTTPRequest(t, harness.sessionHTTPHarness, http.MethodPost, path, body, "https://attacker.example", sessionA, nextKey()), + http.StatusForbidden, "csrf_check_failed") + requireSessionProblem(t, request(http.MethodPost, path, body, organizationHTTPSession{}, nextKey()), http.StatusUnauthorized, "unauthenticated") + requireInvitationValidation(t, request(http.MethodPost, path, body, sessionA, ""), "/Idempotency-Key", "") + requireInvitationValidation(t, request(http.MethodPost, path, `{"expected_version":1,"state":"delivered"}`, sessionA, nextKey()), "", "") + if counts := readInvitationSendCounts(ctx, t, harness, draft.ID, other.ID); counts.deliveredEvents != 0 || counts.charges != 0 { + t.Fatalf("refused callers delivered %+v", counts) + } + current := decodeInvitationHTTP(t, request(http.MethodGet, itemPath(orgA, draft.ID), "", sessionA, ""), http.StatusOK) + if current.State != "draft" { + t.Fatalf("a refused caller changed the draft: %+v", current) + } + }) + + t.Run("lists the candidate's inbox newest first with a bound cursor", func(t *testing.T) { + var total int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM invitations WHERE candidate_id = $1 AND delivered_at IS NOT NULL`, target.ID).Scan(&total); err != nil { + t.Fatalf("count delivered invitations: %v", err) + } + if total < 2 { + t.Fatalf("the candidate has %d delivered invitations, want at least 2 to page", total) + } + seen := map[uuid.UUID]bool{} + var previous time.Time + query := "?limit=1" + for { + response, page := inbox(sessionTarget, query) + if response.Code != http.StatusOK || len(page.Items) != 1 { + t.Fatalf("inbox page = %d %s", response.Code, response.Body.String()) + } + item := page.Items[0] + if seen[item.ID] || (!previous.IsZero() && item.DeliveredAt.After(previous)) { + t.Fatalf("inbox entry %+v is repeated or out of order", item) + } + seen[item.ID], previous = true, item.DeliveredAt + if !page.Page.HasMore { + break + } + query = "?limit=1&cursor=" + *page.Page.NextCursor + } + if len(seen) != total { + t.Fatalf("pages listed %d invitations, want %d", len(seen), total) + } + _, first := inbox(sessionTarget, "?limit=1") + if response, _ := inbox(sessionOther, "?cursor="+*first.Page.NextCursor); response.Code != http.StatusBadRequest { + t.Fatalf("a cursor of another candidate = %d, want 400", response.Code) + } + }) + + t.Run("charges the weekly organization quota once per invitation", func(t *testing.T) { + var used int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, orgB).Scan(&used); err != nil { + t.Fatalf("count the charges of organization B: %v", err) + } + for range invitationSendE0Quota - used { + draft := draftFor(orgB, sessionB, cohort[5], nil) + decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgB, draft.ID), sendBody(draft.Version), sessionB, nextKey()), http.StatusOK) + } + over := draftFor(orgB, sessionB, cohort[5], nil) + key := nextKey() + for range 2 { + limited := request(http.MethodPost, sendPath(orgB, over.ID), sendBody(over.Version), sessionB, key) + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("the quota refusal has no Retry-After") + } + } + if counts := readInvitationSendCounts(ctx, t, harness, over.ID, cohort[5].ID); counts.deliveredEvents != 0 || counts.charges != 0 || counts.outboxDelivered != 0 { + t.Fatalf("a send over the quota stored %+v", counts) + } + var charges int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM company_invitation_quota_usage WHERE organization_id = $1`, orgB).Scan(&charges); err != nil || charges != invitationSendE0Quota { + t.Fatalf("charges of organization B = %d, %v; want the quota of %d", charges, err, invitationSendE0Quota) + } + // The quota of another organization is its own. + draft := draftFor(orgA, sessionA, cohort[5], nil) + decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgA, draft.ID), sendBody(draft.Version), sessionA, nextKey()), http.StatusOK) + // A week later the oldest charges expire, and the same key sends: the + // refusal was not stored under it. The sessions of the week before + // have expired, so the owner signs in again. + harness.clock.Advance(8 * 24 * time.Hour) + laterB := loginOrganizationHTTP(t, harness.sessionHTTPHarness, ownerB.Email.Address()) + if sent := decodeInvitationHTTP(t, request(http.MethodPost, sendPath(orgB, over.ID), sendBody(over.Version), laterB, key), http.StatusOK); sent.State != "delivered" { + t.Fatalf("send after the window = %+v", sent) + } + }) + + t.Run("keeps every candidate value out of logs and stored outcomes", func(t *testing.T) { + requireNoCandidateData("server log", harness.logs.String()) + var stored string + if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(snapshot::text, ' '), '') FROM invitation_send_results`).Scan(&stored); err != nil { + t.Fatalf("read stored outcomes: %v", err) + } + requireNoCandidateData("stored send outcomes", stored) + var mail string + if err := harness.pool.QueryRow(ctx, `SELECT coalesce(string_agg(subject || ' ' || body, ' '), '') FROM mail_requests`).Scan(&mail); err != nil { + t.Fatalf("read mail requests: %v", err) + } + requireNoCandidateData("mail requests", mail) + }) +} + +func mustParseTimestamp(t *testing.T, value string) time.Time { + t.Helper() + parsed, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + t.Fatalf("parse timestamp %q: %v", value, err) + } + return parsed +} + +func TestInvitationSendMigrationKeepsDeliveriesAndKeysQuotaUsage(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + rollBackAboveVersion(ctx, t, migrator, invitationSendMigrationVersion) + + // Quota usage names a stored invitation of the same organization. + _, err := pool.Exec(ctx, `INSERT INTO company_invitation_quota_usage (organization_id, invitation_id, reserved_at, policy_version_id, + verification_level, verification_basis, verification_changed_at, quota_tier) + SELECT $1, $2, now(), $3, verification_level, verification_basis, verification_changed_at, verification_level + FROM organizations WHERE id = $1`, fixture.organization.ID(), uuid.New(), fixture.policyID.UUID()) + assertPgError(t, "charge without an invitation", err, privacyForeignKeyViolation, "company_invitation_quota_usage_invitation_fkey") + + draft := fixture.draft(t) + delivered, err := draft.Deliver(fixture.now.Add(time.Minute)) + if err != nil { + t.Fatalf("Deliver() error = %v", err) + } + event, err := delivered.DeliveryEvent(fixture.owner.ID) + if err != nil { + t.Fatalf("DeliveryEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }); err != nil { + t.Fatalf("Deliver() through the repository error = %v", err) + } + // A second delivery of the same draft version loses the race. + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Deliver(ctx, draft.Version(), delivered, event) + }) + if !errors.Is(err, outbound.ErrInvitationVersionConflict) { + t.Fatalf("second Deliver() error = %v, want ErrInvitationVersionConflict", err) + } + + _, err = migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a delivered invitation", err, privacyIntegrityViolation, invitationDeliveriesRetained) + if _, err := pool.Exec(ctx, `TRUNCATE invitation_send_results, company_invitation_quota_usage, invitation_creation_results, + invitation_events, invitation_terms_versions, invitations`); err != nil { + t.Fatalf("clear the invitation tables: %v", err) + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != invitationSendMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationSendMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name = 'invitation_send_results'`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("send outcomes left after the rollback: %d, %v", remaining, err) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/invitation_storage_test.go b/backend/integration_test/invitation_storage_test.go new file mode 100644 index 0000000..7359f39 --- /dev/null +++ b/backend/integration_test/invitation_storage_test.go @@ -0,0 +1,338 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "strconv" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const ( + // invitationMigrationVersion creates the invitation tables. + invitationMigrationVersion = 37 + invitationRetainedState = "invitations_retained" +) + +type invitationStorageFixture struct { + ctx context.Context + transactor *postgresadapter.Transactor + organization domain.Organization + owner domain.User + candidate domain.User + policyID domain.PolicyVersionID + now time.Time +} + +func invitationStorageTerms() domain.InvitationTerms { + none := domain.InvitationPackageItem{Status: domain.InvitationPackageNotProvided} + return domain.InvitationTerms{ + RoleTitle: "Storage role", Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, + OfferType: domain.InvitationOfferFullTime, Tasks: []string{"Store the draft"}, Team: "Storage team", + TechStack: []string{"Go"}, WorkFormats: []domain.NeedWorkFormat{domain.NeedWorkFormatRemote}, + CommunicationMethod: domain.InvitationCommunicationMethod{Channel: domain.InvitationChannelEmail}, + Salary: domain.SalaryRange{SalaryFrom: 100_000, SalaryTo: 140_000, Currency: "RUB", Period: "month", TaxBasis: "net"}, + Package: domain.InvitationPackage{Bonus: none, Equipment: none, Training: none, HealthInsurance: none}, + } +} + +func newInvitationStorageFixture(ctx context.Context, t *testing.T, databaseURL string) (invitationStorageFixture, *pgxpool.Pool) { + t.Helper() + pool := newPoolFor(ctx, t, databaseURL) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + organizations := organizationFixture{ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now} + owner := organizations.employer(t, "storage-owner@example.test") + organization := organizations.create(t, owner, organizations.completeProfile(t, "Invitation storage company"), now) + candidate := identity.createUser(t, "storage-candidate@example.test", domain.ScenarioCandidate, now.Add(-time.Hour)) + seeded, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx) + if err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + return invitationStorageFixture{ + ctx: ctx, transactor: postgresadapter.NewTransactor(pool), organization: organization, owner: owner, + candidate: candidate, policyID: seeded.Version.ID(), now: now, + }, pool +} + +// draft stores a new draft through the repository in its own transaction. +func (fixture invitationStorageFixture) draft(t *testing.T) domain.Invitation { + t.Helper() + invitationID, err := uuid.NewV7() + if err != nil { + t.Fatalf("NewV7() error = %v", err) + } + draft, err := domain.NewInvitationDraft(domain.NewInvitationDraftInput{ + ID: invitationID, OrganizationID: fixture.organization.ID(), CandidateID: fixture.candidate.ID, ActorID: fixture.owner.ID, + PolicyVersionID: fixture.policyID, At: fixture.now, + Content: domain.InvitationDraftContent{ResponsePeriod: 7, Terms: invitationStorageTerms()}, + }) + if err != nil { + t.Fatalf("NewInvitationDraft() error = %v", err) + } + event, err := draft.DraftEvent(fixture.owner.ID, nil) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Invitations().Create(ctx, draft, event) + }); err != nil { + t.Fatalf("store the draft: %v", err) + } + return draft +} + +func TestInvitationRepositoryStoresVersionsAndRefusesLostUpdates(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + fixture, _ := newInvitationStorageFixture(ctx, t, databaseURL) + draft := fixture.draft(t) + + read := func(work func(unit outbound.UnitOfWork) error) error { + return fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { return work(unit) }) + } + var stored domain.Invitation + if err := read(func(unit outbound.UnitOfWork) error { + var err error + stored, err = unit.Invitations().Get(ctx, fixture.organization.ID(), draft.ID()) + return err + }); err != nil { + t.Fatalf("Get() error = %v", err) + } + if got, want := stored.Snapshot(), draft.Snapshot(); got.Version != want.Version || !got.Terms.Equal(want.Terms) || !got.CreatedAt.Equal(want.CreatedAt) || + stored.CandidateID() != fixture.candidate.ID || stored.PolicyVersionID() != fixture.policyID { + t.Fatalf("stored draft = %+v, want the one that was saved", got) + } + // Another organization finds nothing. + err := read(func(unit outbound.UnitOfWork) error { + _, err := unit.Invitations().Get(ctx, uuid.New(), draft.ID()) + return err + }) + if !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Fatalf("Get(another organization) error = %v, want ErrInvitationNotFound", err) + } + + content := draft.DraftContent() + content.Terms.Salary.SalaryTo = 150_000 + revised, changed, err := draft.ReviseDraft(content, fixture.policyID, fixture.now.Add(time.Minute)) + if err != nil { + t.Fatalf("ReviseDraft() error = %v", err) + } + event, err := revised.DraftEvent(fixture.owner.ID, changed) + if err != nil { + t.Fatalf("DraftEvent() error = %v", err) + } + // A save from a version that is not current is refused and stores nothing. + err = read(func(unit outbound.UnitOfWork) error { + return unit.Invitations().SaveDraft(ctx, 7, revised, true, event) + }) + if err == nil { + t.Fatal("SaveDraft(from version 7) succeeded") + } + if err := read(func(unit outbound.UnitOfWork) error { + return unit.Invitations().SaveDraft(ctx, draft.Version(), revised, true, event) + }); err != nil { + t.Fatalf("SaveDraft() error = %v", err) + } + // The same save again lost the race: the stored draft moved on. + err = read(func(unit outbound.UnitOfWork) error { + return unit.Invitations().SaveDraft(ctx, draft.Version(), revised, true, event) + }) + if !errors.Is(err, outbound.ErrInvitationVersionConflict) { + t.Fatalf("second SaveDraft() error = %v, want ErrInvitationVersionConflict", err) + } + + if err := read(func(unit outbound.UnitOfWork) error { + first, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 1) + if err != nil { + return err + } + second, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 2) + if err != nil { + return err + } + if first.Salary.SalaryTo != 140_000 || second.Salary.SalaryTo != 150_000 { + t.Errorf("terms versions end at %d and %d, want 140000 and 150000", first.Salary.SalaryTo, second.Salary.SalaryTo) + } + if _, err := unit.Invitations().GetTermsVersion(ctx, fixture.organization.ID(), draft.ID(), 3); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("GetTermsVersion(3) error = %v, want ErrInvitationNotFound", err) + } + if _, err := unit.Invitations().GetTermsVersion(ctx, uuid.New(), draft.ID(), 1); !errors.Is(err, outbound.ErrInvitationNotFound) { + t.Errorf("GetTermsVersion(another organization) error = %v, want ErrInvitationNotFound", err) + } + return nil + }); err != nil { + t.Fatalf("read terms versions: %v", err) + } +} + +func TestInvitationTablesRefuseMoneyAndHistoryViolations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + draft := fixture.draft(t) + id := draft.ID() + snapshot := func(from, to int64, basis string) string { + return `{"role_title":"x","specialization":"backend","grade":"middle","offer_type":"full_time","tasks":["x"],"team":"x",` + + `"tech_stack":["Go"],"work_formats":["remote"],"location":null,"communication_method":{"channel":"email","details":null},` + + `"salary":{"salary_from":` + strconv.FormatInt(from, 10) + `,"salary_to":` + strconv.FormatInt(to, 10) + `,"currency":"RUB","period":"month","tax_basis":"` + basis + `"},` + + `"package":{"bonus":{"status":"not_provided"},"equipment":{"status":"not_provided"},"training":{"status":"not_provided"},"health_insurance":{"status":"not_provided"}}}` + } + insertTerms := func(version int64, from, to int64, currency, period, basis string, terms string) error { + _, err := pool.Exec(ctx, `INSERT INTO invitation_terms_versions ( + invitation_id, organization_id, version, terms, salary_from, salary_to, salary_currency, salary_period, salary_tax_basis, created_at + ) VALUES ($1, $2, $3, $4::jsonb, $5, $6, $7, $8, $9, now())`, + id, fixture.organization.ID(), version, terms, from, to, currency, period, basis) + return err + } + + // The money rules hold in the database for any writer. + assertPgError(t, "A equal to B", insertTerms(2, 100000, 100000, "RUB", "month", "net", snapshot(100000, 100000, "net")), checkViolation, "invitation_terms_versions_salary_bounds") + assertPgError(t, "A off the step", insertTerms(2, 100500, 140000, "RUB", "month", "net", snapshot(100500, 140000, "net")), checkViolation, "invitation_terms_versions_salary_bounds") + assertPgError(t, "A of zero", insertTerms(2, 0, 100000, "RUB", "month", "net", snapshot(0, 100000, "net")), checkViolation, "invitation_terms_versions_salary_bounds") + assertPgError(t, "width below 10 percent", insertTerms(2, 95000, 104000, "RUB", "month", "net", snapshot(95000, 104000, "net")), checkViolation, "invitation_terms_versions_salary_width") + assertPgError(t, "width above 40 percent", insertTerms(2, 80000, 121000, "RUB", "month", "net", snapshot(80000, 121000, "net")), checkViolation, "invitation_terms_versions_salary_width") + assertPgError(t, "foreign currency", insertTerms(2, 100000, 140000, "USD", "month", "net", snapshot(100000, 140000, "net")), checkViolation, "invitation_terms_versions_salary_basis") + assertPgError(t, "unknown base", insertTerms(2, 100000, 140000, "RUB", "month", "pre-tax", snapshot(100000, 140000, "pre-tax")), checkViolation, "invitation_terms_versions_salary_basis") + assertPgError(t, "snapshot that disagrees with the columns", insertTerms(2, 100000, 140000, "RUB", "month", "net", snapshot(100000, 150000, "net")), checkViolation, "invitation_terms_versions_snapshot_shape") + assertPgError(t, "snapshot without a term", insertTerms(2, 100000, 140000, "RUB", "month", "net", `{"salary":{"salary_from":100000,"salary_to":140000,"currency":"RUB","period":"month","tax_basis":"net"}}`), checkViolation, "invitation_terms_versions_snapshot_shape") + // The exact boundaries are accepted by the same rules, as new versions of + // the same invitation. + if err := insertTerms(2, 95000, 105000, "RUB", "month", "gross", snapshot(95000, 105000, "gross")); err != nil { + t.Fatalf("insert the 10 percent range: %v", err) + } + if err := insertTerms(3, 80000, 120000, "RUB", "month", "gross", snapshot(80000, 120000, "gross")); err != nil { + t.Fatalf("insert the 40 percent range: %v", err) + } + _, err := pool.Exec(ctx, `DELETE FROM invitation_terms_versions WHERE invitation_id = $1 AND version = 2`, id) + assertPgError(t, "delete of a terms version", err, privacyIntegrityViolation, "invitation_terms_versions_immutable") + + // Terms versions and audit events are append-only. + _, err = pool.Exec(ctx, `UPDATE invitation_terms_versions SET salary_to = 150000 WHERE invitation_id = $1 AND version = 1`, id) + assertPgError(t, "update of a terms version", err, privacyIntegrityViolation, "invitation_terms_versions_immutable") + _, err = pool.Exec(ctx, `UPDATE invitation_events SET kind = 'draft_updated' WHERE invitation_id = $1`, id) + assertPgError(t, "update of an audit event", err, privacyIntegrityViolation, "invitation_events_immutable") + _, err = pool.Exec(ctx, `DELETE FROM invitation_events WHERE invitation_id = $1`, id) + assertPgError(t, "delete of an audit event", err, privacyIntegrityViolation, "invitation_events_immutable") + + // The invitation keeps its identity, steps its version by one, and is + // never deleted. + _, err = pool.Exec(ctx, `UPDATE invitations SET candidate_id = $2, version = version + 1 WHERE id = $1`, id, fixture.owner.ID) + assertPgError(t, "change of the candidate", err, privacyIntegrityViolation, "invitations_identity_immutable") + _, err = pool.Exec(ctx, `UPDATE invitations SET version = version + 2 WHERE id = $1`, id) + assertPgError(t, "version that skips a step", err, privacyIntegrityViolation, "invitations_version_step") + _, err = pool.Exec(ctx, `UPDATE invitations SET terms_version = 3, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "terms version that skips a step", err, privacyIntegrityViolation, "invitations_version_step") + _, err = pool.Exec(ctx, `UPDATE invitations SET response_period_days = 5, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "response period outside the policy options", err, checkViolation, "invitations_response_period") + _, err = pool.Exec(ctx, `UPDATE invitations SET delivered_at = now(), version = version + 1 WHERE id = $1`, id) + assertPgError(t, "delivery without a deadline", err, checkViolation, "invitations_deadline_with_delivery") + _, err = pool.Exec(ctx, `UPDATE invitations SET delivered_at = now(), response_deadline_at = now() + interval '7 days', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "delivery of a draft", err, checkViolation, "invitations_draft_is_unsent") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'expired', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "expiry without a reason", err, checkViolation, "invitations_expiry_reason") + _, err = pool.Exec(ctx, `UPDATE invitations SET state = 'sent', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "the internal sending step as a state", err, checkViolation, "invitations_state_known") + _, err = pool.Exec(ctx, `DELETE FROM invitations WHERE id = $1`, id) + assertPgError(t, "delete of an invitation", err, privacyIntegrityViolation, "invitations_immutable") + + // A delivered invitation keeps its deadline. + if _, err := pool.Exec(ctx, `UPDATE invitations SET state = 'delivered', delivered_at = '2026-10-09T10:00:00Z', + response_deadline_at = '2026-10-16T10:00:00Z', version = version + 1 WHERE id = $1`, id); err != nil { + t.Fatalf("deliver the invitation: %v", err) + } + _, err = pool.Exec(ctx, `UPDATE invitations SET response_deadline_at = '2026-10-30T10:00:00Z', version = version + 1 WHERE id = $1`, id) + assertPgError(t, "move of the deadline", err, privacyIntegrityViolation, "invitations_history_immutable") + _, err = pool.Exec(ctx, `UPDATE invitations SET response_period_days = 14, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "change of the period after delivery", err, privacyIntegrityViolation, "invitations_history_immutable") + if _, err := pool.Exec(ctx, `UPDATE invitations SET salary_raise_used = true, version = version + 1 WHERE id = $1`, id); err != nil { + t.Fatalf("record the raise: %v", err) + } + _, err = pool.Exec(ctx, `UPDATE invitations SET salary_raise_used = false, version = version + 1 WHERE id = $1`, id) + assertPgError(t, "undoing the raise", err, privacyIntegrityViolation, "invitations_history_immutable") + + // An invitation links only to a need of its own organization, and its + // current terms version must exist when the transaction commits. + foreignOrganization := organizationFixture{ctx: ctx, pool: pool, identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: fixture.now}, + transactor: fixture.transactor, now: fixture.now} + otherOwner := foreignOrganization.employer(t, "storage-other-owner@example.test") + other := foreignOrganization.create(t, otherOwner, foreignOrganization.completeProfile(t, "Other storage company"), fixture.now) + needID := uuid.New() + _, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, need_id, need_requirements_version, state, version, terms_version, + response_period_days, policy_version_id, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, 1, 'draft', 1, 1, 7, $5, $6, now(), now())`, + uuid.New(), other.ID(), fixture.candidate.ID, needID, fixture.policyID, otherOwner.ID) + assertPgError(t, "link to an unknown need", err, privacyForeignKeyViolation, "invitations_need_fkey") + _, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, need_id, state, version, terms_version, + response_period_days, policy_version_id, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, 'draft', 1, 1, 7, $5, $6, now(), now())`, + uuid.New(), other.ID(), fixture.candidate.ID, needID, fixture.policyID, otherOwner.ID) + assertPgError(t, "need without a requirements version", err, checkViolation, "invitations_need_pair") + _, err = pool.Exec(ctx, `INSERT INTO invitations (id, organization_id, candidate_id, state, version, terms_version, + response_period_days, policy_version_id, created_by, created_at, updated_at) + VALUES ($1, $2, $3, 'draft', 1, 1, 7, $4, $5, now(), now())`, + uuid.New(), other.ID(), fixture.candidate.ID, fixture.policyID, otherOwner.ID) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != privacyForeignKeyViolation || pgError.ConstraintName != "invitations_current_terms_fkey" { + t.Fatalf("invitation without its first terms version error = %v, want a deferred violation of invitations_current_terms_fkey", err) + } +} + +func TestInvitationMigrationRollbackKeepsStoredInvitations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + fixture, pool := newInvitationStorageFixture(ctx, t, databaseURL) + rollBackAboveVersion(ctx, t, migrator, invitationMigrationVersion) + fixture.draft(t) + + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a stored invitation", err, privacyIntegrityViolation, invitationRetainedState) + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + for _, status := range statuses { + if status.Version == invitationMigrationVersion && !status.Applied { + t.Fatal("the invitation migration was rolled back despite a stored invitation") + } + } + + // Once the rows are gone the rollback succeeds and the tables disappear. + if _, err := pool.Exec(ctx, `TRUNCATE invitation_creation_results, invitation_events, invitation_terms_versions, invitations`); err != nil { + t.Fatalf("clear the invitation tables: %v", err) + } + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != invitationMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want migration %d rolled back", result, err, invitationMigrationVersion) + } + var remaining int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_name LIKE 'invitation%'`).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("invitation tables left after the rollback: %d, %v", remaining, err) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/kafka_helpers_test.go b/backend/integration_test/kafka_helpers_test.go new file mode 100644 index 0000000..1f61568 --- /dev/null +++ b/backend/integration_test/kafka_helpers_test.go @@ -0,0 +1,193 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "errors" + "strings" + "testing" + "time" + + "github.com/moby/moby/client" + "github.com/testcontainers/testcontainers-go" + "github.com/twmb/franz-go/pkg/kadm" + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" +) + +const ( + kafkaTopicPrefix = "integration-" + kafkaReplicationFactor = 1 + kafkaOperationTimeout = 15 * time.Second +) + +// newKafkaClient returns a client for the test broker that closes when t +// finishes. Options add producer or consumer settings to the seed brokers. +func (env *testEnvironment) newKafkaClient(t *testing.T, options ...kgo.Opt) *kgo.Client { + t.Helper() + if env.kafkaContainer == nil { + t.Fatal("Kafka was not selected in bootstrap") + } + options = append([]kgo.Opt{kgo.SeedBrokers(env.Config.KafkaBrokers...)}, options...) + client, err := kgo.NewClient(options...) + if err != nil { + t.Fatalf("create Kafka client: %v", err) + } + t.Cleanup(client.Close) + return client +} + +// newKafkaTopicName returns a name that no other test or shard uses. +func newKafkaTopicName() string { + return kafkaTopicPrefix + strings.ToLower(rand.Text()) +} + +// createKafkaTopic creates a uniquely named topic and deletes it when t +// finishes, including after a failure. The broker never creates topics on +// demand, so tests create every topic they use. +func (env *testEnvironment) createKafkaTopic(ctx context.Context, t *testing.T, partitions int32) string { + t.Helper() + topic := newKafkaTopicName() + // Register deletion first: a request that times out may still create it. + // The test context is already canceled when cleanup runs. + cleanupCtx := context.WithoutCancel(ctx) + t.Cleanup(func() { env.deleteKafkaTopic(cleanupCtx, t, topic) }) + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + responses, err := env.KafkaAdmin.CreateTopics(ctx, partitions, kafkaReplicationFactor, nil, topic) + if err == nil { + var response kadm.CreateTopicResponse + response, err = responses.On(topic, nil) + if err == nil { + err = response.Err + } + } + if err != nil { + t.Fatalf("create Kafka topic %s: %v", topic, err) + } + return topic +} + +func (env *testEnvironment) deleteKafkaTopic(ctx context.Context, t *testing.T, topic string) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, cleanupTimeout) + defer cancel() + responses, err := env.KafkaAdmin.DeleteTopics(ctx, topic) + if err == nil { + var response kadm.DeleteTopicResponse + response, err = responses.On(topic, nil) + if err == nil { + err = response.Err + } + } + // A failed creation leaves nothing to delete. + if err != nil && !errors.Is(err, kerr.UnknownTopicOrPartition) { + t.Errorf("delete Kafka topic %s: %v", topic, err) + } +} + +func produceKafkaRecords(ctx context.Context, t *testing.T, client *kgo.Client, records ...*kgo.Record) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + if err := client.ProduceSync(ctx, records...).FirstErr(); err != nil { + t.Fatalf("produce %d Kafka records: %v", len(records), err) + } +} + +// consumeKafkaRecords reads count records from the start of every partition of +// topic without a consumer group, so no group offsets outlive the test. +func (env *testEnvironment) consumeKafkaRecords(ctx context.Context, t *testing.T, topic string, count int) []*kgo.Record { + t.Helper() + consumer := env.newKafkaClient(t, + kgo.ConsumeTopics(topic), + kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), + ) + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + records := make([]*kgo.Record, 0, count) + for len(records) < count { + fetches := consumer.PollFetches(ctx) + if err := ctx.Err(); err != nil { + t.Fatalf("consume Kafka topic %s: received %d of %d records: %v", topic, len(records), count, err) + } + if err := fetches.Err(); err != nil { + t.Fatalf("consume Kafka topic %s: %v", topic, err) + } + records = append(records, fetches.Records()...) + } + return records +} + +// kafkaTopicExists reports whether the broker metadata contains topic. +func kafkaTopicExists(ctx context.Context, t *testing.T, admin *kadm.Client, topic string) bool { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + topics, err := admin.ListTopics(ctx, topic) + if err != nil { + t.Fatalf("list Kafka topic %s: %v", topic, err) + } + if detail, ok := topics[topic]; ok && detail.Err != nil && !errors.Is(detail.Err, kerr.UnknownTopicOrPartition) { + t.Fatalf("load Kafka topic %s: %v", topic, detail.Err) + } + return topics.Has(topic) +} + +// waitForKafkaTopicDeletion allows for the short delay before a deletion +// accepted by the controller reaches broker metadata. +func waitForKafkaTopicDeletion(ctx context.Context, t *testing.T, admin *kadm.Client, topic string) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + ticker := time.NewTicker(readinessInterval) + defer ticker.Stop() + for kafkaTopicExists(ctx, t, admin, topic) { + select { + case <-ctx.Done(): + t.Fatalf("Kafka topic %s still exists after cleanup", topic) + case <-ticker.C: + } + } +} + +// pauseKafka freezes the broker without closing its port, so clients see a +// broker that accepts connections and never answers. A stopped container +// would come back on a different host port, which the advertised listener +// and the clients' seed brokers do not follow. The returned function resumes +// the broker; cleanup also resumes it so the container can be terminated. +func (env *testEnvironment) pauseKafka(ctx context.Context, t *testing.T) (resume func()) { + t.Helper() + if env.kafkaContainer == nil { + t.Fatal("Kafka was not selected in bootstrap") + } + docker, err := testcontainers.NewDockerClientWithOpts(ctx) + if err != nil { + t.Fatalf("create Docker client: %v", err) + } + t.Cleanup(func() { _ = docker.Close() }) + containerID := env.kafkaContainer.GetContainerID() + pauseCtx, cancel := context.WithTimeout(ctx, stopTimeout) + defer cancel() + if _, err := docker.ContainerPause(pauseCtx, containerID, client.ContainerPauseOptions{}); err != nil { + t.Fatalf("pause Kafka: %v", err) + } + paused := true + resume = func() { + t.Helper() + if !paused { + return + } + resumeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), stopTimeout) + defer cancel() + if _, err := docker.ContainerUnpause(resumeCtx, containerID, client.ContainerUnpauseOptions{}); err != nil { + t.Errorf("resume Kafka: %v", err) + return + } + paused = false + } + t.Cleanup(resume) + return resume +} diff --git a/backend/integration_test/kafka_test.go b/backend/integration_test/kafka_test.go new file mode 100644 index 0000000..2d82513 --- /dev/null +++ b/backend/integration_test/kafka_test.go @@ -0,0 +1,124 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "slices" + "strconv" + "testing" + + "github.com/twmb/franz-go/pkg/kerr" + "github.com/twmb/franz-go/pkg/kgo" +) + +const ( + kafkaOrderingPartitions = 3 + kafkaRecordsPerKey = 5 + kafkaRecordType = "integration.technical-check" +) + +// TestKafkaAgainstContainer checks the test harness and broker settings with +// technical records. It does not exercise an outbox relay or product events. +func TestKafkaAgainstContainer(t *testing.T) { + env := bootstrap(t, kafkaService) + ctx := t.Context() + + t.Run("keyed records keep headers and partition order", func(t *testing.T) { + topic := env.createKafkaTopic(ctx, t, kafkaOrderingPartitions) + producer := env.newKafkaClient(t) + keys := []string{"aggregate-a", "aggregate-b", "aggregate-c"} + sent := make([]*kgo.Record, 0, len(keys)*kafkaRecordsPerKey) + for sequence := range kafkaRecordsPerKey { + for _, key := range keys { + sent = append(sent, technicalRecord(topic, key, sequence)) + } + } + produceKafkaRecords(ctx, t, producer, sent...) + + received := env.consumeKafkaRecords(ctx, t, topic, len(sent)) + if len(received) != len(sent) { + t.Fatalf("received %d records, want %d", len(received), len(sent)) + } + byKey := make(map[string][]*kgo.Record, len(keys)) + for _, record := range received { + byKey[string(record.Key)] = append(byKey[string(record.Key)], record) + } + for _, key := range keys { + assertKeyedSequence(t, key, byKey[key]) + } + }) + + t.Run("missing topic is not created on demand", func(t *testing.T) { + topic := newKafkaTopicName() + // The client asks the broker to create unknown topics; the broker + // setting must refuse, so a missing topic surfaces as an error. + producer := env.newKafkaClient(t, + kgo.AllowAutoTopicCreation(), + kgo.MetadataMinAge(readinessInterval), + ) + produceCtx, cancel := context.WithTimeout(ctx, kafkaOperationTimeout) + defer cancel() + err := producer.ProduceSync(produceCtx, technicalRecord(topic, "aggregate-a", 0)).FirstErr() + if !errors.Is(err, kerr.UnknownTopicOrPartition) { + t.Fatalf("produce to missing topic: %v, want %v", err, kerr.UnknownTopicOrPartition) + } + if kafkaTopicExists(ctx, t, env.KafkaAdmin, topic) { + t.Fatalf("broker created missing topic %s", topic) + } + }) + + t.Run("topic cleanup runs when the test finishes", func(t *testing.T) { + var topic string + t.Run("owner", func(t *testing.T) { + topic = env.createKafkaTopic(ctx, t, 1) + produceKafkaRecords(ctx, t, env.newKafkaClient(t), technicalRecord(topic, "aggregate-a", 0)) + if !kafkaTopicExists(ctx, t, env.KafkaAdmin, topic) { + t.Fatalf("created topic %s is missing", topic) + } + }) + if topic == "" { + t.Fatal("owner test did not create a topic") + } + waitForKafkaTopicDeletion(ctx, t, env.KafkaAdmin, topic) + }) +} + +func technicalRecord(topic, key string, sequence int) *kgo.Record { + return &kgo.Record{ + Topic: topic, + Key: []byte(key), + Value: []byte(`{"sequence":` + strconv.Itoa(sequence) + `}`), + Headers: []kgo.RecordHeader{ + {Key: "event-type", Value: []byte(kafkaRecordType)}, + {Key: "sequence", Value: []byte(strconv.Itoa(sequence))}, + }, + } +} + +// assertKeyedSequence checks that records with one key share a partition and +// arrive in production order with their payload and headers intact. +func assertKeyedSequence(t *testing.T, key string, records []*kgo.Record) { + t.Helper() + if len(records) != kafkaRecordsPerKey { + t.Fatalf("key %s: received %d records, want %d", key, len(records), kafkaRecordsPerKey) + } + for sequence, record := range records { + want := technicalRecord(record.Topic, key, sequence) + if record.Partition != records[0].Partition { + t.Errorf("key %s: record %d in partition %d, first in %d", key, sequence, record.Partition, records[0].Partition) + } + if sequence > 0 && record.Offset <= records[sequence-1].Offset { + t.Errorf("key %s: offset %d does not follow %d", key, record.Offset, records[sequence-1].Offset) + } + if string(record.Value) != string(want.Value) { + t.Errorf("key %s: record %d value %q, want %q", key, sequence, record.Value, want.Value) + } + if !slices.EqualFunc(record.Headers, want.Headers, func(got, want kgo.RecordHeader) bool { + return got.Key == want.Key && string(got.Value) == string(want.Value) + }) { + t.Errorf("key %s: record %d headers %v, want %v", key, sequence, record.Headers, want.Headers) + } + } +} diff --git a/backend/integration_test/mail_quota_test.go b/backend/integration_test/mail_quota_test.go new file mode 100644 index 0000000..5760495 --- /dev/null +++ b/backend/integration_test/mail_quota_test.go @@ -0,0 +1,855 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "log/slog" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/resend" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +const ( + quotaTestTimeout = 3 * time.Minute + // quotaConcurrentSenders reserve at once; each holds its own connection, + // so they really contend for the window rows. + quotaConcurrentSenders = 12 + quotaAccount = "integration" +) + +var ( + mailQuotaUsageTable = pgx.Identifier{"mail_quota_usage"} + mailQuotaReservationsTable = pgx.Identifier{"mail_quota_reservations"} +) + +// quotaHarness drives notification.QuotaGate against PostgreSQL with a fake +// clock that the test moves. +type quotaHarness struct { + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + deliveries outbound.DeliveryRepository + recipients *deliveryHarness + logs *syncBuffer + now time.Time +} + +func TestMailQuota(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), quotaTestTimeout) + defer cancel() + pool := env.newPoolWithMaxConns(ctx, t, quotaConcurrentSenders+1) + harness := "aHarness{ + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(), + logs: &syncBuffer{}, + } + harness.recipients = &deliveryHarness{env: env, pool: pool, identity: postgresadapter.NewIdentityStore(pool), logs: harness.logs} + reset := func(t *testing.T, now time.Time) domain.User { + t.Helper() + truncateTables(ctx, t, pool, slices.Concat([]pgx.Identifier{mailQuotaUsageTable, mailQuotaReservationsTable}, usersDependentTables)...) + harness.now = now + harness.recipients.now = now + return harness.recipients.createRecipient(ctx, t, true) + } + + t.Run("concurrent reservations admit exactly the remaining daily quota", func(t *testing.T) { + now := time.Date(2026, 10, 6, 15, 0, 0, 0, time.UTC) + recipient := reset(t, now) + gate := harness.gate(t, "resend", 10, 3000) + account := mustProviderAccount(t, "resend") + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + + // The first round starts on windows that have no row yet, so the + // row creation races as well; the second starts at 7 of 10. + harness.reserveConcurrently(ctx, t, gate, harness.createDeliveries(ctx, t, recipient, account, quotaConcurrentSenders), 10, midnight) + harness.assertUsage(ctx, t, account, now, 10, 10) + + recipient2 := reset(t, now) + for _, delivery := range harness.createDeliveries(ctx, t, recipient2, account, 7) { + if !harness.prepare(ctx, t, gate, delivery).Proceed() { + t.Fatal("a send within the daily limit was not admitted") + } + } + harness.reserveConcurrently(ctx, t, gate, harness.createDeliveries(ctx, t, recipient2, account, quotaConcurrentSenders), 3, midnight) + harness.assertUsage(ctx, t, account, now, 10, 10) + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("the fake clock crosses midnight UTC and the month boundary", func(t *testing.T) { + start := time.Date(2026, 10, 30, 22, 0, 0, 0, time.UTC) + recipient := reset(t, start) + gate := harness.gate(t, "resend", 2, 3) + account := mustProviderAccount(t, "resend") + deliveries := harness.createDeliveries(ctx, t, recipient, account, 4) + + for _, delivery := range deliveries[:2] { + if !harness.prepare(ctx, t, gate, delivery).Proceed() { + t.Fatal("a send within the limits was not admitted") + } + } + // The day is full: the third waits for 00:00 UTC. + dayReset := time.Date(2026, 10, 31, 0, 0, 0, 0, time.UTC) + third := harness.prepare(ctx, t, gate, deliveries[2]) + harness.assertWaiting(ctx, t, third, deliveries[2].ID(), dayReset) + + // One second before midnight it still waits; at midnight it goes. + harness.now = dayReset.Add(-time.Second) + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[2].ID())), deliveries[2].ID(), dayReset) + harness.now = dayReset + if !harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[2].ID())).Proceed() { + t.Fatal("the waiting delivery was not admitted after midnight UTC") + } + // The new day has room, but the month is full: the fourth waits for + // the first day of the next month. + monthReset := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, deliveries[3]), deliveries[3].ID(), monthReset) + harness.now = monthReset + if !harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[3].ID())).Proceed() { + t.Fatal("the waiting delivery was not admitted in the new month") + } + + harness.assertUsage(ctx, t, account, start, 2, 3) + harness.assertUsage(ctx, t, account, dayReset, 1, 3) + harness.assertUsage(ctx, t, account, monthReset, 1, 1) + assertRowCount(ctx, t, pool, mailQuotaUsageTable, 5) + }) + + t.Run("a lowered limit defers sends and switching to SMTP does not skip the quota", func(t *testing.T) { + now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + recipient := reset(t, now) + resend := mustProviderAccount(t, "resend") + gate := harness.gateFromConfig(t, map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": "re_integration"}) + for _, delivery := range harness.createDeliveries(ctx, t, recipient, resend, 4) { + if !harness.prepare(ctx, t, gate, delivery).Proceed() { + t.Fatal("a send within the default limit was not admitted") + } + } + + // The operator lowers the daily limit below today's usage. + lowered := harness.gateFromConfig(t, map[string]string{"EMAIL_PROVIDER": "resend", "RESEND_API_KEY": "re_integration", "EMAIL_QUOTA_DAILY": "3"}) + waiting := harness.createDeliveries(ctx, t, recipient, resend, 1)[0] + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, lowered, waiting), waiting.ID(), time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)) + harness.assertUsage(ctx, t, resend, now, 4, 4) + + // smtp needs stated limits: without them the process does not start. + smtpSettings := map[string]string{ + "EMAIL_PROVIDER": "smtp", "SMTP_HOST": "smtp.example.com", "SMTP_PORT": "587", + "SMTP_USERNAME": "mailer", "SMTP_PASSWORD": "integration-password", "SMTP_TLS_MODE": "starttls", + } + if _, err := loadQuotaConfig(smtpSettings); err == nil { + t.Fatal("smtp without EMAIL_QUOTA_DAILY and EMAIL_QUOTA_MONTHLY was accepted") + } + smtpSettings["EMAIL_QUOTA_DAILY"] = "2" + smtpSettings["EMAIL_QUOTA_MONTHLY"] = "2" + smtpGate := harness.gateFromConfig(t, smtpSettings) + smtp := mustProviderAccount(t, "smtp") + relayed := harness.createDeliveries(ctx, t, recipient, smtp, 3) + for _, delivery := range relayed[:2] { + if !harness.prepare(ctx, t, smtpGate, delivery).Proceed() { + t.Fatal("an SMTP send within its limit was not admitted") + } + } + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, smtpGate, relayed[2]), relayed[2].ID(), time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)) + harness.assertUsage(ctx, t, smtp, now, 2, 2) + + // A delivery pinned to the old account is not sent through the relay + // without a limit: the gate refuses it and reserves nothing. + err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := smtpGate.PrepareSend(ctx, unit, waiting) + return err + }) + if !errors.Is(err, notification.ErrQuotaNotConfigured) { + t.Fatalf("PrepareSend() for a Resend delivery under smtp error = %v, want ErrQuotaNotConfigured", err) + } + harness.assertUsage(ctx, t, resend, now, 4, 4) + }) + + t.Run("a provider quota answer refines the local count", func(t *testing.T) { + now := time.Date(2026, 10, 6, 20, 0, 0, 0, time.UTC) + recipient := reset(t, now) + gate := harness.gate(t, "resend", 100, 3000) + account := mustProviderAccount(t, "resend") + deliveries := harness.createDeliveries(ctx, t, recipient, account, 4) + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + + // A temporary failure before the request was written gives the + // reservation back. + temporary := harness.prepare(ctx, t, gate, deliveries[0]) + harness.settle(ctx, t, gate, temporary, outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionTemporary, + }, now.Add(time.Minute)) + harness.assertUsage(ctx, t, account, now, 0, 0) + + // Resend refuses with daily_quota_exceeded although the local count + // is 1 of 100, for example because the account also sends elsewhere. + refused := harness.prepare(ctx, t, gate, deliveries[1]) + stored := harness.settle(ctx, t, gate, refused, outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, + ProviderCode: "daily_quota_exceeded", RetryAfter: midnight.Sub(now), QuotaPeriod: domain.MailQuotaPeriodDay, + }, time.Time{}) + if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().Equal(midnight) || stored.AttemptCount() != 1 { + t.Fatalf("refused delivery is %s due %s after %d attempts, want waiting_quota due %s", stored.Status(), stored.NextAttemptAt(), stored.AttemptCount(), midnight) + } + harness.assertUsage(ctx, t, account, now, 100, 0) + var exhaustedAt time.Time + if err := pool.QueryRow(ctx, "SELECT provider_exhausted_at FROM mail_quota_usage WHERE period_kind = 'day'").Scan(&exhaustedAt); err != nil || !exhaustedAt.Equal(now) { + t.Fatalf("provider_exhausted_at = %s, %v; want %s", exhaustedAt, err, now) + } + // The gate now stops before the provider. + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, deliveries[2]), deliveries[2].ID(), midnight) + + // Next day: Resend refuses with monthly_quota_exceeded and no hint. + // The month is marked full and the delivery waits for the month + // start. + harness.now = midnight + monthly := harness.prepare(ctx, t, gate, harness.get(ctx, t, deliveries[1].ID())) + stored = harness.settle(ctx, t, gate, monthly, outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionQuotaExhausted, + ProviderCode: "monthly_quota_exceeded", QuotaPeriod: domain.MailQuotaPeriodMonth, + }, time.Time{}) + monthReset := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC) + if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().Equal(monthReset) { + t.Fatalf("refused delivery is %s due %s, want waiting_quota due %s", stored.Status(), stored.NextAttemptAt(), monthReset) + } + harness.assertUsage(ctx, t, account, midnight, 0, 3000) + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, deliveries[3]), deliveries[3].ID(), monthReset) + harness.assertLogsHoldNoPersonalData(t) + }) + + t.Run("deleting an account keeps the usage counted", func(t *testing.T) { + now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + recipient := reset(t, now) + gate := harness.gate(t, "resend", 3, 3000) + account := mustProviderAccount(t, "resend") + for _, delivery := range harness.createDeliveries(ctx, t, recipient, account, 3) { + permit := harness.prepare(ctx, t, gate, delivery) + harness.settle(ctx, t, gate, permit, outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: uuid.NewString()}, time.Time{}) + } + if _, err := pool.Exec(ctx, "DELETE FROM users WHERE id = $1", recipient.ID); err != nil { + t.Fatalf("delete the recipient account: %v", err) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 0) + assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 0) + harness.assertUsage(ctx, t, account, now, 3, 3) + + // A send for another account the same day is still over the limit. + harness.recipients.now = now + other := harness.createRecipientWithAddress(ctx, t, "other.recipient@example.com") + delivery := harness.createDeliveries(ctx, t, other, account, 1)[0] + harness.assertWaiting(ctx, t, harness.prepare(ctx, t, gate, delivery), delivery.ID(), time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC)) + }) + + t.Run("releases, marks, and reservations in opposite row orders never deadlock", func(t *testing.T) { + dayOne := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) + reset(t, dayOne) + account := mustProviderAccount(t, "resend") + limits, err := domain.NewMailQuotaLimits(1_000_000, 1_000_000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + // Day one creates the month row before the day-two row, so a scan + // of day two meets the month row first in heap order: the order in + // which an UPDATE without the ordered lock locked them, against a + // reservation that locks the day first. + earlier := make([]outbound.MailQuotaReservation, quotaStressRounds) + for index := range earlier { + earlier[index] = harness.reserveDirectly(ctx, t, account, limits, dayOne) + } + dayTwo := dayOne.Add(24 * time.Hour) + current := make([]outbound.MailQuotaReservation, quotaStressRounds) + for index := range current { + current[index] = harness.reserveDirectly(ctx, t, account, limits, dayTwo) + } + // Heap-order plans, as in the queued case below. + heapOrder := postgresadapter.NewTransactor(env.newPoolWithRuntimeParams(ctx, t, map[string]string{"enable_indexscan": "off"})) + settle := func(settlement outbound.MailQuotaSettlement) error { + return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.MailQuotas().Settle(ctx, settlement) + return err + }) + } + reserve := func() error { + return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.MailQuotas().Reserve(ctx, outbound.MailQuotaReserveRequest{Reservation: newReservation(t, account, dayTwo), Limits: limits}) + return err + }) + } + for round := range quotaStressRounds { + // A release of day two, a release of day one that marks day two + // across midnight, and two reservations of day two start at once. + errs := runAtOnce( + func() error { + return settle(outbound.MailQuotaSettlement{Reservation: current[round], Outcome: outbound.MailQuotaOutcomeRejected, Release: true, At: dayTwo}) + }, + func() error { + return settle(outbound.MailQuotaSettlement{ + Reservation: earlier[round], Outcome: outbound.MailQuotaOutcomeRejected, Release: true, At: dayTwo, + ExhaustedPeriod: domain.MailQuotaPeriodDay, ExhaustedWindows: domain.MailQuotaWindowsAt(dayTwo), ExhaustedLimit: 1, + }) + }, + reserve, + reserve, + ) + for _, err := range errs { + if err != nil { + t.Fatalf("round %d: concurrent quota write error = %v (deadlock: %t)", round, err, errors.Is(err, outbound.ErrTransactionConflict)) + } + } + } + }) + + t.Run("a release queued behind a reservation on the day row does not deadlock", func(t *testing.T) { + day := time.Date(2026, 10, 7, 10, 0, 0, 0, time.UTC) + account := mustProviderAccount(t, "resend") + limits, err := domain.NewMailQuotaLimits(1000, 1000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + // Without the index the planner scans in heap order, as the bitmap + // plan that reproduced the deadlock did. The fixed lock order must + // not depend on the plan. + heapOrder := postgresadapter.NewTransactor(env.newPoolWithRuntimeParams(ctx, t, map[string]string{"enable_indexscan": "off"})) + for _, releaseFirst := range []bool{false, true} { + reset(t, day) + // The month row is written before the day row, so a scan meets + // it first: the order in which an UPDATE without the ordered + // lock took the rows, against a reservation that takes the day + // row first. + opened := newReservation(t, account, day) + for _, statement := range []string{ + "INSERT INTO mail_quota_usage VALUES ('resend', 'integration', 'month', '2026-10-01', 1, NULL, $1)", + "INSERT INTO mail_quota_usage VALUES ('resend', 'integration', 'day', '2026-10-07', 1, NULL, $1)", + } { + if _, err := pool.Exec(ctx, statement, day); err != nil { + t.Fatalf("prepare usage rows: %v", err) + } + } + if _, err := pool.Exec(ctx, `INSERT INTO mail_quota_reservations (id, delivery_id, provider, provider_account, day_start, month_start, recipients, reserved_at) + VALUES ($1, $2, 'resend', 'integration', '2026-10-07', '2026-10-01', 1, $3)`, opened.ID, opened.DeliveryID, day); err != nil { + t.Fatalf("prepare the open reservation: %v", err) + } + + // A third transaction holds the day row, so both writers queue + // on it in a chosen order. + blocker, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin the blocking transaction: %v", err) + } + if _, err := blocker.Exec(ctx, "SELECT 1 FROM mail_quota_usage WHERE period_kind = 'day' FOR UPDATE"); err != nil { + t.Fatalf("lock the day row: %v", err) + } + release := func() error { + return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.MailQuotas().Settle(ctx, outbound.MailQuotaSettlement{Reservation: opened, Outcome: outbound.MailQuotaOutcomeRejected, Release: true, At: day}) + return err + }) + } + reserve := func() error { + return heapOrder.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.MailQuotas().Reserve(ctx, outbound.MailQuotaReserveRequest{Reservation: newReservation(t, account, day), Limits: limits}) + return err + }) + } + first, second := reserve, release + if releaseFirst { + first, second = release, reserve + } + results := make(chan error, 2) + go func() { results <- first() }() + harness.waitForLockWaiters(ctx, t, 1) + go func() { results <- second() }() + harness.waitForLockWaiters(ctx, t, 2) + if err := blocker.Rollback(ctx); err != nil { + t.Fatalf("release the day row: %v", err) + } + for range 2 { + if err := <-results; err != nil { + t.Fatalf("release first %t: queued quota write error = %v (deadlock: %t)", releaseFirst, err, errors.Is(err, outbound.ErrTransactionConflict)) + } + } + harness.assertUsage(ctx, t, account, day, 1, 1) + } + }) + + t.Run("a release happens once and a retry inside the idempotency window reuses its reservation", func(t *testing.T) { + now := time.Date(2026, 10, 6, 10, 0, 0, 0, time.UTC) + recipient := reset(t, now) + gate := harness.gate(t, "resend", 100, 3000) + account := mustProviderAccount(t, "resend") + deliveries := harness.createDeliveries(ctx, t, recipient, account, 2) + + // A transport error is settled twice, as after a commit whose + // answer was lost: the journal releases it once. + notSent := harness.prepare(ctx, t, gate, deliveries[0]) + harness.prepare(ctx, t, gate, deliveries[1]) + for range 2 { + err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := gate.SettleSend(ctx, unit, notSent.Permit, outbound.SendResult{}, context.Canceled) + return err + }) + if err != nil { + t.Fatalf("SettleSend() error = %v", err) + } + } + harness.assertUsage(ctx, t, account, now, 1, 1) + + // An unknown attempt keeps its reservation; the retry an hour later + // reuses it, and the one after the 24-hour window counts again. + uncertain := harness.prepare(ctx, t, gate, deliveries[1]) + if !uncertain.Permit.Reused() { + t.Fatal("the second prepare of an open reservation did not reuse it") + } + stored := harness.settle(ctx, t, gate, uncertain, outbound.SendResult{Outcome: outbound.MailOutcomeUnknown}, now.Add(time.Hour)) + harness.now = now.Add(time.Hour) + if retry := harness.prepare(ctx, t, gate, stored); !retry.Proceed() || !retry.Permit.Reused() { + t.Fatalf("retry inside the window: proceed %t, reused %t", retry.Proceed(), retry.Permit.Reused()) + } + harness.assertUsage(ctx, t, account, now, 1, 1) + harness.now = now.Add(resend.IdempotencyWindow + time.Hour) + if late := harness.prepare(ctx, t, gate, stored); !late.Proceed() || late.Permit.Reused() { + t.Fatalf("retry after the window: proceed %t, reused %t", late.Proceed(), late.Permit.Reused()) + } + harness.assertUsage(ctx, t, account, harness.now, 1, 2) + + var open, released, settled int + err := pool.QueryRow(ctx, `SELECT count(*) FILTER (WHERE released_at IS NULL), count(*) FILTER (WHERE released_at IS NOT NULL), + count(*) FILTER (WHERE settled_outcome IS NOT NULL) FROM mail_quota_reservations`).Scan(&open, &released, &settled) + if err != nil || open != 2 || released != 1 || settled != 2 { + t.Fatalf("journal: open %d, released %d, settled %d, %v; want 2, 1, 2", open, released, settled, err) + } + }) + + t.Run("the account sees its waiting mail and nobody else's", func(t *testing.T) { + now := time.Date(2026, 10, 6, 18, 0, 0, 0, time.UTC) + recipient := reset(t, now) + gate := harness.gate(t, "resend", 1, 3000) + account := mustProviderAccount(t, "resend") + reader := notification.NewDeliveryStatusReader(harness.deliveries) + if _, found, err := reader.LatestForUser(ctx, recipient.ID, domain.MailKindNotification); err != nil || found { + t.Fatalf("LatestForUser() before any mail = %t, %v; want nothing", found, err) + } + harness.prepare(ctx, t, gate, harness.createDeliveries(ctx, t, recipient, account, 1)[0]) + harness.now = now.Add(time.Minute) + harness.prepare(ctx, t, gate, harness.createDeliveries(ctx, t, recipient, account, 1)[0]) + + status, found, err := reader.LatestForUser(ctx, recipient.ID, domain.MailKindNotification) + midnight := time.Date(2026, 10, 7, 0, 0, 0, 0, time.UTC) + if err != nil || !found || !status.WaitingForQuota() || !status.WaitingUntil.Equal(midnight) { + t.Fatalf("LatestForUser() = %+v, %t, %v; want waiting until %s", status, found, err, midnight) + } + other := harness.createRecipientWithAddress(ctx, t, "someone.else@example.com") + if _, found, err := reader.LatestForUser(ctx, other.ID, domain.MailKindNotification); err != nil || found { + t.Fatalf("LatestForUser() for another account = %t, %v; want nothing", found, err) + } + if _, found, err := reader.LatestForUser(ctx, recipient.ID, domain.MailKindVerification); err != nil || found { + t.Fatalf("LatestForUser() for another kind = %t, %v; want nothing", found, err) + } + }) + + t.Run("startup reports the usage and a renamed account", func(t *testing.T) { + now := time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + recipient := reset(t, now) + oldLabel, err := domain.NewMailProviderAccount("resend", "old-label") + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + limits, err := domain.NewMailQuotaLimits(100, 3000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + oldGate := notification.NewQuotaGate(oldLabel, limits, resend.IdempotencyWindow, harness.clock, slog.New(slog.NewJSONHandler(harness.logs, nil))) + harness.prepare(ctx, t, oldGate, harness.createDeliveries(ctx, t, recipient, oldLabel, 1)[0]) + harness.prepare(ctx, t, harness.gate(t, "resend", 100, 3000), harness.createDeliveries(ctx, t, recipient, mustProviderAccount(t, "resend"), 1)[0]) + + logs := &syncBuffer{} + reader := postgresadapter.NewMailQuotaStore(pool).MailQuotas() + if err := notification.ReportQuotaUsage(ctx, reader, mustProviderAccount(t, "resend"), limits, now, slog.New(slog.NewJSONHandler(logs, nil))); err != nil { + t.Fatalf("ReportQuotaUsage() error = %v", err) + } + for _, want := range []string{`"account":"integration"`, `"day_used":1`, `"month_used":1`, `"other_accounts":["old-label"]`} { + if !strings.Contains(logs.String(), want) { + t.Fatalf("startup report lacks %s: %s", want, logs.String()) + } + } + }) + + t.Run("the database refuses invalid usage rows", func(t *testing.T) { + reset(t, time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)) + for constraint, statement := range map[string]string{ + "mail_quota_usage_period_kind_known": "INSERT INTO mail_quota_usage VALUES ('resend', 'main', 'week', '2026-10-05', 0, NULL, now())", + "mail_quota_usage_month_starts_on_day_one": "INSERT INTO mail_quota_usage VALUES ('resend', 'main', 'month', '2026-10-05', 0, NULL, now())", + "mail_quota_usage_used_not_negative": "INSERT INTO mail_quota_usage VALUES ('resend', 'main', 'day', '2026-10-05', -1, NULL, now())", + "mail_quota_usage_provider_account_format": "INSERT INTO mail_quota_usage VALUES ('resend', 'Main Account', 'day', '2026-10-05', 0, NULL, now())", + "mail_quota_reservations_windows_match": "INSERT INTO mail_quota_reservations (id, delivery_id, provider, provider_account, day_start, month_start, recipients, reserved_at) " + + "VALUES (gen_random_uuid(), gen_random_uuid(), 'resend', 'main', '2026-11-01', '2026-10-01', 1, now())", + "mail_quota_reservations_outcome_known": "INSERT INTO mail_quota_reservations (id, delivery_id, provider, provider_account, day_start, month_start, recipients, reserved_at, settled_outcome, settled_at) " + + "VALUES (gen_random_uuid(), gen_random_uuid(), 'resend', 'main', '2026-10-05', '2026-10-01', 1, now(), 'sent', now())", + } { + _, err := pool.Exec(ctx, statement) + assertCheckViolation(t, err, constraint) + } + }) +} + +func (harness *quotaHarness) clock() time.Time { return harness.now } + +// quotaStressRounds bounds the concurrency run; a deadlock shows up as a +// 40P01 error after PostgreSQL's deadlock_timeout. +const quotaStressRounds = 60 + +func newReservation(t *testing.T, account domain.MailProviderAccount, at time.Time) outbound.MailQuotaReservation { + t.Helper() + return outbound.MailQuotaReservation{ + ID: uuid.Must(uuid.NewV7()), DeliveryID: uuid.Must(uuid.NewV7()), Account: account, + Windows: domain.MailQuotaWindowsAt(at), Recipients: 1, ReservedAt: at, + } +} + +// reserveDirectly reserves through the repository, without a delivery row. +func (harness *quotaHarness) reserveDirectly(ctx context.Context, t *testing.T, account domain.MailProviderAccount, limits domain.MailQuotaLimits, at time.Time) outbound.MailQuotaReservation { + t.Helper() + var reserved outbound.MailQuotaReservation + err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + result, err := unit.MailQuotas().Reserve(ctx, outbound.MailQuotaReserveRequest{Reservation: newReservation(t, account, at), Limits: limits}) + reserved = result.Reservation + return err + }) + if err != nil { + t.Fatalf("Reserve() error = %v", err) + } + return reserved +} + +// quotaLockWaitTimeout bounds the wait for a writer to queue on a row lock. +const quotaLockWaitTimeout = 10 * time.Second + +// waitForLockWaiters waits until want backends of this database wait for a +// row lock. +func (harness *quotaHarness) waitForLockWaiters(ctx context.Context, t *testing.T, want int) { + t.Helper() + deadline := time.Now().Add(quotaLockWaitTimeout) + for { + var waiting int + err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock'`).Scan(&waiting) + if err != nil { + t.Fatalf("count lock waiters: %v", err) + } + if waiting >= want { + return + } + if time.Now().After(deadline) { + t.Fatalf("%d backends wait for a lock, want %d", waiting, want) + } + time.Sleep(10 * time.Millisecond) + } +} + +// newPoolWithRuntimeParams opens a pool whose sessions use the given +// PostgreSQL settings. +func (env *testEnvironment) newPoolWithRuntimeParams(ctx context.Context, t *testing.T, params map[string]string) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + for key, value := range params { + poolConfig.ConnConfig.RuntimeParams[key] = value + } + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// runAtOnce starts every function at the same moment and returns their +// errors in order. +func runAtOnce(functions ...func() error) []error { + errs := make([]error, len(functions)) + start := make(chan struct{}) + var group sync.WaitGroup + for index, function := range functions { + group.Go(func() { + <-start + errs[index] = function() + }) + } + close(start) + group.Wait() + return errs +} + +func (harness *quotaHarness) gate(t *testing.T, provider string, daily, monthly int64) *notification.QuotaGate { + t.Helper() + limits, err := domain.NewMailQuotaLimits(daily, monthly) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + // SMTP has no provider-side deduplication, so its retries count again. + window := resend.IdempotencyWindow + if provider == "smtp" { + window = 0 + } + return notification.NewQuotaGate(mustProviderAccount(t, provider), limits, window, harness.clock, slog.New(slog.NewJSONHandler(harness.logs, nil))) +} + +// gateFromConfig builds the gate from configuration as bootstrap will, so +// the test covers the configured limits and not only the gate. +func (harness *quotaHarness) gateFromConfig(t *testing.T, mail map[string]string) *notification.QuotaGate { + t.Helper() + settings, err := loadQuotaConfig(mail) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.EmailAccount != quotaAccount { + t.Fatalf("EmailAccount = %q, want %q", settings.EmailAccount, quotaAccount) + } + return harness.gate(t, string(settings.EmailProvider), int64(settings.EmailQuotaDaily), int64(settings.EmailQuotaMonthly)) +} + +func loadQuotaConfig(mail map[string]string) (config.Config, error) { + values := map[string]string{ + "SEAWEEDFS_ACCESS_KEY": "test-access", + "IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab", + "SEAWEEDFS_SECRET_KEY": "test-secret", + "EMAIL_FROM": "no-reply@example.com", + "EMAIL_ACCOUNT": quotaAccount, + "APP_PUBLIC_URL": "http://localhost:8080", + } + for key, value := range mail { + values[key] = value + } + return config.LoadFromEnv(func(key string) (string, bool) { + value, ok := values[key] + return value, ok + }) +} + +func mustProviderAccount(t *testing.T, provider string) domain.MailProviderAccount { + t.Helper() + account, err := domain.NewMailProviderAccount(provider, quotaAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + return account +} + +func (harness *quotaHarness) createRecipientWithAddress(ctx context.Context, t *testing.T, address string) domain.User { + t.Helper() + hash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: mustEmail(t, address), PasswordHash: hash, Scenario: domain.ScenarioCandidate, RegisteredAt: harness.now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.recipients.identity.Users().Create(ctx, user); err != nil { + t.Fatalf("create the recipient account: %v", err) + } + return user +} + +// createDeliveries stores count pending deliveries pinned to account, due at +// the current fake time. +func (harness *quotaHarness) createDeliveries(ctx context.Context, t *testing.T, recipient domain.User, account domain.MailProviderAccount, count int) []domain.Delivery { + t.Helper() + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY quota\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + deliveries := make([]domain.Delivery, 0, count) + for range count { + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), + RecipientUserID: recipient.ID, + Recipient: recipient.Email, + Content: content, + ProviderAccount: account, + CreatedAt: harness.now, + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := harness.deliveries.Create(ctx, delivery); err != nil || !created { + t.Fatalf("Create() = %t, %v; want the delivery stored", created, err) + } + deliveries = append(deliveries, delivery) + } + return deliveries +} + +func (harness *quotaHarness) prepare(ctx context.Context, t *testing.T, gate *notification.QuotaGate, delivery domain.Delivery) notification.SendDecision { + t.Helper() + var decision notification.SendDecision + err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + decision, err = gate.PrepareSend(ctx, unit, delivery) + return err + }) + if err != nil { + t.Fatalf("PrepareSend() error = %v", err) + } + return decision +} + +// settle records the attempt and settles the quota in one transaction, as +// the sending worker will. nextAttempt is the retry policy's choice for a +// pending outcome; the quota decides it for quota_exhausted. +func (harness *quotaHarness) settle( + ctx context.Context, + t *testing.T, + gate *notification.QuotaGate, + decision notification.SendDecision, + result outbound.SendResult, + nextAttempt time.Time, +) domain.Delivery { + t.Helper() + if !decision.Proceed() { + t.Fatal("the send was not admitted") + } + err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + until, err := gate.SettleSend(ctx, unit, decision.Permit, result, nil) + if err != nil { + return err + } + if !until.IsZero() { + nextAttempt = until + } + next, attempt, err := decision.Delivery.RecordAttempt(domain.DeliveryAttemptInput{ + At: harness.now, + Outcome: domain.DeliveryAttemptOutcome(result.Outcome), + Rejection: domain.DeliveryRejection(result.Rejection), + ProviderCode: string(result.ProviderCode), + ProviderMessageID: result.ProviderMessageID, + RetryAfter: result.RetryAfter, + NextAttemptAt: nextAttempt, + }) + if err != nil { + return err + } + return unit.Deliveries().RecordAttempt(ctx, next, attempt) + }) + if err != nil { + t.Fatalf("settle the send: %v", err) + } + return harness.get(ctx, t, decision.Delivery.ID()) +} + +// reserveConcurrently runs one PrepareSend per delivery at once and checks +// that exactly admitted of them got a permit and the rest are stored as +// waiting_quota until resetAt. +func (harness *quotaHarness) reserveConcurrently( + ctx context.Context, + t *testing.T, + gate *notification.QuotaGate, + deliveries []domain.Delivery, + admitted int, + resetAt time.Time, +) { + t.Helper() + decisions := make([]notification.SendDecision, len(deliveries)) + errs := make([]error, len(deliveries)) + start := make(chan struct{}) + var senders sync.WaitGroup + for index, delivery := range deliveries { + senders.Go(func() { + <-start + errs[index] = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + decisions[index], err = gate.PrepareSend(ctx, unit, delivery) + return err + }) + }) + } + close(start) + senders.Wait() + proceeded := 0 + for index, decision := range decisions { + if errs[index] != nil { + t.Fatalf("concurrent PrepareSend() error = %v", errs[index]) + } + if decision.Proceed() { + proceeded++ + continue + } + harness.assertWaiting(ctx, t, decision, deliveries[index].ID(), resetAt) + } + if proceeded != admitted { + t.Fatalf("%d of %d concurrent sends were admitted, want exactly %d", proceeded, len(deliveries), admitted) + } +} + +func (harness *quotaHarness) get(ctx context.Context, t *testing.T, id uuid.UUID) domain.Delivery { + t.Helper() + delivery, err := harness.deliveries.Get(ctx, id) + if err != nil { + t.Fatalf("Get(%s) error = %v", id, err) + } + return delivery +} + +// assertWaiting checks the decision and the stored delivery: the status +// that the operator and the later user-facing status read. +func (harness *quotaHarness) assertWaiting(ctx context.Context, t *testing.T, decision notification.SendDecision, id uuid.UUID, resetAt time.Time) { + t.Helper() + if decision.Proceed() || !decision.ResetAt.Equal(resetAt) { + t.Fatalf("decision: proceed %t, reset %s; want a wait until %s", decision.Proceed(), decision.ResetAt, resetAt) + } + stored := harness.get(ctx, t, id) + if stored.Status() != domain.DeliveryStatusWaitingQuota || !stored.NextAttemptAt().Equal(resetAt) { + t.Fatalf("stored delivery is %s due %s, want waiting_quota due %s", stored.Status(), stored.NextAttemptAt(), resetAt) + } +} + +func (harness *quotaHarness) assertUsage(ctx context.Context, t *testing.T, account domain.MailProviderAccount, at time.Time, day, month int64) { + t.Helper() + windows := domain.MailQuotaWindowsAt(at) + for period, want := range map[domain.MailQuotaPeriod]int64{domain.MailQuotaPeriodDay: day, domain.MailQuotaPeriodMonth: month} { + var used int64 + err := harness.pool.QueryRow(ctx, ` + SELECT coalesce(sum(used_recipients), 0) FROM mail_quota_usage + WHERE provider = $1 AND provider_account = $2 AND period_kind = $3 AND period_start = $4`, + account.Provider(), account.Account(), string(period), windows.Start(period).Format(time.DateOnly)).Scan(&used) + if err != nil { + t.Fatalf("read %s usage: %v", period, err) + } + if used != want { + t.Fatalf("%s usage of %s at %s = %d, want %d", period, account.Provider(), windows.Start(period).Format(time.DateOnly), used, want) + } + } +} + +func (harness *quotaHarness) assertLogsHoldNoPersonalData(t *testing.T) { + t.Helper() + harness.recipients.assertLogsHoldNoPersonalData(t) +} + +func assertCheckViolation(t *testing.T, err error, constraint string) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != "23514" || pgError.ConstraintName != constraint { + t.Fatalf("statement error = %v, want a check violation of %s", err, constraint) + } +} diff --git a/backend/integration_test/mail_retry_migration_test.go b/backend/integration_test/mail_retry_migration_test.go new file mode 100644 index 0000000..3c8ca1f --- /dev/null +++ b/backend/integration_test/mail_retry_migration_test.go @@ -0,0 +1,111 @@ +//go:build integration + +package integration_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +const mailRetryMigrationVersion = 17 + +func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackToMailRetryVersion(ctx, t, migrator) + + deliveryID := uuid.New() + decidedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + if _, err := pool.Exec(ctx, `INSERT INTO delivery_retry_decisions ( + delivery_id, attempt_count, actor, duplicate_risk_acknowledged, previous_lease_expired, decided_at + ) VALUES ($1, 2, 'operator:mail-ops', true, false, $2)`, deliveryID, decidedAt); err != nil { + t.Fatalf("insert retry decision: %v", err) + } + + for _, statement := range []string{ + "UPDATE delivery_retry_decisions SET actor = 'operator:other' WHERE delivery_id = '" + deliveryID.String() + "'", + "DELETE FROM delivery_retry_decisions WHERE delivery_id = '" + deliveryID.String() + "'", + "TRUNCATE delivery_retry_decisions", + } { + _, err := pool.Exec(ctx, statement) + assertSQLRefusal(t, err, "delivery_retry_decisions_immutable") + } + var decisions int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { + t.Fatalf("audit decisions = %d, %v; want one retained record", decisions, err) + } + var predicate string + if err := pool.QueryRow(ctx, `SELECT pg_get_expr(indpred, indrelid) FROM pg_index WHERE indexrelid = 'deliveries_due_idx'::regclass`).Scan(&predicate); err != nil { + t.Fatalf("read deliveries_due_idx predicate: %v", err) + } + if predicate == "" || !containsAll(predicate, "unknown", "next_attempt_at") { + t.Fatalf("deliveries_due_idx predicate = %q; want scheduled unknown rows", predicate) + } + + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != mailRetryMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want rollback of migration %d", result, err, mailRetryMigrationVersion) + } + var auditTable bool + if err := pool.QueryRow(ctx, "SELECT to_regclass('public.delivery_retry_decisions') IS NOT NULL").Scan(&auditTable); err != nil || auditTable { + t.Fatalf("audit table after rollback = %t, %v; want removed", auditTable, err) + } +} + +func rollBackToMailRetryVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", mailRetryMigrationVersion, err) + } + mailRetryApplied := false + laterMigrationApplied := false + for _, status := range statuses { + if !status.Applied { + continue + } + if status.Version == mailRetryMigrationVersion { + mailRetryApplied = true + } + if status.Version > mailRetryMigrationVersion { + laterMigrationApplied = true + } + } + if !mailRetryApplied { + t.Fatalf("migration %d is not applied", mailRetryMigrationVersion) + } + if !laterMigrationApplied { + return + } + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() while preparing migration %d: %v", mailRetryMigrationVersion, err) + } + if result.Version <= mailRetryMigrationVersion { + t.Fatalf("DownOne() rolled back migration %d while preparing migration %d", result.Version, mailRetryMigrationVersion) + } + } +} + +func containsAll(value string, fragments ...string) bool { + for _, fragment := range fragments { + if !strings.Contains(value, fragment) { + return false + } + } + return true +} diff --git a/backend/integration_test/mail_sender_test.go b/backend/integration_test/mail_sender_test.go new file mode 100644 index 0000000..d6ca505 --- /dev/null +++ b/backend/integration_test/mail_sender_test.go @@ -0,0 +1,1979 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/primary/cli/mailretry" + "lincodex/backend/internal/adapter/secondary/mail/disabled" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/worker/mailsender" + "lincodex/backend/internal/worker/retry" +) + +const ( + mailSenderTestTimeout = 5 * time.Minute + mailSenderAccount = "integration" + // The lease runs by the database clock, so the tests that let it expire + // wait in real time; it is short for that. + mailSenderLease = 3 * time.Second + mailSenderSettleBudget = 1500 * time.Millisecond + // mailSenderTokenLifetime is long enough to outlast the idempotency + // window, so a test can move past it without the token expiring first. + mailSenderTokenLifetime = 72 * time.Hour + mailSenderFrom = "Lincodex " + // mailSenderConcurrentWorkers drain the queue at once; each pass holds + // its own connection. + mailSenderConcurrentWorkers = 4 + mailSenderQueued = 8 +) + +var ( + mailSenderStart = mailSenderStartAt(time.Now()) + mailSenderTables = []pgx.Identifier{{"mail_quota_reservations"}, {"mail_quota_usage"}} +) + +// Bounds of the distance from mailSenderStart to the real clock. +const ( + mailSenderStartMinLag = 24 * time.Hour + mailSenderStartMaxLag = 48 * time.Hour +) + +// mailSenderStartAt returns the fake application clock at the start of every +// subtest: 12:00 UTC on the latest day whose noon is at least +// mailSenderStartMinLag before now. The database, the lease, and the +// mail-retry command run by the real clock, and some subtests move the fake +// clock to the database clock, so a fixed calendar date would expire the +// tokens issued at the start once the real clock passed it by +// mailSenderTokenLifetime. With the real clock one to two days ahead: +// - the fake and the database clocks never coincide, so a lease measured by +// the wrong one fails; +// - moving the fake clock by up to 24 hours never overtakes the database +// clock, so a due time that takes the later of both is the database one; +// - a token issued at the start outlives the alignment with the database +// clock by about a day; +// - the next midnight UTC, the quota day boundary, is 12 hours ahead. +func mailSenderStartAt(now time.Time) time.Time { + now = now.UTC() + start := time.Date(now.Year(), now.Month(), now.Day()-1, 12, 0, 0, 0, time.UTC) + if now.Sub(start) < mailSenderStartMinLag { + start = start.AddDate(0, 0, -1) + } + return start +} + +// TestMailSenderStartFollowsTheCalendar checks the bounds that keep +// TestServiceMailSending independent of the day it runs on, across the times +// of a day and month, year, and leap-day boundaries. It needs no database. +func TestMailSenderStartFollowsTheCalendar(t *testing.T) { + if mailSenderStartMaxLag+mailSenderTestTimeout >= mailSenderTokenLifetime { + t.Fatalf("a token issued at the start (%s) can expire before the subtests align with the database clock (up to %s later)", + mailSenderTokenLifetime, mailSenderStartMaxLag+mailSenderTestTimeout) + } + days := []time.Time{ + time.Now().UTC(), + time.Date(2026, 10, 9, 0, 0, 0, 0, time.UTC), + time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + time.Date(2026, 12, 31, 0, 0, 0, 0, time.UTC), + time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC), + time.Date(2028, 2, 29, 0, 0, 0, 0, time.UTC), + time.Date(2028, 3, 1, 0, 0, 0, 0, time.UTC), + } + for _, day := range days { + day = day.Truncate(24 * time.Hour) + for offset := time.Duration(0); offset < 24*time.Hour; offset += 7 * time.Minute { + now := day.Add(offset) + start := mailSenderStartAt(now) + lag := now.Sub(start) + if start.Hour() != 12 || start.Minute() != 0 || start.Second() != 0 || start.Nanosecond() != 0 || start.Location() != time.UTC { + t.Fatalf("start for %s = %s, want 12:00 UTC", now, start) + } + if lag < mailSenderStartMinLag || lag >= mailSenderStartMaxLag { + t.Fatalf("start for %s = %s, %s behind; want %s to %s", now, start, lag, mailSenderStartMinLag, mailSenderStartMaxLag) + } + } + } +} + +// testClock is the application clock of the sending tests. Several workers +// read it at once, so it is guarded. +type testClock struct { + mu sync.Mutex + now time.Time +} + +func (clock *testClock) Now() time.Time { + clock.mu.Lock() + defer clock.mu.Unlock() + return clock.now +} + +func (clock *testClock) Advance(by time.Duration) { + clock.mu.Lock() + defer clock.mu.Unlock() + clock.now = clock.now.Add(by) +} + +func (clock *testClock) Set(at time.Time) { + clock.mu.Lock() + defer clock.mu.Unlock() + clock.now = at +} + +// settlementOutage lets the first two transactions through, the claim and the +// check before the send, +// and fails every later one, as a worker does that loses the database right +// after it called the provider. +type settlementOutage struct { + inner outbound.Transactor + calls atomic.Int32 +} + +func (outage *settlementOutage) WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit outbound.UnitOfWork) error) error { + if outage.calls.Add(1) > 2 { + return errors.New("settlement unavailable") + } + return outage.inner.WithinTransaction(ctx, fn) +} + +// failingTransport fails every call without an answer, as a misconfigured +// transport can. +type failingTransport struct{ err error } + +func (transport failingTransport) Send(context.Context, outbound.OutgoingMail) (outbound.SendResult, error) { + return outbound.SendResult{}, transport.err +} + +// countingPass counts the passes of a worker loop. +type countingPass struct { + inner inbound.MailPass + passes atomic.Int32 +} + +func (pass *countingPass) PauseFailureCounting(paused bool) { pass.inner.PauseFailureCounting(paused) } + +func (pass *countingPass) ProcessNext(ctx, workCtx context.Context) (inbound.MailPassResult, error) { + pass.passes.Add(1) + return pass.inner.ProcessNext(ctx, workCtx) +} + +type senderHarness struct { + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + identity *postgresadapter.IdentityStore + deliveries outbound.DeliveryRepository + mailer *notification.ServiceMailer + fixture *resendfixture.Server + transport outbound.MailSender + account domain.MailProviderAccount + clock *testClock + logs *syncBuffer + publicURL string + users int +} + +func TestServiceMailSending(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), mailSenderTestTimeout) + defer cancel() + pool := env.newPoolWithMaxConns(ctx, t, mailSenderConcurrentWorkers*2+4) + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + fixture := resendfixture.New() + t.Cleanup(fixture.Close) + clock := &testClock{now: mailSenderStart} + fixture.SetClock(clock.Now) + transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now) + if err != nil { + t.Fatalf("NewLoopbackSender() error = %v", err) + } + account, err := domain.NewMailProviderAccount("resend", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + harness := &senderHarness{ + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + identity: postgresadapter.NewIdentityStore(pool), + deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(), + mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now), + fixture: fixture, + transport: transport, + account: account, + clock: clock, + logs: &syncBuffer{}, + publicURL: env.Config.AppPublicURL, + } + reset := func(t *testing.T) { + t.Helper() + // The fixture keeps what it received; a new one per subtest would + // need a new transport, so the tests compare against the counts at + // their start instead. + truncateTables(ctx, t, pool, slices.Concat(mailSenderTables, usersDependentTables)...) + clock.Set(mailSenderStart) + fixture.SetClock(clock.Now) + fixture.SetDelay(0) + // A subtest that stops early leaves its scripted answers queued; + // drop them so its failure is not repeated by the next subtests. + // A subtest that passes must have used every answer it scripted. + fixture.ClearScript() + t.Cleanup(func() { + if left := fixture.ClearScript(); left != 0 && !t.Failed() { + t.Errorf("the subtest left %d scripted provider answers unused", left) + } + }) + } + + t.Run("a service email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + raw, token, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + // The account has no consent record of any purpose: C2 is the + // publication of the candidate card, and a service mail needs none. + assertRowCount(ctx, t, pool, pgx.Identifier{"consent_records"}, 0) + + stored := harness.delivery(ctx, t, deliveryID) + switch { + case stored.Status() != domain.DeliveryStatusPending || stored.Kind() != domain.MailKindVerification: + t.Fatalf("enqueued delivery is %s of kind %s", stored.Status(), stored.Kind()) + case stored.EmailTokenID() != token.ID || deliveryID != token.ID: + t.Fatal("the delivery is not bound to the token it was enqueued for") + case stored.IdempotencyKey() != "delivery/"+deliveryID.String(): + t.Fatalf("idempotency key = %q", stored.IdempotencyKey()) + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("pass = %+v, want accepted for the enqueued delivery", result) + } + + requests := fixture.Requests()[calls:] + if len(requests) != 1 { + t.Fatalf("the fixture received %d calls, want 1", len(requests)) + } + request := requests[0] + link := harness.publicURL + "/verify-email#token=" + raw.Reveal() + switch { + case request.IdempotencyKey != "delivery/"+deliveryID.String(): + t.Fatalf("idempotency key sent = %q", request.IdempotencyKey) + case len(request.To) != 1 || request.To[0] != user.Email.Address(): + t.Fatal("the message was not addressed to the account") + case !strings.Contains(request.Text, link) || !strings.Contains(request.HTML, link): + t.Fatal("the message does not carry the verification link with its token in the fragment") + case strings.Contains(request.Text, "?token=") || strings.Contains(request.HTML, "?token="): + t.Fatal("the token travels in a query") + } + + accepted := harness.delivery(ctx, t, deliveryID) + if accepted.Status() != domain.DeliveryStatusAccepted || accepted.ProviderMessageID() == "" || + accepted.AttemptCount() != 1 || !accepted.NextAttemptAt().IsZero() { + t.Fatalf("delivery is %s with %d attempts and message ID %q, want accepted by the provider after one attempt", + accepted.Status(), accepted.AttemptCount(), accepted.ProviderMessageID()) + } + attempts := harness.attempts(ctx, t, deliveryID) + if len(attempts) != 1 || attempts[0].Outcome != domain.DeliveryOutcomeAccepted || attempts[0].StatusAfter != domain.DeliveryStatusAccepted { + t.Fatalf("attempts = %+v, want one accepted attempt", attempts) + } + harness.assertQuotaUsage(ctx, t, 1) + harness.assertClaimReleased(ctx, t, deliveryID) + + // The account sees the provider's acceptance, and a second pass has + // nothing to do. + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, user.ID, domain.MailKindVerification) + if err != nil || !found || status.Status != domain.DeliveryStatusAccepted { + t.Fatalf("LatestForUser() = %+v, %t, %v; want accepted", status, found, err) + } + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("second pass = %+v, want idle", again) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the second pass called the provider again") + } + harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email") + }) + + t.Run("a password reset email for an account without C2 is accepted by the local Resend fixture", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, true) + raw, token, deliveryID := harness.enqueuePasswordReset(ctx, t, user, mailSenderTokenLifetime) + assertRowCount(ctx, t, pool, pgx.Identifier{"consent_records"}, 0) + + stored := harness.delivery(ctx, t, deliveryID) + if stored.Status() != domain.DeliveryStatusPending || stored.Kind() != domain.MailKindPasswordReset || stored.EmailTokenID() != token.ID { + t.Fatalf("enqueued delivery is %s of kind %s bound to %v", stored.Status(), stored.Kind(), stored.EmailTokenID()) + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("pass = %+v, want accepted for the enqueued delivery", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 1 { + t.Fatalf("the fixture received %d calls, want 1", len(requests)) + } + request := requests[0] + link := harness.publicURL + "/reset-password#token=" + raw.Reveal() + switch { + case len(request.To) != 1 || request.To[0] != user.Email.Address(): + t.Fatal("the message was not addressed to the account") + case !strings.Contains(request.Text, link) || !strings.Contains(request.HTML, link): + t.Fatal("the message does not carry the reset link with its token in the fragment") + case strings.Contains(request.Text, "?token=") || strings.Contains(request.HTML, "?token="): + t.Fatal("the token travels in a query") + } + accepted := harness.delivery(ctx, t, deliveryID) + if accepted.Status() != domain.DeliveryStatusAccepted || accepted.AttemptCount() != 1 { + t.Fatalf("delivery is %s after %d attempts, want accepted after one attempt", accepted.Status(), accepted.AttemptCount()) + } + harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "reset-password") + }) + + t.Run("a verification mail goes out after the account's C2 was granted and revoked before the worker runs", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + + // C2 is granted and revoked while the mail waits. The publication + // history must not hold the mail back: only the account and the token + // decide, as ServiceMailState reads nothing else. + c2Text, err := postgresadapter.NewConsentStore(pool).ConsentTexts().Current(ctx, domain.ConsentPurposePublication, harness.clock.Now()) + if err != nil { + t.Fatalf("read the current C2 text: %v", err) + } + consentService := consent.NewService(harness.transactor, harness.clock.Now) + granted, err := consentService.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{ + SubjectID: user.ID, Purpose: domain.ConsentPurposePublication, TextVersion: c2Text.Version(), + }) + if err != nil || !granted.Created { + t.Fatalf("grant C2 = created %t, %v; want a new record", granted.Created, err) + } + revocation, err := consentService.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{ + SubjectID: user.ID, Purpose: domain.ConsentPurposePublication, + }) + if err != nil || len(revocation.Records) != 1 { + t.Fatalf("revoke C2 = %d records, %v; want one revoked record", len(revocation.Records), err) + } + if _, revoked := revocation.Records[0].RevokedAt(); !revoked { + t.Fatal("the C2 record is not revoked") + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("pass = %+v, want the verification mail accepted after C2 was revoked", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 1 || len(requests[0].To) != 1 || requests[0].To[0] != user.Email.Address() { + t.Fatalf("the fixture received %d calls, want one to the account", len(requests)) + } + }) + + t.Run("an accepted request with a lost response retries under the same key within 24 hours", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + fixture.Script(resendfixture.Reply{DropAfterAccept: true}) + + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass after the fixture accepted and dropped the response = %+v, want unknown", result) + } + uncertain := harness.delivery(ctx, t, deliveryID) + if uncertain.Status() != domain.DeliveryStatusUnknown || !uncertain.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) { + t.Fatalf("delivery is %s due %s, want unknown with a bounded retry", uncertain.Status(), uncertain.NextAttemptAt()) + } + if fixture.Messages()-messages != 1 { + t.Fatalf("fixture accepted %d messages, want exactly one before the retry", fixture.Messages()-messages) + } + + harness.clock.Advance(time.Minute) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass within the provider window = %+v, want the original acceptance", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || + requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed || + !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || + requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { + t.Fatalf("provider calls = %+v, want the same pinned key and stored body, replayed once", requests) + } + stored := harness.delivery(ctx, t, deliveryID) + if stored.ProviderAccount() != harness.account || stored.Status() != domain.DeliveryStatusAccepted || + stored.AttemptCount() != 2 || fixture.Messages()-messages != 1 { + t.Fatalf("delivery is %s on %s after %d attempts, fixture has %d new message(s); want pinned account, accepted, two calls, one message", + stored.Status(), stored.ProviderAccount().Account(), stored.AttemptCount(), fixture.Messages()-messages) + } + }) + + t.Run("a worker that holds a delivery keeps every other worker off it", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + arrivals := fixture.Arrivals() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + first := harness.newSender(t, harness.transactor, 100, 3000) + second := harness.newSender(t, harness.transactor, 100, 3000) + + // The provider answers slowly, so the first worker is in the middle + // of its send, holding the lease, when the second one looks. + fixture.SetDelay(500 * time.Millisecond) + firstResult := make(chan inbound.MailPassResult, 1) + go func() { + result, err := first.ProcessNext(ctx, ctx) + if err != nil { + t.Errorf("first ProcessNext() error = %v", err) + } + firstResult <- result + }() + waitFor(ctx, t, "the first worker's request to reach the provider", func() bool { return fixture.Arrivals() == arrivals+1 }) + + if result := harness.pass(ctx, t, second); result.Outcome != inbound.MailPassIdle { + t.Fatalf("the second worker's pass = %+v, want idle while the first one holds the delivery", result) + } + if result := <-firstResult; result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("the first worker's pass = %+v, want accepted", result) + } + fixture.SetDelay(0) + + requests := fixture.Requests()[calls:] + if len(requests) != 1 || requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || requests[0].Replayed { + t.Fatalf("provider calls = %+v, want exactly one under the delivery key", requests) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 1) + if got := harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { + t.Fatalf("delivery is %s with %d attempts, want accepted after one", got.Status(), got.AttemptCount()) + } + }) + + t.Run("workers racing for a queue send each delivery exactly once", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + ids := make(map[uuid.UUID]bool, mailSenderQueued) + for range mailSenderQueued { + user := harness.createUser(ctx, t, false) + _, _, id := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + ids[id] = true + } + var accepted atomic.Int32 + var workers sync.WaitGroup + for range mailSenderConcurrentWorkers { + sender := harness.newSender(t, harness.transactor, 100, 3000) + workers.Go(func() { + for { + result, err := sender.ProcessNext(ctx, ctx) + if err != nil { + t.Errorf("ProcessNext() error = %v", err) + return + } + if result.Outcome == inbound.MailPassIdle { + return + } + if result.Outcome == inbound.MailPassAccepted { + accepted.Add(1) + } + } + }) + } + workers.Wait() + + if accepted.Load() != mailSenderQueued { + t.Fatalf("%d deliveries were accepted, want %d", accepted.Load(), mailSenderQueued) + } + requests := fixture.Requests()[calls:] + keys := make(map[string]int, len(requests)) + for _, request := range requests { + keys[request.IdempotencyKey]++ + if request.Replayed { + t.Fatalf("a delivery was sent twice: %s", request.IdempotencyKey) + } + } + if len(requests) != mailSenderQueued || len(keys) != mailSenderQueued || fixture.Messages()-messages != mailSenderQueued { + t.Fatalf("provider calls = %d with %d keys and %d messages, want %d of each", len(requests), len(keys), fixture.Messages()-messages, mailSenderQueued) + } + for id := range ids { + if got := harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { + t.Fatalf("a delivery is %s with %d attempts, want accepted after one", got.Status(), got.AttemptCount()) + } + } + harness.assertQuotaUsage(ctx, t, mailSenderQueued) + }) + + t.Run("a worker that stopped after sending is replaced and the provider sees the same key", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + + // The first worker's request is accepted, but the database fails + // before it can store the answer: it dies holding the lease. + failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) + if _, err := failing.ProcessNext(ctx, ctx); err == nil { + t.Fatal("ProcessNext() with a failing settlement returned no error") + } + if got := harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { + t.Fatalf("the delivery is %s with %d attempts, want pending with none: nothing was stored", got.Status(), got.AttemptCount()) + } + if owner, _ := harness.claimOf(ctx, t, deliveryID); owner == nil { + t.Fatal("the stopped worker's lease is gone") + } + + // While the lease lives, no other worker takes the delivery. + replacement := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassIdle { + t.Fatalf("pass under a live lease = %+v, want idle", result) + } + // After the lease expires the replacement repeats the request under + // the same key; the provider answers with the original message. + time.Sleep(mailSenderLease + 300*time.Millisecond) + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after the lease expired = %+v, want accepted", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || + requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed { + t.Fatalf("provider calls = %+v, want two calls under one key, the second a replay", requests) + } + if fixture.Messages()-messages != 1 { + t.Fatalf("the provider holds %d new messages, want 1", fixture.Messages()-messages) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"delivery_attempts"}, 1) + // The open reservation was reused: the message counts once. + harness.assertQuotaUsage(ctx, t, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_quota_reservations"}, 1) + }) + + t.Run("an attempt lost beyond the idempotency window is unknown and is not sent again", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) + if _, err := failing.ProcessNext(ctx, ctx); err == nil { + t.Fatal("ProcessNext() with a failing settlement returned no error") + } + + // Every worker was gone for longer than the provider remembers keys, + // counted from the first request, whatever the latest lease says. + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = first_send_started_at - interval '25 hours' WHERE id = $1", deliveryID) + time.Sleep(mailSenderLease + 300*time.Millisecond) + replacement := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass = %+v, want unknown", result) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the delivery was sent again although the provider may have forgotten its key") + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusUnknown || got.AttemptCount() != 1 || !got.NextAttemptAt().IsZero() { + t.Fatalf("delivery is %s with %d attempts and a next attempt %s, want unknown after one, for an operator", got.Status(), got.AttemptCount(), got.NextAttemptAt()) + } + if again := harness.pass(ctx, t, replacement); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after the unknown record = %+v, want idle", again) + } + }) + + t.Run("a revoked token or an account that moved on sends nothing and ends with a reason", func(t *testing.T) { + tests := []struct { + name string + change func(ctx context.Context, t *testing.T, user domain.User, token domain.EmailToken, raw domain.SecretToken) + want domain.DeliveryCancelReason + }{ + { + name: "token revoked by a resend", + change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { + t.Helper() + invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()) + if err != nil || invalidated != 1 { + t.Fatalf("InvalidateActive() = %d, %v; want 1", invalidated, err) + } + }, + want: domain.DeliveryCancelTokenRevoked, + }, + { + name: "token already used", + change: func(ctx context.Context, t *testing.T, _ domain.User, _ domain.EmailToken, raw domain.SecretToken) { + t.Helper() + if _, err := harness.identity.EmailTokens().Consume(ctx, raw.Hash(), domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil { + t.Fatalf("Consume() error = %v", err) + } + }, + want: domain.DeliveryCancelTokenConsumed, + }, + { + name: "token expired", + change: func(_ context.Context, _ *testing.T, _ domain.User, token domain.EmailToken, _ domain.SecretToken) { + harness.clock.Set(token.ExpiresAt) + }, + want: domain.DeliveryCancelTokenExpired, + }, + { + name: "account registered again", + change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { + t.Helper() + harness.exec(ctx, t, "UPDATE users SET registration_version = registration_version + 1 WHERE id = $1", user.ID) + }, + want: domain.DeliveryCancelAccountNotCurrent, + }, + { + name: "address already verified", + change: func(ctx context.Context, t *testing.T, user domain.User, token domain.EmailToken, _ domain.SecretToken) { + t.Helper() + if _, err := harness.identity.Users().MarkEmailVerified(ctx, user.ID, token.RegistrationVersion, harness.clock.Now()); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + }, + want: domain.DeliveryCancelAccountNotCurrent, + }, + { + name: "address of the account changed", + change: func(ctx context.Context, t *testing.T, user domain.User, _ domain.EmailToken, _ domain.SecretToken) { + t.Helper() + harness.exec(ctx, t, "UPDATE users SET email = 'moved.on@example.com', email_normalized = 'moved.on@example.com' WHERE id = $1", user.ID) + }, + want: domain.DeliveryCancelRecipientMismatch, + }, + { + name: "token of another purpose", + change: func(ctx context.Context, t *testing.T, _ domain.User, token domain.EmailToken, _ domain.SecretToken) { + t.Helper() + harness.exec(ctx, t, "UPDATE email_tokens SET purpose = 'password_reset' WHERE id = $1", token.ID) + }, + want: domain.DeliveryCancelTokenPurposeMismatch, + }, + } + reset(t) + calls := len(fixture.Requests()) + sender := harness.newSender(t, harness.transactor, 100, 3000) + for _, test := range tests { + user := harness.createUser(ctx, t, false) + raw, token, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) + test.change(ctx, t, user, token, raw) + + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassCancelled || result.CancelReason != test.want || result.DeliveryID != deliveryID { + t.Fatalf("%s: pass = %+v, want cancelled with reason %s", test.name, result, test.want) + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusCancelled || got.CancelReason() != test.want || + got.AttemptCount() != 0 || !got.NextAttemptAt().IsZero() || got.ProviderMessageID() != "" { + t.Fatalf("%s: delivery is %s (%s) with %d attempts, want cancelled with reason %s and no attempt", + test.name, got.Status(), got.CancelReason(), got.AttemptCount(), test.want) + } + harness.assertClaimReleased(ctx, t, deliveryID) + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("%s: pass after the cancellation = %+v, want idle", test.name, again) + } + if _, _, err := got.RecordAttempt(domain.DeliveryAttemptInput{At: harness.clock.Now(), Outcome: domain.DeliveryOutcomeUnknown}); !errors.Is(err, domain.ErrDeliveryTransition) { + t.Fatalf("%s: an attempt on a cancelled delivery error = %v, want ErrDeliveryTransition", test.name, err) + } + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, user.ID, domain.MailKindVerification) + if err != nil || !found || status.Status != domain.DeliveryStatusCancelled { + t.Fatalf("%s: LatestForUser() = %+v, %t, %v; want cancelled", test.name, status, found, err) + } + harness.clock.Set(mailSenderStart) + } + if got := len(fixture.Requests()[calls:]); got != 0 { + t.Fatalf("the provider received %d calls, want none: an invalid mail was sent", got) + } + // Nothing was reserved or counted for mail that never went out. + assertRowCount(ctx, t, pool, pgx.Identifier{"mail_quota_reservations"}, 0) + harness.assertQuotaUsage(ctx, t, 0) + }) + + t.Run("a verification mail revoked before its send is cancelled, keeps its account, and stays out of the logs", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + raw, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + if invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil || invalidated != 1 { + t.Fatalf("InvalidateActive() = %d, %v; want 1", invalidated, err) + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelTokenRevoked { + t.Fatalf("pass = %+v, want cancelled with reason %s", result, domain.DeliveryCancelTokenRevoked) + } + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after the cancellation = %+v, want idle", again) + } + if got := len(fixture.Requests()[calls:]); got != 0 { + t.Fatalf("the provider received %d calls, want none for a revoked mail", got) + } + + cancelled := harness.delivery(ctx, t, deliveryID) + switch { + case cancelled.Status() != domain.DeliveryStatusCancelled || cancelled.CancelReason() != domain.DeliveryCancelTokenRevoked: + t.Fatalf("delivery is %s (%s), want cancelled by a revoked token", cancelled.Status(), cancelled.CancelReason()) + case cancelled.ProviderAccount() != harness.account || cancelled.AttemptCount() != 0 || cancelled.ProviderMessageID() != "": + t.Fatal("the cancellation changed the transport account or recorded an attempt") + case !cancelled.Content().Redacted() || cancelled.Content().Text() != "": + t.Fatal("the body of the cancelled mail is still stored") + } + // The address, the token, the link, and the account ID never reach the logs. + harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), user.ID.String(), "verify-email") + }) + + t.Run("a delivery that cannot be restored is cancelled and does not block the queue", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + poisoned := harness.createUser(ctx, t, false) + _, _, poisonedID := harness.enqueueVerification(ctx, t, poisoned, mailSenderTokenLifetime) + healthy := harness.createUser(ctx, t, false) + _, _, healthyID := harness.enqueueVerification(ctx, t, healthy, mailSenderTokenLifetime) + + // The content trigger refuses any change of a stored body, so the + // test lifts it for one statement to break the content hash, as a + // manual edit of the table would. + harness.exec(ctx, t, "ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change") + _, err := pool.Exec(ctx, "UPDATE deliveries SET content_sha256 = $2 WHERE id = $1", poisonedID, make([]byte, 32)) + harness.exec(ctx, t, "ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change") + if err != nil { + t.Fatalf("break the content hash: %v", err) + } + if _, err := harness.deliveries.Get(ctx, poisonedID); !errors.Is(err, domain.ErrMailContentIntegrity) { + t.Fatalf("Get() of the broken delivery error = %v, want ErrMailContentIntegrity", err) + } + + sender := harness.newSender(t, harness.transactor, 100, 3000) + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassCancelled || result.DeliveryID != poisonedID || result.CancelReason != domain.DeliveryCancelContentInvalid { + t.Fatalf("pass = %+v, want the broken delivery cancelled as content_invalid", result) + } + var status, reason string + var version int64 + if err := pool.QueryRow(ctx, "SELECT status, cancel_reason, version FROM deliveries WHERE id = $1", poisonedID).Scan(&status, &reason, &version); err != nil || + status != "cancelled" || reason != "content_invalid" || version != 2 { + t.Fatalf("broken delivery is %q (%q) at version %d, %v; want cancelled content_invalid at version 2", status, reason, version, err) + } + harness.assertClaimReleased(ctx, t, poisonedID) + if len(fixture.Requests()[calls:]) != 0 { + t.Fatal("a broken delivery reached the provider") + } + + // The delivery behind it is sent in the next pass. + if next := harness.pass(ctx, t, sender); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthyID { + t.Fatalf("next pass = %+v, want the healthy delivery accepted", next) + } + harness.assertLogsHoldNoSecrets(t, poisoned.Email.Address(), healthy.Email.Address()) + }) + + t.Run("a row that fails for a reason of its own moves back in the queue and is cancelled after repeated failures", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + broken := harness.createUser(ctx, t, false) + _, _, brokenID := harness.enqueueVerification(ctx, t, broken, mailSenderTokenLifetime) + healthy := harness.createUser(ctx, t, false) + _, _, healthyID := harness.enqueueVerification(ctx, t, healthy, mailSenderTokenLifetime) + + // A subject with a line break passes the table and fails the domain's + // rules, so the row cannot be restored although its hash is intact: + // a deterministic fault that is not a hash mismatch. + harness.exec(ctx, t, "ALTER TABLE deliveries DISABLE TRIGGER deliveries_refuse_content_change") + _, err := pool.Exec(ctx, "UPDATE deliveries SET subject = E'broken\nsubject' WHERE id = $1", brokenID) + harness.exec(ctx, t, "ALTER TABLE deliveries ENABLE TRIGGER deliveries_refuse_content_change") + if err != nil { + t.Fatalf("break the subject: %v", err) + } + sender := harness.newSender(t, harness.transactor, 100, 3000) + + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassRowFailed || result.DeliveryID != brokenID { + t.Fatalf("first pass = %+v, want row_failed for the broken delivery", result) + } + var failures int + var due time.Time + if err := pool.QueryRow(ctx, "SELECT failure_count, next_attempt_at FROM deliveries WHERE id = $1", brokenID).Scan(&failures, &due); err != nil || + failures != 1 || !due.Equal(mailSenderStart.Add(time.Minute)) { + t.Fatalf("broken row: %d failures due %s, %v; want 1 failure due a minute later", failures, due, err) + } + harness.assertClaimReleased(ctx, t, brokenID) + // It is not claimed again at once, and the delivery behind it is sent. + if next := harness.pass(ctx, t, sender); next.Outcome != inbound.MailPassAccepted || next.DeliveryID != healthyID { + t.Fatalf("second pass = %+v, want the healthy delivery accepted", next) + } + // Each failure pushes the row further; the third cancels it. + harness.clock.Advance(time.Hour) + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassRowFailed { + t.Fatalf("pass at the second due time = %+v, want row_failed", again) + } + harness.clock.Advance(2 * time.Hour) + final := harness.pass(ctx, t, sender) + if final.Outcome != inbound.MailPassCancelled || final.CancelReason != domain.DeliveryCancelProcessingFailed { + t.Fatalf("third failure = %+v, want cancelled as processing_failed", final) + } + var status, reason string + var redacted *time.Time + if err := pool.QueryRow(ctx, "SELECT status, cancel_reason, body_redacted_at FROM deliveries WHERE id = $1", brokenID).Scan(&status, &reason, &redacted); err != nil || + status != "cancelled" || reason != "processing_failed" || redacted == nil { + t.Fatalf("broken row is %q (%q) redacted %v, %v; want cancelled processing_failed with its bodies cleared", status, reason, redacted, err) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the broken delivery reached the provider") + } + harness.assertLogsHoldNoSecrets(t, broken.Email.Address(), healthy.Email.Address()) + }) + + t.Run("a transport error without an answer moves the row back without counting it, not a loop at the head of the queue", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + faulty := *harness + faulty.transport = failingTransport{err: errors.New("transport is misconfigured")} + sender := faulty.newSender(t, harness.transactor, 100, 3000) + + result := faulty.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassInterrupted || result.DeliveryID != deliveryID { + t.Fatalf("pass = %+v, want interrupted: the fault is not counted against the row", result) + } + var failures int + if err := pool.QueryRow(ctx, "SELECT failure_count FROM deliveries WHERE id = $1", deliveryID).Scan(&failures); err != nil || failures != 0 { + t.Fatalf("failure_count = %d, %v; want 0", failures, err) + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 || !got.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) { + t.Fatalf("delivery is %s due %s after %d attempts, want pending due a minute later with none", got.Status(), got.NextAttemptAt(), got.AttemptCount()) + } + harness.assertClaimReleased(ctx, t, deliveryID) + harness.assertQuotaUsage(ctx, t, 0) + if again := faulty.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass before the due time = %+v, want idle", again) + } + }) + + t.Run("a failure is recorded only for a row that no other worker holds", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + holder, stranger := uuid.New(), uuid.New() + if _, err := harness.deliveries.ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: holder, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, + }); err != nil { + t.Fatalf("ClaimDue() error = %v", err) + } + at := harness.clock.Now() + // A stranger whose claim rolled back must not touch a row that the + // holder has just claimed. + moved, err := harness.deliveries.RecordFailure(ctx, deliveryID, stranger, at, at.Add(time.Hour), 3, true) + if err != nil || moved { + t.Fatalf("RecordFailure() by a stranger = %t, %v; want it to leave the row alone", moved, err) + } + var failures int + var due time.Time + if err := pool.QueryRow(ctx, "SELECT failure_count, next_attempt_at FROM deliveries WHERE id = $1", deliveryID).Scan(&failures, &due); err != nil || + failures != 0 || !due.Equal(at) { + t.Fatalf("row after a stranger's failure: %d failures due %s, %v; want it untouched", failures, due, err) + } + if owner, _ := harness.claimOf(ctx, t, deliveryID); owner == nil || *owner != holder { + t.Fatal("a stranger's failure cleared the holder's lease") + } + // The holder itself may record it; counting can be switched off. + if _, err := harness.deliveries.RecordFailure(ctx, deliveryID, holder, at, at.Add(time.Hour), 3, false); err != nil { + t.Fatalf("RecordFailure() by the holder error = %v", err) + } + if err := pool.QueryRow(ctx, "SELECT failure_count FROM deliveries WHERE id = $1", deliveryID).Scan(&failures); err != nil || failures != 0 { + t.Fatalf("failure_count after an uncounted failure = %d, %v; want 0", failures, err) + } + harness.assertClaimReleased(ctx, t, deliveryID) + }) + + t.Run("the first request, not the latest lease, starts the idempotency window", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + // Three workers in a row stop after the call. Each takeover is only + // seconds after the lease before it, so counting from the latest lease + // would never see the age of the first request. + for cycle := range 3 { + failing := harness.newSender(t, &settlementOutage{inner: harness.transactor}, 100, 3000) + if _, err := failing.ProcessNext(ctx, ctx); err == nil { + t.Fatalf("cycle %d: ProcessNext() with a failing settlement returned no error", cycle) + } + time.Sleep(mailSenderLease + 300*time.Millisecond) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = first_send_started_at - interval '8 hours' WHERE id = $1", deliveryID) + } + replacement := harness.newSender(t, harness.transactor, 100, 3000) + // 24 hours after the first request, 23 with the safety margin. + if result := harness.pass(ctx, t, replacement); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass = %+v, want unknown: the first request is 24 hours old", result) + } + if got := len(fixture.Requests()[calls:]); got != 3 { + t.Fatalf("provider calls = %d, want the three of the lost workers and no fourth", got) + } + }) + + t.Run("the lease follows the database clock and a result is recorded only by the lease holder", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + owner, other := uuid.New(), uuid.New() + claimed, err := harness.deliveries.ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, + }) + if err != nil || claimed.Delivery.ID() != deliveryID { + t.Fatalf("ClaimDue() = %v, %v; want the enqueued delivery", claimed.Delivery.ID(), err) + } + // The fake application clock is one to two days behind the database + // clock; the lease must be measured by the database one. + var live, bounded bool + if err := pool.QueryRow(ctx, `SELECT claimed_until > clock_timestamp(), claimed_until <= clock_timestamp() + interval '3 seconds' + FROM deliveries WHERE id = $1`, deliveryID).Scan(&live, &bounded); err != nil || !live || !bounded { + t.Fatalf("lease live = %t, within its length = %t, %v; want a lease of 3 seconds by the database clock", live, bounded, err) + } + next, attempt, err := claimed.Delivery.RecordAttempt(domain.DeliveryAttemptInput{ + At: harness.clock.Now(), Outcome: domain.DeliveryOutcomeAccepted, ProviderMessageID: deliveryMessageID, + }) + if err != nil { + t.Fatalf("RecordAttempt() error = %v", err) + } + if err := harness.deliveries.RecordClaimedAttempt(ctx, other, next, attempt); !errors.Is(err, outbound.ErrDeliveryVersionConflict) { + t.Fatalf("RecordClaimedAttempt() by a stranger error = %v, want ErrDeliveryVersionConflict", err) + } + if held, err := harness.deliveries.LockClaimed(ctx, deliveryID, other); err != nil || held { + t.Fatalf("LockClaimed() by a stranger = %t, %v; want false", held, err) + } + if err := harness.deliveries.RecordClaimedAttempt(ctx, owner, next, attempt); err != nil { + t.Fatalf("RecordClaimedAttempt() by the holder error = %v", err) + } + }) + + t.Run("the claim query reads the small due index, not the notification backlog", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, true) + harness.exec(ctx, t, `INSERT INTO deliveries ( + id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256, + provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at + ) + SELECT gen_random_uuid(), $1, 'backlog@example.com', 'notification', 'notification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'), + 'resend', $2, 'delivery/backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3 + FROM generate_series(1, 5000) AS n`, user.ID, mailSenderAccount, mailSenderStart) + harness.exec(ctx, t, "ANALYZE deliveries") + rows, err := pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due + WHERE due.kind IN ('verification', 'password_reset') AND due.kind = any($1::text[]) + AND due.status IN ('pending', 'waiting_quota') AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= $2::timestamptz AND due.provider = 'resend' AND due.provider_account = $3 + AND (due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp()) + ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED`, + []string{"verification", "password_reset"}, mailSenderStart, mailSenderAccount) + if err != nil { + t.Fatalf("explain the claim: %v", err) + } + defer rows.Close() + var plan strings.Builder + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatalf("scan the plan: %v", err) + } + plan.WriteString(line + "\n") + } + if !strings.Contains(plan.String(), "deliveries_due_idx") || strings.Contains(plan.String(), "Seq Scan") { + t.Fatalf("the claim does not use deliveries_due_idx over 5000 notification rows:\n%s", plan.String()) + } + }) + + t.Run("overdue service mail ignores a notification backlog", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, true) + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "s", "t\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + notificationDelivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), RecipientUserID: user.ID, Recipient: user.Email, Content: content, + ProviderAccount: harness.account, CreatedAt: mailSenderStart.Add(-48 * time.Hour), + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := harness.deliveries.Create(ctx, notificationDelivery); err != nil || !created { + t.Fatalf("Create() = %t, %v", created, err) + } + reader := postgresadapter.NewDeliveryStatisticsStore(pool) + statistics, err := reader.DeliveryStatistics(ctx) + if err != nil || !statistics.EarliestPendingAttemptAt.IsZero() { + t.Fatalf("DeliveryStatistics() earliest = %s, %v; want none for a notification-only backlog", statistics.EarliestPendingAttemptAt, err) + } + other := harness.createUser(ctx, t, false) + _, _, serviceID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) + statistics, err = reader.DeliveryStatistics(ctx) + due := harness.delivery(ctx, t, serviceID).NextAttemptAt() + if err != nil || !statistics.EarliestPendingAttemptAt.Equal(due) { + t.Fatalf("DeliveryStatistics() earliest = %s, %v; want the service mail's due time %s", statistics.EarliestPendingAttemptAt, err, due) + } + }) + + t.Run("a token mail loses its bodies when it ends, and only then", func(t *testing.T) { + reset(t) + accepted := harness.createUser(ctx, t, false) + raw, _, acceptedID := harness.enqueueVerification(ctx, t, accepted, mailSenderTokenLifetime) + revoked := harness.createUser(ctx, t, false) + revokedRaw, _, revokedID := harness.enqueueVerification(ctx, t, revoked, mailSenderTokenLifetime) + if invalidated, err := harness.identity.EmailTokens().InvalidateActive(ctx, revoked.ID, domain.EmailTokenPurposeEmailVerification, harness.clock.Now()); err != nil || invalidated != 1 { + t.Fatalf("InvalidateActive() = %d, %v", invalidated, err) + } + // While the mail waits, its body is the token's only home. + var text string + if err := pool.QueryRow(ctx, "SELECT text_body FROM deliveries WHERE id = $1", acceptedID).Scan(&text); err != nil || !strings.Contains(text, raw.Reveal()) { + t.Fatalf("a waiting mail has no body: %v", err) + } + _, err := pool.Exec(ctx, "UPDATE deliveries SET text_body = '', html_body = '', body_redacted_at = now() WHERE id = $1", acceptedID) + assertSQLRefusal(t, err, "deliveries_content_immutable") + + sender := harness.newSender(t, harness.transactor, 100, 3000) + for range 2 { + harness.pass(ctx, t, sender) + } + for name, id := range map[string]uuid.UUID{"accepted": acceptedID, "cancelled": revokedID} { + var text, html string + var redactedAt *time.Time + if err := pool.QueryRow(ctx, "SELECT text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1", id).Scan(&text, &html, &redactedAt); err != nil || + text != "" || html != "" || redactedAt == nil { + t.Fatalf("%s delivery keeps a body (%d, %d bytes) or no redaction time: %v", name, len(text), len(html), err) + } + got := harness.delivery(ctx, t, id) + if !got.Content().Redacted() || got.Content().Text() != "" || got.Content().Subject() == "" { + t.Fatalf("%s delivery restores as %v, want redacted content with its subject", name, got.Content()) + } + } + // Neither the token nor its mail is in the table any more. + var leaked int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM deliveries WHERE text_body LIKE $1 OR html_body LIKE $1 OR text_body LIKE $2 OR html_body LIKE $2", + "%"+raw.Reveal()+"%", "%"+revokedRaw.Reveal()+"%").Scan(&leaked); err != nil || leaked != 0 { + t.Fatalf("%d rows still hold a token, %v", leaked, err) + } + // A redacted row cannot get a body back, or lose its mark. + for _, statement := range []string{ + "UPDATE deliveries SET text_body = 'again' WHERE id = $1", + "UPDATE deliveries SET body_redacted_at = NULL WHERE id = $1", + } { + _, err := pool.Exec(ctx, statement, acceptedID) + assertSQLRefusal(t, err, "deliveries_content_immutable") + } + // The account still sees its status. + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, accepted.ID, domain.MailKindVerification) + if err != nil || !found || status.Status != domain.DeliveryStatusAccepted { + t.Fatalf("LatestForUser() = %+v, %t, %v; want accepted", status, found, err) + } + }) + + t.Run("a deleted account leaves nothing to send", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) + harness.exec(ctx, t, "DELETE FROM users WHERE id = $1", user.ID) + if _, err := harness.deliveries.Get(ctx, deliveryID); !errors.Is(err, outbound.ErrDeliveryNotFound) { + t.Fatalf("Get() after the account was deleted error = %v, want ErrDeliveryNotFound", err) + } + sender := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { + t.Fatalf("pass = %+v with %d provider calls, want idle and none", result, len(fixture.Requests()[calls:])) + } + }) + + t.Run("provider answers become delivery states and due times without an internal retry", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + + // A refusal for now: the delivery is pending again, due later, and + // nothing repeats the request before that. + fixture.Script(resendfixture.Reply{Status: http.StatusServiceUnavailable, Name: "service_unavailable"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { + t.Fatalf("pass after a 503 = %+v, want retry", result) + } + pending := harness.delivery(ctx, t, deliveryID) + wantDue := mailSenderStart.Add(time.Minute) + if pending.Status() != domain.DeliveryStatusPending || !pending.NextAttemptAt().Equal(wantDue) || pending.AttemptCount() != 1 { + t.Fatalf("delivery is %s due %s after %d attempts, want pending due %s after one", pending.Status(), pending.NextAttemptAt(), pending.AttemptCount(), wantDue) + } + harness.assertQuotaUsage(ctx, t, 0) // the refused request did not count + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 1 { + t.Fatalf("pass before the due time = %+v with %d provider calls, want idle and 1", again, len(fixture.Requests()[calls:])) + } + harness.clock.Set(wantDue) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass at the due time = %+v, want accepted", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey { + t.Fatalf("provider calls = %+v, want two calls under one key", requests) + } + attempts := harness.attempts(ctx, t, deliveryID) + if len(attempts) != 2 || attempts[0].Rejection != domain.DeliveryRejectionTemporary || attempts[1].Outcome != domain.DeliveryOutcomeAccepted { + t.Fatalf("attempts = %+v, want a temporary refusal and then acceptance", attempts) + } + + // An uncertain answer remains unknown, but gets a bounded retry while + // the provider still holds the idempotency key. + other := harness.createUser(ctx, t, false) + _, _, uncertainID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) + fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass after a 500 = %+v, want unknown", result) + } + if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().Equal(harness.clock.Now().Add(time.Minute)) { + t.Fatalf("delivery is %s with next attempt %s, want unknown with bounded retry", got.Status(), got.NextAttemptAt()) + } + harness.clock.Advance(24 * time.Hour) + // PostgreSQL owns the cutoff clock; move its start time to exercise + // the same DB-clock age calculation without sleeping for a day. + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", uncertainID) + callsBefore := len(fixture.Requests()) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown || len(fixture.Requests()) != callsBefore { + t.Fatalf("pass after the deduplication cutoff = %+v, want unknown without a call", result) + } + if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() { + t.Fatalf("delivery after cutoff is %s due %s, want terminal unknown without automatic retry", got.Status(), got.NextAttemptAt()) + } + + // A permanent refusal ends the delivery. + harness.clock.Set(mailSenderStart) + third := harness.createUser(ctx, t, false) + _, _, refusedID := harness.enqueueVerification(ctx, t, third, mailSenderTokenLifetime) + fixture.Script(resendfixture.Reply{Status: http.StatusForbidden, Name: "validation_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRejected { + t.Fatalf("pass after a 403 = %+v, want rejected", result) + } + if got := harness.delivery(ctx, t, refusedID); got.Status() != domain.DeliveryStatusRejected { + t.Fatalf("delivery is %s, want rejected", got.Status()) + } + }) + + t.Run("an earlier unknown answer remains uncertain after a confirmed 429", func(t *testing.T) { + for _, test := range []struct { + name string + age time.Duration + wantOutcome inbound.MailPassOutcome + wantStatus domain.DeliveryStatus + wantCalls int + }{ + {name: "retry remains allowed before cutoff", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3}, + {name: "cutoff stops without a phantom attempt", age: 24 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2}, + } { + t.Run(test.name, func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + + fixture.Script(resendfixture.Reply{DropAfterAccept: true}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("accepted request with dropped response = %+v, want unknown", result) + } + harness.clock.Advance(time.Minute) + fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "60"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { + t.Fatalf("confirmed 429 = %+v, want retry", result) + } + pending := harness.delivery(ctx, t, deliveryID) + if pending.Status() != domain.DeliveryStatusPending || pending.AttemptCount() != 2 { + t.Fatalf("delivery after 429 is %s after %d attempts, want pending after two", pending.Status(), pending.AttemptCount()) + } + attempts := harness.attempts(ctx, t, deliveryID) + if len(attempts) != 2 || attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Rejection != domain.DeliveryRejectionRateLimited { + t.Fatalf("attempts = %+v, want unknown then confirmed rate limit", attempts) + } + + harness.clock.Set(mailSenderStart.Add(test.age)) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - make_interval(secs => $2::float8) WHERE id = $1", deliveryID, test.age.Seconds()) + result := harness.pass(ctx, t, sender) + stored := harness.delivery(ctx, t, deliveryID) + if result.Outcome != test.wantOutcome || stored.Status() != test.wantStatus || len(fixture.Requests())-calls != test.wantCalls { + t.Fatalf("pass = %+v, delivery %s, provider requests %d; want %s and %d calls", result, stored.Status(), len(fixture.Requests())-calls, test.wantOutcome, test.wantCalls) + } + requests := fixture.Requests()[calls:] + if requests[0].IdempotencyKey != requests[1].IdempotencyKey || + !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || + requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { + t.Fatal("unknown and confirmed-refusal requests did not keep the same pinned key and body") + } + if test.wantStatus == domain.DeliveryStatusUnknown && + (stored.AttemptCount() != 2 || !stored.NextAttemptAt().IsZero() || len(attempts) != 2 || fixture.Messages()-messages != 1) { + t.Fatalf("cutoff state = %s due %s after %d attempts, fixture accepted %d messages; want no new call or attempt", stored.Status(), stored.NextAttemptAt(), stored.AttemptCount(), fixture.Messages()-messages) + } + }) + } + }) + + t.Run("manual retry audits the decision, honors 429 Retry-After, and stops after another unknown", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial 500 pass = %+v, want unknown", result) + } + + operator, err := notification.NewDeliveryRetryOperator( + harness.transactor, harness.deliveries, harness.account, resend.IdempotencyWindow, harness.clock.Now, + ) + if err != nil { + t.Fatalf("NewDeliveryRetryOperator() error = %v", err) + } + if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { + t.Fatalf("RetryUnknown() before cutoff error = %v, want not allowed", err) + } + if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", false); !errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired) { + t.Fatalf("RetryUnknown() without acknowledgement error = %v, want acknowledgement required", err) + } + + // Claim while the original result is still inside the safe window, + // then age the DB-clock timestamp before MarkSendStarted. The last + // storage check must refuse the call even though the claim succeeded. + harness.clock.Advance(time.Minute) + owner := uuid.New() + var claimed outbound.ClaimedDelivery + if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: time.Minute, + }) + return err + }); err != nil || claimed.Delivery.ID() != deliveryID { + t.Fatalf("claim for the cutoff check = %s, %v; want the uncertain delivery", claimed.Delivery.ID(), err) + } + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", deliveryID) + started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour) + if err != nil || started { + t.Fatalf("MarkSendStarted() at the DB-clock cutoff = %t, %v; want no send", started, err) + } + if released, err := harness.deliveries.ReleaseClaim(ctx, deliveryID, owner); err != nil || !released { + t.Fatalf("ReleaseClaim() after cutoff refusal = %t, %v; want released", released, err) + } + + harness.clock.Set(mailSenderStart.Add(23 * time.Hour)) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass at the automatic cutoff = %+v, want automatic retry stopped", result) + } + stopped := harness.delivery(ctx, t, deliveryID) + if stopped.Status() != domain.DeliveryStatusUnknown || !stopped.NextAttemptAt().IsZero() { + t.Fatalf("delivery after automatic cutoff is %s due %s, want unknown without automatic retry", stopped.Status(), stopped.NextAttemptAt()) + } + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return env.Config.DatabaseURL, true + case "EMAIL_PROVIDER": + return "resend", true + case "EMAIL_ACCOUNT": + return mailSenderAccount, true + default: + return "", false + } + } + var cliOutput bytes.Buffer + if err := mailretry.Run(ctx, []string{"inspect", "--delivery", deliveryID.String()}, lookup, &cliOutput); err != nil { + t.Fatalf("mail-retry inspect error = %v", err) + } + if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) || + strings.Contains(cliOutput.String(), user.Email.Address()) { + t.Fatalf("mail-retry inspect output = %q; want duplicate warning without recipient data", cliOutput.String()) + } + cliOutput.Reset() + if err := mailretry.Run(ctx, []string{ + "retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk", + }, lookup, &cliOutput); err != nil { + t.Fatalf("mail-retry retry error = %v", err) + } + if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) || + !strings.Contains(cliOutput.String(), "retry scheduled; audit decision recorded") { + t.Fatalf("mail-retry retry output = %q; want warning and audited scheduling", cliOutput.String()) + } + if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { + t.Fatalf("duplicate RetryUnknown() error = %v, want not allowed", err) + } + var decisions int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { + t.Fatalf("audited decisions = %d, %v; want exactly one", decisions, err) + } + scheduled := harness.delivery(ctx, t, deliveryID) + if scheduled.Status() != domain.DeliveryStatusUnknown || scheduled.NextAttemptAt().IsZero() { + t.Fatalf("authorized delivery is %s due %s; want scheduled unknown work", scheduled.Status(), scheduled.NextAttemptAt()) + } + dueAfterAuthorization := scheduled.NextAttemptAt().Add(time.Second) + var databaseNow time.Time + if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&databaseNow); err != nil { + t.Fatalf("read database clock after manual retry: %v", err) + } + databaseDueAt := databaseNow.Add(time.Second) + if databaseDueAt.After(dueAfterAuthorization) { + dueAfterAuthorization = databaseDueAt + } + // The CLI uses the real clock; the worker uses the test clock. Align the + // worker with the persisted due time before scripting the next provider + // response, or this subtest leaves that response queued for the next one. + harness.clock.Set(dueAfterAuthorization) + + fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "300"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { + t.Fatalf("manual 429 pass = %+v, want scheduled retry", result) + } + rateLimited := harness.delivery(ctx, t, deliveryID) + wantRetryAt := harness.clock.Now().Add(5 * time.Minute) + if rateLimited.Status() != domain.DeliveryStatusPending || !rateLimited.NextAttemptAt().Equal(wantRetryAt) { + t.Fatalf("429 state is %s due %s, want pending due at Retry-After %s", rateLimited.Status(), rateLimited.NextAttemptAt(), wantRetryAt) + } + + harness.clock.Set(wantRetryAt) + fixture.Script(resendfixture.Reply{DropAfterAccept: true}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("manual send with accepted connection drop = %+v, want unknown", result) + } + unknown := harness.delivery(ctx, t, deliveryID) + if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() || unknown.AttemptCount() != 3 { + t.Fatalf("manual drop state is %s due %s after %d attempts, want terminal unknown after 3", unknown.Status(), unknown.NextAttemptAt(), unknown.AttemptCount()) + } + callsAfterUnknown := len(fixture.Requests()) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsAfterUnknown { + t.Fatalf("pass after manual unknown = %+v with %d requests, want idle", result, len(fixture.Requests())-calls) + } + if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { + t.Fatalf("audited decisions without another operator command = %d, %v; want still one", decisions, err) + } + requests := fixture.Requests()[calls:] + if len(requests) != 3 || fixture.Messages()-messages != 1 { + t.Fatalf("provider saw %d requests and accepted %d messages; want 3 requests and one accepted message", len(requests), fixture.Messages()-messages) + } + for _, request := range requests[1:] { + if request.IdempotencyKey != requests[0].IdempotencyKey || !slices.Equal(request.To, requests[0].To) || + request.Subject != requests[0].Subject || request.Text != requests[0].Text || request.HTML != requests[0].HTML { + t.Fatal("the manual retries changed the pinned key or stored body") + } + } + if requests[2].Replayed { + t.Fatal("the final request was unexpectedly replayed before the fixture accepted its first manual request") + } + }) + + t.Run("an expired manual send-start is recorded before another authorized send", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial 500 pass = %+v, want unknown", result) + } + harness.clock.Set(mailSenderStart.Add(23 * time.Hour)) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass at automatic cutoff = %+v, want terminal unknown", result) + } + + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return env.Config.DatabaseURL, true + case "EMAIL_PROVIDER": + return "resend", true + case "EMAIL_ACCOUNT": + return mailSenderAccount, true + default: + return "", false + } + } + retryCommand := func() { + t.Helper() + var output bytes.Buffer + if err := mailretry.Run(ctx, []string{ + "retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk", + }, lookup, &output); err != nil { + t.Fatalf("mail-retry command error = %v", err) + } + if !strings.Contains(output.String(), notification.DuplicateRiskWarning) || + !strings.Contains(output.String(), "retry scheduled; audit decision recorded") || + strings.Contains(output.String(), user.Email.Address()) { + t.Fatalf("mail-retry output = %q; want warning and safe scheduling result", output.String()) + } + } + dbClock := func() time.Time { + t.Helper() + var now time.Time + if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil { + t.Fatalf("read database clock: %v", err) + } + return now + } + retryCommand() + authorized := harness.delivery(ctx, t, deliveryID) + if authorized.Status() != domain.DeliveryStatusUnknown || authorized.NextAttemptAt().IsZero() { + t.Fatalf("authorized delivery state = %s due %s; want scheduled unknown work", authorized.Status(), authorized.NextAttemptAt()) + } + // Authorization keeps the later of the app and database timestamps. + // The cutoff pass above uses the fake app clock, so advancing only to + // database-now can still leave the delivery not due yet. + dueAfterAuthorization := authorized.NextAttemptAt().Add(time.Second) + if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterAuthorization) { + dueAfterAuthorization = databaseNow + } + harness.clock.Set(dueAfterAuthorization) + owner := uuid.New() + var claimed outbound.ClaimedDelivery + if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, + }) + return err + }); err != nil || claimed.Delivery.ID() != deliveryID || !claimed.ManualRetryPending { + t.Fatalf("manual send claim = %s, pending %t, error %v; want the authorized delivery", claimed.Delivery.ID(), claimed.ManualRetryPending, err) + } + started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour) + if err != nil || !started { + t.Fatalf("MarkSendStarted() for operator decision = %t, %v; want started", started, err) + } + harness.exec(ctx, t, "UPDATE deliveries SET claimed_until = clock_timestamp() - interval '1 second' WHERE id = $1", deliveryID) + + callsBeforeRecovery := len(fixture.Requests()) + retryCommand() + if len(fixture.Requests()) != callsBeforeRecovery { + t.Fatal("operator recovery called the provider instead of only recording the lost result and scheduling work") + } + recovered := harness.delivery(ctx, t, deliveryID) + attempts := harness.attempts(ctx, t, deliveryID) + if recovered.AttemptCount() != 2 || recovered.Status() != domain.DeliveryStatusUnknown || recovered.NextAttemptAt().IsZero() || len(attempts) != 2 || + attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Outcome != domain.DeliveryOutcomeUnknown || + attempts[1].At.Before(attempts[0].At) { + t.Fatalf("recovered delivery = %s due %s after %d attempts, attempts %+v; want the lost manual call appended as unknown and another decision scheduled", recovered.Status(), recovered.NextAttemptAt(), recovered.AttemptCount(), attempts) + } + rows, err := pool.Query(ctx, ` + SELECT attempt_count, duplicate_risk_acknowledged, previous_lease_expired + FROM delivery_retry_decisions + WHERE delivery_id = $1 + ORDER BY decision_id`, deliveryID) + if err != nil { + t.Fatalf("read retry decisions: %v", err) + } + defer rows.Close() + var decisions []struct { + attemptCount int32 + duplicateRiskAcknowledged bool + previousLeaseExpired bool + } + for rows.Next() { + var decision struct { + attemptCount int32 + duplicateRiskAcknowledged bool + previousLeaseExpired bool + } + if err := rows.Scan(&decision.attemptCount, &decision.duplicateRiskAcknowledged, &decision.previousLeaseExpired); err != nil { + t.Fatalf("scan retry decision: %v", err) + } + decisions = append(decisions, decision) + } + if err := rows.Err(); err != nil { + t.Fatalf("read retry decisions: %v", err) + } + if len(decisions) != 2 || decisions[0].attemptCount != 1 || decisions[1].attemptCount != 2 || + !decisions[0].duplicateRiskAcknowledged || !decisions[1].duplicateRiskAcknowledged || + decisions[0].previousLeaseExpired || !decisions[1].previousLeaseExpired { + t.Fatalf("retry decisions = %+v; want each decision tied to its unknown attempt and second decision marked as lease recovery", decisions) + } + + dueAfterRecovery := recovered.NextAttemptAt().Add(time.Second) + if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterRecovery) { + dueAfterRecovery = databaseNow + } + harness.clock.Set(dueAfterRecovery) + fixture.Script(resendfixture.Reply{}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after recovered operator decision = %+v, want accepted", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || + !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || + requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { + t.Fatalf("provider requests after recovery = %+v; want initial and manually authorized request with the pinned key and body", requests) + } + }) + + t.Run("a used-up quota parks the delivery in a user-visible waiting status", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + // The local gate: one message per day. + sender := harness.newSender(t, harness.transactor, 1, 5) + first := harness.createUser(ctx, t, false) + harness.enqueueVerification(ctx, t, first, mailSenderTokenLifetime) + second := harness.createUser(ctx, t, false) + _, _, waitingID := harness.enqueueVerification(ctx, t, second, mailSenderTokenLifetime) + + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("first pass = %+v, want accepted", result) + } + result := harness.pass(ctx, t, sender) + if result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != waitingID { + t.Fatalf("second pass = %+v, want waiting_quota for the second delivery", result) + } + midnight := time.Date(mailSenderStart.Year(), mailSenderStart.Month(), mailSenderStart.Day()+1, 0, 0, 0, 0, time.UTC) + status, found, err := notification.NewDeliveryStatusReader(harness.deliveries).LatestForUser(ctx, second.ID, domain.MailKindVerification) + if err != nil || !found || !status.WaitingForQuota() || !status.WaitingUntil.Equal(midnight) { + t.Fatalf("LatestForUser() = %+v, %t, %v; want waiting until %s", status, found, err, midnight) + } + if len(fixture.Requests()[calls:]) != 1 { + t.Fatal("the provider was called for a delivery that the local quota deferred") + } + // Not due yet one second before the reset; sent right after it. + harness.clock.Set(midnight.Add(-time.Second)) + if again := harness.pass(ctx, t, sender); again.Outcome != inbound.MailPassIdle { + t.Fatalf("pass before the reset = %+v, want idle", again) + } + harness.clock.Set(midnight) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != waitingID { + t.Fatalf("pass at the reset = %+v, want the waiting delivery accepted", result) + } + + // The provider's own refusal for its quota also waits for the reset. + third := harness.createUser(ctx, t, false) + _, _, refusedID := harness.enqueueVerification(ctx, t, third, mailSenderTokenLifetime) + fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "daily_quota_exceeded"}) + wide := harness.newSender(t, harness.transactor, 100, 3000) + nextMidnight := midnight.AddDate(0, 0, 1) + if result := harness.pass(ctx, t, wide); result.Outcome != inbound.MailPassWaitingQuota || result.DeliveryID != refusedID { + t.Fatalf("pass after the provider quota answer = %+v, want waiting_quota", result) + } + if got := harness.delivery(ctx, t, refusedID); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(nextMidnight) { + t.Fatalf("delivery is %s until %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), nextMidnight) + } + }) + + t.Run("product notifications are not sent by this worker", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, true) + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), RecipientUserID: user.ID, Recipient: user.Email, + Content: content, ProviderAccount: harness.account, CreatedAt: harness.clock.Now(), + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := harness.deliveries.Create(ctx, delivery); err != nil || !created { + t.Fatalf("Create() = %t, %v; want the notification stored", created, err) + } + sender := harness.newSender(t, harness.transactor, 100, 3000) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()[calls:]) != 0 { + t.Fatalf("pass = %+v with %d provider calls, want idle and none: product notification sending is not implemented", result, len(fixture.Requests()[calls:])) + } + if got := harness.delivery(ctx, t, delivery.ID()); got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 { + t.Fatalf("the notification is %s with %d attempts, want it untouched", got.Status(), got.AttemptCount()) + } + }) + + t.Run("EMAIL_PROVIDER=disabled sends nothing, keeps the mail, and does not spin", func(t *testing.T) { + reset(t) + disabledAccount, err := domain.NewMailProviderAccount("disabled", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + stored := *harness + stored.account = disabledAccount + stored.mailer = notification.NewServiceMailer(notification.NewTemplateRenderer(templates), disabledAccount, clock.Now) + stored.transport = disabled.NewSender() + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := stored.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + if got := harness.delivery(ctx, t, deliveryID); got.ProviderAccount() != disabledAccount { + t.Fatal("the mail stored while no transport runs is not pinned to disabled") + } + + sender := stored.newSender(t, harness.transactor, 100, 3000) + if result := stored.pass(ctx, t, sender); result.Outcome != inbound.MailPassChannelUnavailable { + t.Fatalf("pass = %+v, want channel_unavailable", result) + } + got := harness.delivery(ctx, t, deliveryID) + if got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 0 || got.Version() != 1 { + t.Fatalf("delivery is %s with %d attempts at version %d, want it untouched", got.Status(), got.AttemptCount(), got.Version()) + } + harness.assertClaimReleased(ctx, t, deliveryID) + harness.assertQuotaUsageFor(ctx, t, disabledAccount, 0) + + // The worker loop backs off instead of claiming again at once. + metrics := prometheus.New() + counted := &countingPass{inner: sender} + worker, err := mailsender.New(counted, metrics, slog.New(slog.NewJSONHandler(harness.logs, nil)), mailsender.Settings{ + PollInterval: 50 * time.Millisecond, + Backoff: retry.Backoff{Initial: 400 * time.Millisecond, Max: time.Second}, + ShutdownGrace: time.Second, + }) + if err != nil { + t.Fatalf("mailsender.New() error = %v", err) + } + runCtx, stop := context.WithCancel(ctx) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + worker.Run(runCtx) + }() + waitFor(ctx, t, "the sender gauge to show the loop", func() bool { return strings.Contains(scrapeMetrics(metrics), "lincodex_mail_sender_running 1\n") }) + time.Sleep(900 * time.Millisecond) + stop() + <-stopped + if passes := counted.passes.Load(); passes > 4 { + t.Fatalf("the loop made %d passes in under a second, want it to back off", passes) + } + if !strings.Contains(scrapeMetrics(metrics), "lincodex_mail_sender_running 0\n") { + t.Fatal("the sender gauge did not return to 0 after the loop stopped") + } + if len(fixture.Requests()[calls:]) != 0 { + t.Fatal("the disabled transport reached the provider") + } + harness.assertQuotaUsageFor(ctx, t, disabledAccount, 0) + + // The stand now enables a transport: the mail is moved to its + // account, before any attempt, and sent. + live := harness.newSenderWithRebind(t, harness.transactor, 100, 3000, "disabled") + if result := harness.pass(ctx, t, live); result.Outcome != inbound.MailPassAccepted || result.DeliveryID != deliveryID { + t.Fatalf("pass with a transport = %+v, want accepted", result) + } + rebound := harness.delivery(ctx, t, deliveryID) + if rebound.ProviderAccount() != harness.account || rebound.Status() != domain.DeliveryStatusAccepted { + t.Fatalf("delivery is %s on %s, want accepted on the configured account", rebound.Status(), rebound.ProviderAccount().Provider()) + } + }) + + t.Run("the schema keeps cancellation, leases, and the token binding consistent", func(t *testing.T) { + reset(t) + user := harness.createUser(ctx, t, false) + _, token, deliveryID := harness.enqueueVerification(ctx, t, user, time.Hour) + other := harness.createUser(ctx, t, false) + _, otherToken, _ := harness.enqueueVerification(ctx, t, other, time.Hour) + + checks := []struct { + name string + statement string + args []any + constraint string + trigger bool + }{ + { + name: "a cancelled delivery has a reason", + statement: "UPDATE deliveries SET status = 'cancelled', next_attempt_at = NULL WHERE id = $1", + args: []any{deliveryID}, + constraint: "deliveries_cancel_reason_matches_status", + }, + { + name: "a reason belongs only to a cancelled delivery", + statement: "UPDATE deliveries SET cancel_reason = 'token_revoked' WHERE id = $1", + args: []any{deliveryID}, + constraint: "deliveries_cancel_reason_matches_status", + }, + { + name: "a lease has an owner and a deadline together", + statement: "UPDATE deliveries SET claim_owner = $2 WHERE id = $1", + args: []any{deliveryID, uuid.New()}, + constraint: "deliveries_claim_complete", + }, + { + name: "a terminal delivery holds no lease", + statement: "UPDATE deliveries SET status = 'rejected', next_attempt_at = NULL, claim_owner = $2, claimed_until = now() WHERE id = $1", + args: []any{deliveryID, uuid.New()}, + constraint: "deliveries_claim_complete", + }, + { + name: "the kind of a stored delivery never changes", + statement: "UPDATE deliveries SET kind = 'notification', template_version = 'notification.v1' WHERE id = $1", + args: []any{deliveryID}, + constraint: "deliveries_content_immutable", + trigger: true, + }, + { + name: "a notification carries no token", + statement: `INSERT INTO deliveries ( + id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, + content_sha256, provider, provider_account, idempotency_key, status, attempt_count, + next_attempt_at, version, created_at, updated_at, email_token_id + ) + SELECT gen_random_uuid(), recipient_user_id, recipient_email, 'notification', 'notification.v1', subject, + text_body, html_body, content_sha256, provider, provider_account, + 'delivery/' || gen_random_uuid()::text, status, attempt_count, next_attempt_at, version, + created_at, updated_at, email_token_id + FROM deliveries WHERE id = $1`, + args: []any{deliveryID}, + constraint: "deliveries_token_only_for_token_kinds", + }, + { + name: "the token binding never changes", + statement: "UPDATE deliveries SET email_token_id = $2 WHERE id = $1", + args: []any{deliveryID, otherToken.ID}, + constraint: "deliveries_content_immutable", + trigger: true, + }, + } + for _, check := range checks { + _, err := pool.Exec(ctx, check.statement, check.args...) + if check.trigger { + assertSQLRefusal(t, err, check.constraint) + continue + } + var pgError interface{ SQLState() string } + if !errors.As(err, &pgError) || pgError.SQLState() != checkViolationCode { + t.Fatalf("%s: error = %v, want a check violation", check.name, err) + } + if !strings.Contains(err.Error(), check.constraint) { + t.Fatalf("%s: error = %v, want constraint %s", check.name, err, check.constraint) + } + } + // A token that a delivery references cannot disappear on its own. + if _, err := pool.Exec(ctx, "DELETE FROM email_tokens WHERE id = $1", token.ID); err == nil { + t.Fatal("a token that a delivery is bound to was deleted") + } + // Deleting the account removes both. + harness.exec(ctx, t, "DELETE FROM users WHERE id = $1", user.ID) + assertRowCount(ctx, t, pool, pgx.Identifier{"email_tokens"}, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 1) + }) +} + +func (harness *senderHarness) createUser(ctx context.Context, t *testing.T, verified bool) domain.User { + t.Helper() + harness.users++ + hash, err := domain.NewPasswordHash(identityTestPasswordHash) + if err != nil { + t.Fatalf("NewPasswordHash() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: mustEmail(t, fmt.Sprintf("Synthetic.User%d@Example.com", harness.users)), + PasswordHash: hash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: harness.clock.Now(), + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.identity.Users().Create(ctx, user); err != nil { + t.Fatalf("create the account: %v", err) + } + if !verified { + return user + } + confirmed, err := harness.identity.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, harness.clock.Now()) + if err != nil { + t.Fatalf("verify the account: %v", err) + } + return confirmed +} + +// enqueueVerification issues a token and stores its mail in one transaction, +// as the registration flow will. +func (harness *senderHarness) enqueueVerification(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) { + t.Helper() + return harness.enqueueToken(ctx, t, user, domain.EmailTokenPurposeEmailVerification, lifetime, harness.mailer.EnqueueVerification) +} + +// enqueuePasswordReset issues a password reset token and stores its mail in +// one transaction, as the reset flow will. +func (harness *senderHarness) enqueuePasswordReset(ctx context.Context, t *testing.T, user domain.User, lifetime time.Duration) (domain.SecretToken, domain.EmailToken, uuid.UUID) { + t.Helper() + return harness.enqueueToken(ctx, t, user, domain.EmailTokenPurposePasswordReset, lifetime, harness.mailer.EnqueuePasswordReset) +} + +// enqueueToken issues a token of purpose and stores the mail that enqueue +// builds for it, in the same transaction as the token. +func (harness *senderHarness) enqueueToken( + ctx context.Context, + t *testing.T, + user domain.User, + purpose domain.EmailTokenPurpose, + lifetime time.Duration, + enqueue func(context.Context, outbound.UnitOfWork, notification.TokenMailRequest) (uuid.UUID, error), +) (domain.SecretToken, domain.EmailToken, uuid.UUID) { + t.Helper() + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatalf("NewSecretToken() error = %v", err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: user.ID, Purpose: purpose, TokenHash: raw.Hash(), + RegistrationVersion: user.RegistrationVersion, IssuedAt: harness.clock.Now(), Lifetime: lifetime, + }) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + code, err := domain.NewVerificationCode() + if err != nil { + t.Fatalf("NewVerificationCode() error = %v", err) + } + var deliveryID uuid.UUID + err = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.EmailTokens().Insert(ctx, token); err != nil { + return err + } + deliveryID, err = enqueue(ctx, unit, notification.TokenMailRequest{ + Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour), + Code: code, CodeLifetime: domain.VerificationCodeLifetime, + }) + return err + }) + if err != nil { + t.Fatalf("enqueue the %s mail: %v", purpose, err) + } + return raw, token, deliveryID +} + +func (harness *senderHarness) newSender(t *testing.T, transactor outbound.Transactor, daily, monthly int64) *notification.ServiceMailSender { + t.Helper() + return harness.newSenderWithRebind(t, transactor, daily, monthly, "") +} + +func (harness *senderHarness) newSenderWithRebind(t *testing.T, transactor outbound.Transactor, daily, monthly int64, rebindProvider string) *notification.ServiceMailSender { + t.Helper() + limits, err := domain.NewMailQuotaLimits(daily, monthly) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + logger := slog.New(slog.NewJSONHandler(harness.logs, nil)) + // The idempotency window is the one of Resend; the disabled transport + // has none, which only matters after a lost attempt. + gate := notification.NewQuotaGate(harness.account, limits, resend.IdempotencyWindow, harness.clock.Now, logger) + sender, err := notification.NewServiceMailSender(transactor, harness.transport, gate, notification.ServiceMailSenderSettings{ + Account: harness.account, + RebindProvider: rebindProvider, + Lease: mailSenderLease, + StoreTimeout: 30 * time.Second, + SettleBudget: mailSenderSettleBudget, + ShutdownSettleBudget: time.Second, + MaxFailures: 3, + Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, + }, harness.clock.Now, logger) + if err != nil { + t.Fatalf("NewServiceMailSender() error = %v", err) + } + return sender +} + +func (harness *senderHarness) pass(ctx context.Context, t *testing.T, sender *notification.ServiceMailSender) inbound.MailPassResult { + t.Helper() + result, err := sender.ProcessNext(ctx, ctx) + if err != nil { + t.Fatalf("ProcessNext() error = %v", err) + } + return result +} + +func (harness *senderHarness) delivery(ctx context.Context, t *testing.T, id uuid.UUID) domain.Delivery { + t.Helper() + delivery, err := harness.deliveries.Get(ctx, id) + if err != nil { + t.Fatalf("Get(%s) error = %v", id, err) + } + return delivery +} + +func (harness *senderHarness) attempts(ctx context.Context, t *testing.T, id uuid.UUID) []domain.DeliveryAttempt { + t.Helper() + attempts, err := harness.deliveries.ListAttempts(ctx, id) + if err != nil { + t.Fatalf("ListAttempts(%s) error = %v", id, err) + } + return attempts +} + +func (harness *senderHarness) exec(ctx context.Context, t *testing.T, statement string, args ...any) { + t.Helper() + if _, err := harness.pool.Exec(ctx, statement, args...); err != nil { + t.Fatalf("exec %q: %v", statement, err) + } +} + +func (harness *senderHarness) claimOf(ctx context.Context, t *testing.T, id uuid.UUID) (*uuid.UUID, *time.Time) { + t.Helper() + var owner *uuid.UUID + var until *time.Time + if err := harness.pool.QueryRow(ctx, "SELECT claim_owner, claimed_until FROM deliveries WHERE id = $1", id).Scan(&owner, &until); err != nil { + t.Fatalf("read the lease of %s: %v", id, err) + } + return owner, until +} + +func (harness *senderHarness) assertClaimReleased(ctx context.Context, t *testing.T, id uuid.UUID) { + t.Helper() + if owner, until := harness.claimOf(ctx, t, id); owner != nil || until != nil { + t.Fatalf("delivery %s still holds a lease", id) + } +} + +func (harness *senderHarness) assertQuotaUsage(ctx context.Context, t *testing.T, want int64) { + t.Helper() + harness.assertQuotaUsageFor(ctx, t, harness.account, want) +} + +// assertQuotaUsageFor checks the recipients counted today and this month +// under account, by the fake clock. +func (harness *senderHarness) assertQuotaUsageFor(ctx context.Context, t *testing.T, account domain.MailProviderAccount, want int64) { + t.Helper() + usage, err := postgresadapter.NewMailQuotaStore(harness.pool).MailQuotas().Usage(ctx, account, domain.MailQuotaWindowsAt(harness.clock.Now())) + if err != nil { + t.Fatalf("Usage() error = %v", err) + } + if usage.DayUsed != want || usage.MonthUsed != want { + t.Fatalf("quota usage under %s = %d today and %d this month, want %d", account.Provider(), usage.DayUsed, usage.MonthUsed, want) + } +} + +func (harness *senderHarness) assertLogsHoldNoSecrets(t *testing.T, forbidden ...string) { + t.Helper() + logs := harness.logs.String() + for _, marker := range forbidden { + if marker != "" && strings.Contains(logs, marker) { + t.Fatalf("a secret or an address reached the logs:\n%s", logs) + } + } +} + +func scrapeMetrics(metrics *prometheus.Metrics) string { + recorder := httptest.NewRecorder() + metrics.Handler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + return recorder.Body.String() +} diff --git a/backend/integration_test/manual_assessment_request_test.go b/backend/integration_test/manual_assessment_request_test.go new file mode 100644 index 0000000..4495e95 --- /dev/null +++ b/backend/integration_test/manual_assessment_request_test.go @@ -0,0 +1,302 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/consent" +) + +const manualAssessmentHTTPTimeout = 8 * time.Minute + +const manualAssessmentBody = `{"type":"manual_assessment","description":"I do not consent to automated categorization.","assessment_target":{"specialization":"backend","grade":"junior"}}` + +// TestManualAssessmentRequestAfterC3Refusal drives the real router through a +// C3 refusal and the manual assessment request that replaces the automated +// path. The request must neither depend on C3 nor change it, and it must leave +// existing attempts and results untouched. +func TestManualAssessmentRequestAfterC3Refusal(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), manualAssessmentHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv) + productPolicy, _, _, _ := seedSupportManualRubric(ctx, t, harness) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + reader := consent.NewQueryService(postgresadapter.NewConsentStore(harness.pool), time.Now) + + t.Run("refusal before the first test", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-before-test@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.10:1234") + grantManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.11:1234") + revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.12:1234") + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + consentBefore := consentLedgerSnapshot(ctx, t, harness, candidate.ID) + + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-before-test-1", "198.51.100.13:1234") + var request supportCaseHTTPResponse + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &request) != nil { + t.Fatalf("manual request after C3 revocation = %d %s, want 201", created.Code, created.Body.String()) + } + if request.Type != "manual_assessment" || request.Status != "waiting_expert" || request.Decision != nil || + request.RubricVersion == nil || *request.RubricVersion != productPolicy.Version() { + t.Fatalf("created request = %+v, want waiting_expert without a decision, pinned to rubric version %d", request, productPolicy.Version()) + } + if len(request.History) != 2 || request.History[1].Actor != "system" || request.History[1].Status != "waiting_expert" { + t.Fatalf("request history = %+v, want creation and a system move to the expert queue", request.History) + } + if request.AssessmentTarget == nil || request.AssessmentTarget.Specialization != "backend" || request.AssessmentTarget.Grade != "junior" || + request.Description != "I do not consent to automated categorization." { + t.Fatalf("request target/reason = %+v / %q, want backend junior and the stated reason", request.AssessmentTarget, request.Description) + } + + read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+request.ID, "", cookie.Value, "", "", "198.51.100.14:1234") + if read.Code != http.StatusOK || read.Body.String() != created.Body.String() { + t.Fatalf("manual request GET = %d %s, want the created case %s", read.Code, read.Body.String(), created.Body.String()) + } + + // The request is not a consent action and not an assessment action. + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore { + t.Fatalf("manual request changed the consent ledger or its events:\nbefore %s\nafter %s", consentBefore, after) + } + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != "[]|[]" { + t.Fatalf("manual request created assessment rows %s, want no attempt and no result", got) + } + + // A page reload loses the form's idempotency key: a new key must not + // create a second case, and the same key still replays the first. + reload := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-before-test-2", "198.51.100.15:1234") + requireSessionProblem(t, reload, http.StatusConflict, "state_conflict") + replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-before-test-1", "198.51.100.16:1234") + if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() { + t.Fatalf("same-key replay = %d %s, want the original case", replay.Code, replay.Body.String()) + } + assertSupportCaseCount(t, ctx, harness, candidate.ID, 1) + if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore { + t.Fatalf("repeated manual requests changed the consent ledger or its events") + } + }) + + t.Run("unavailable rubric is stored as unavailable", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-no-rubric@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.20:1234") + body := `{"type":"manual_assessment","description":"No automated bank exists for this target.","assessment_target":{"specialization":"backend","grade":"senior"}}` + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie.Value, csrf, "manual-no-rubric-1", "198.51.100.21:1234") + var request supportCaseHTTPResponse + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &request) != nil || + request.Status != "waiting_expert" || request.RubricVersion != nil || request.Decision != nil { + t.Fatalf("manual request without a published rubric = %d %s, want waiting_expert with a null rubric version", created.Code, created.Body.String()) + } + var storedVersion *int32 + var storedOpening *uuid.UUID + if err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id FROM support_cases WHERE id = $1::uuid`, request.ID). + Scan(&storedVersion, &storedOpening); err != nil || storedVersion != nil || storedOpening != nil { + t.Fatalf("stored rubric pin = %v/%v, %v; want none", storedVersion, storedOpening, err) + } + }) + + t.Run("failed first test and missing attempt reference", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-after-failure@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.30:1234") + attemptID := completeManualAssessmentFixtureAttempt(ctx, t, harness, candidate.ID, cookie, csrf, "198.51.100.3", false) + revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.39:1234") + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + // The snapshot is taken after the revocation on purpose: the fixture attempt + // needs a granted C3, so the ledger legitimately changes until then. Only + // changes made by the manual request itself are being checked. + consentBefore := consentLedgerSnapshot(ctx, t, harness, candidate.ID) + assessmentBefore := userAssessmentSnapshot(ctx, t, harness, candidate.ID) + if assessmentBefore == "[]|[]" { + t.Fatal("fixture did not store a failed attempt and its result") + } + + // The refusal and the failed first test do not block the request. The + // failed attempt is accepted as the optional reference; it is not changed. + withReferenceBody := fmt.Sprintf(`{"type":"manual_assessment","description":"Please assess this specialization.","assessment_target":{"specialization":"backend","grade":"junior"},"object":{"type":"assessment_attempt","id":%q}}`, attemptID) + withReference := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", withReferenceBody, + cookie.Value, csrf, "manual-failure-1", "198.51.100.40:1234") + var referenced supportCaseHTTPResponse + if withReference.Code != http.StatusCreated || json.Unmarshal(withReference.Body.Bytes(), &referenced) != nil || + referenced.Status != "waiting_expert" || referenced.Decision != nil { + t.Fatalf("manual request referencing the failed attempt = %d %s, want waiting_expert without a decision", withReference.Code, withReference.Body.String()) + } + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore { + t.Fatalf("manual request changed attempts or results:\nbefore %s\nafter %s", assessmentBefore, got) + } + if after := consentLedgerSnapshot(ctx, t, harness, candidate.ID); after != consentBefore { + t.Fatal("manual request changed the consent ledger or its events") + } + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + + // A reload creates a new key: still one open case, attempts unchanged. + reload := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", withReferenceBody, + cookie.Value, csrf, "manual-failure-2", "198.51.100.41:1234") + requireSessionProblem(t, reload, http.StatusConflict, "state_conflict") + assertSupportCaseCount(t, ctx, harness, candidate.ID, 1) + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore { + t.Fatalf("repeated manual request changed attempts or results:\nbefore %s\nafter %s", assessmentBefore, got) + } + }) + + t.Run("confirmed result is kept", func(t *testing.T) { + candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "manual-after-confirmation@example.test", passwordHash, true) + cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "198.51.100.50:1234") + completeManualAssessmentFixtureAttempt(ctx, t, harness, candidate.ID, cookie, csrf, "198.51.100.5", true) + revokeManualAssessmentC3(t, harness, cookie, csrf, "198.51.100.59:1234") + assessmentBefore := userAssessmentSnapshot(ctx, t, harness, candidate.ID) + + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualAssessmentBody, + cookie.Value, csrf, "manual-confirmed-1", "198.51.100.60:1234") + if created.Code != http.StatusCreated { + t.Fatalf("manual request after a confirmed result = %d %s, want 201", created.Code, created.Body.String()) + } + if got := userAssessmentSnapshot(ctx, t, harness, candidate.ID); got != assessmentBefore { + t.Fatalf("manual request changed the confirmed result or attempts:\nbefore %s\nafter %s", assessmentBefore, got) + } + requireManualAssessmentC3Inactive(ctx, t, reader, candidate.ID) + }) +} + +func grantManualAssessmentC3(t *testing.T, harness *supportCaseHTTPHarness, cookie *http.Cookie, csrf, remoteAddr string) { + t.Helper() + text := harness.request(t, http.MethodGet, "/api/v1/me/consent-texts/c3", "", "", cookie.Value, "", remoteAddr) + var current struct { + TextVersion string `json:"text_version"` + } + if text.Code != http.StatusOK || json.Unmarshal(text.Body.Bytes(), ¤t) != nil || current.TextVersion == "" { + t.Fatalf("read current C3 text = %d %s", text.Code, text.Body.String()) + } + if grant := consentGrantHTTP(t, harness.sessionHTTPHarness, cookie, csrf, "c3", current.TextVersion, sessionHTTPTestOrigin); grant.Code != http.StatusOK { + t.Fatalf("grant C3 = %d %s", grant.Code, grant.Body.String()) + } +} + +func revokeManualAssessmentC3(t *testing.T, harness *supportCaseHTTPHarness, cookie *http.Cookie, csrf, remoteAddr string) { + t.Helper() + revoked := harness.request(t, http.MethodDelete, "/api/v1/me/consents/c3", "", sessionHTTPTestOrigin, cookie.Value, csrf, remoteAddr) + if revoked.Code != http.StatusNoContent { + t.Fatalf("revoke C3 = %d %s, want 204", revoked.Code, revoked.Body.String()) + } +} + +func requireManualAssessmentC3Inactive(ctx context.Context, t *testing.T, reader *consent.QueryService, subject uuid.UUID) { + t.Helper() + active, err := reader.HasCurrentConsent(ctx, subject, domain.ConsentPurposeAutoCategorization) + if err != nil || active { + t.Fatalf("current C3 = %v, %v; want no active C3", active, err) + } +} + +// consentLedgerSnapshot returns every consent row and the count of consent +// events of the subject, so a test can prove a command left both unchanged. +func consentLedgerSnapshot(ctx context.Context, t *testing.T, harness *supportCaseHTTPHarness, subject uuid.UUID) string { + t.Helper() + var records string + var events int64 + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(record) ORDER BY record.id)::text, '[]') + FROM consent_records AS record WHERE record.subject_id = $1`, subject).Scan(&records); err != nil { + t.Fatalf("read consent ledger: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events + WHERE event_type LIKE 'consent.%' AND payload->>'subject_id' = $1`, subject.String()).Scan(&events); err != nil { + t.Fatalf("count consent events: %v", err) + } + return fmt.Sprintf("%s|events=%d", records, events) +} + +// userAssessmentSnapshot returns the attempts and the immutable results of one +// account as stable JSON, joined by "|". +func userAssessmentSnapshot(ctx context.Context, t *testing.T, harness *supportCaseHTTPHarness, userID uuid.UUID) string { + t.Helper() + var attempts, results string + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(attempt) ORDER BY attempt.id)::text, '[]') + FROM assessment_attempts AS attempt WHERE attempt.user_id = $1`, userID).Scan(&attempts); err != nil { + t.Fatalf("read assessment attempts: %v", err) + } + if err := harness.pool.QueryRow(ctx, `SELECT COALESCE(jsonb_agg(to_jsonb(result) ORDER BY result.attempt_id)::text, '[]') + FROM assessment_attempt_results AS result WHERE result.user_id = $1`, userID).Scan(&results); err != nil { + t.Fatalf("read assessment results: %v", err) + } + return attempts + "|" + results +} + +// completeManualAssessmentFixtureAttempt grants C3 (an automated attempt needs +// it), runs one real Backend/Junior attempt to completion, and answers every +// item correctly or incorrectly. +func completeManualAssessmentFixtureAttempt( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, + userID uuid.UUID, + cookie *http.Cookie, + csrf, remotePrefix string, + correct bool, +) uuid.UUID { + t.Helper() + attemptHarness := &assessmentAttemptHTTPHarness{sessionHTTPHarness: harness.sessionHTTPHarness, keyring: harness.keyring} + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step='candidate_questionnaire' WHERE id=$1", userID); err != nil { + t.Fatalf("set candidate onboarding step: %v", err) + } + questionnaire := `{"expected_version":0,"specializations":[{"specialization":"backend","self_assessed_grade":"junior","task_languages":["go"],"stack":[],"experience":null}],"work_context":{"work_formats":["remote"]}}` + if response := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPut, "/api/v1/me/questionnaire", questionnaire, + sessionHTTPTestOrigin, cookie.Value, csrf, "", remotePrefix+"1:1234"); response.Code != http.StatusOK { + t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String()) + } + grantManualAssessmentC3(t, harness, cookie, csrf, remotePrefix+"2:1234") + create := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, "/api/v1/me/assessment-attempts", + assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "manual-fixture-create-"+userID.String(), remotePrefix+"3:1234") + var attempt assessmentAnswerHTTPAttempt + if create.Code != http.StatusCreated || json.Unmarshal(create.Body.Bytes(), &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create fixture attempt = %d %s", create.Code, create.Body.String()) + } + version := attempt.Version + for _, item := range readAssessmentAnswerHTTPItems(t, ctx, attemptHarness, attempt.ID) { + body := assessmentAnswerHTTPBodyWithCorrectness(t, version, item, correct) + response := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), + sessionHTTPTestOrigin, cookie.Value, csrf, fmt.Sprintf("manual-fixture-answer-%s-%d", userID, item.Ordinal), remotePrefix+"4:1234") + var next assessmentAnswerHTTPAttempt + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &next) != nil { + t.Fatalf("answer fixture item %d = %d %s", item.Ordinal, response.Code, response.Body.String()) + } + version = next.Version + } + finalizeBody := fmt.Sprintf(`{"expected_version":%d}`, version) + finalized := assessmentAttemptHTTPRequest(t, attemptHarness, http.MethodPost, + "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", finalizeBody, + sessionHTTPTestOrigin, cookie.Value, csrf, "manual-fixture-finalize-"+userID.String(), remotePrefix+"5:1234") + var completed assessmentAnswerHTTPAttempt + if finalized.Code != http.StatusOK || json.Unmarshal(finalized.Body.Bytes(), &completed) != nil || completed.State != "completed" { + t.Fatalf("finalize fixture attempt = %d %s, want completed", finalized.Code, finalized.Body.String()) + } + wantOutcome := "not_confirmed" + if correct { + wantOutcome = "confirmed" + } + var outcome string + if err := harness.pool.QueryRow(ctx, `SELECT outcome FROM assessment_attempt_results WHERE attempt_id = $1`, attempt.ID).Scan(&outcome); err != nil || outcome != wantOutcome { + t.Fatalf("stored fixture outcome = %q, %v; want %q", outcome, err, wantOutcome) + } + return attempt.ID +} diff --git a/backend/integration_test/match_search_http_test.go b/backend/integration_test/match_search_http_test.go new file mode 100644 index 0000000..dc200bd --- /dev/null +++ b/backend/integration_test/match_search_http_test.go @@ -0,0 +1,1373 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "math" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + apiadapter "lincodex/backend/internal/adapter/primary/http/api" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/evidence" + "lincodex/backend/internal/usecase/matching" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/organization" + "lincodex/backend/internal/usecase/policy" + profileusecase "lincodex/backend/internal/usecase/profile" + "lincodex/backend/internal/usecase/semantic" +) + +const matchSearchHTTPTimeout = 15 * time.Minute + +// matchScoreTolerance covers the six-decimal rounding of the response. +const matchScoreTolerance = 1.5e-6 + +type matchSearchHarness struct { + *assessmentAttemptHTTPHarness + key domain.CandidateViewPseudonymKey +} + +func newMatchSearchHarness(ctx context.Context, t *testing.T, env *testEnvironment) *matchSearchHarness { + t.Helper() + return newMatchSearchHarnessWithSemantic(ctx, t, env, nil) +} + +// newMatchSearchHarnessWithSemantic wires the semantic trigger into the +// profile, publication, and need operations; nil schedules nothing. +func newMatchSearchHarnessWithSemantic(ctx context.Context, t *testing.T, env *testEnvironment, trigger *semantic.Trigger) *matchSearchHarness { + t.Helper() + var key domain.CandidateViewPseudonymKey + var organizationHandler *v1.OrganizationHandler + harness := newAssessmentAttemptHTTPHarnessWithMiddleware(ctx, t, env, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, + func(parts assessmentHarnessParts) []v1.HandlerOption { + var err error + if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now) + quota := companyquota.NewService(parts.clock.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + privacyDependencies := candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now} + needDependencies := needusecase.Dependencies{Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now} + profileService := profileusecase.NewService(parts.transactor, parts.clock.Now) + if trigger != nil { + privacyDependencies.Semantic = trigger + needDependencies.Semantic = trigger + profileService = profileService.WithSemantic(trigger, semanticCheckInterval) + } + settings, err := candidateprivacy.NewService(privacyDependencies) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: parts.transactor, Keyring: parts.keyring, Clock: parts.clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needDependencies) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + search, err := matching.NewService(matching.Dependencies{ + Transactor: parts.transactor, Cards: views.ListVisibleCards, Clock: parts.clock.Now, + Views: func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (matching.ViewSession, error) { + session, err := views.BeginSearchViews(ctx, unit, actorID, organizationID) + if err != nil { + return nil, err + } + return session, nil + }, + }) + if err != nil { + t.Fatalf("matching.NewService() error = %v", err) + } + evidenceService, err := evidence.NewService(evidence.Dependencies{ + Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection, + }) + if err != nil { + t.Fatalf("evidence.NewService() error = %v", err) + } + organizationHandler = v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + return []v1.HandlerOption{ + v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)), + v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)), + v1.WithProfile(v1.NewProfileHandler(profileService)), + v1.WithOrganization(organizationHandler), + v1.WithNeed(v1.NewNeedHandler(needService)), + v1.WithMatches(v1.NewMatchHandler(search)), + } + }, + func() []apiadapter.Middleware { + return []apiadapter.Middleware{httpadapter.NewCompanyContextMiddleware(organizationHandler)} + }) + return &matchSearchHarness{assessmentAttemptHTTPHarness: harness, key: key} +} + +type matchEntryBody struct { + CandidateHandle string `json:"candidate_handle"` + Specialization string `json:"specialization"` + ConfirmationStatus string `json:"confirmation_status"` + DeclaredGrade *string `json:"declared_grade"` + Category *struct { + Specialization string `json:"specialization"` + Grade string `json:"grade"` + Basis string `json:"basis"` + } `json:"category"` + Strength *string `json:"strength"` + PublicContext struct { + Stack []string `json:"stack"` + ExperienceBand *string `json:"experience_band"` + WorkFormats []string `json:"work_formats"` + SalaryCompatibility *string `json:"salary_compatibility"` + } `json:"public_context"` + EvidenceSummary []struct { + Code string `json:"code"` + State string `json:"state"` + } `json:"evidence_summary"` + Components map[string]*float64 `json:"components"` + UnknownFlags []struct { + Component string `json:"component"` + Reason string `json:"reason"` + } `json:"unknown_flags"` +} + +func (entry matchEntryBody) component(name string) float64 { + if value := entry.Components[name]; value != nil { + return *value + } + return math.NaN() +} + +func (entry matchEntryBody) summary() []string { + items := make([]string, 0, len(entry.EvidenceSummary)) + for _, item := range entry.EvidenceSummary { + items = append(items, item.Code+":"+item.State) + } + return items +} + +func (entry matchEntryBody) flags() []string { + flags := make([]string, 0, len(entry.UnknownFlags)) + for _, flag := range entry.UnknownFlags { + flags = append(flags, flag.Component+":"+flag.Reason) + } + return flags +} + +type matchSearchBody struct { + Source map[string]any `json:"source"` + Groups struct { + Main []matchEntryBody `json:"main"` + Near []matchEntryBody `json:"near"` + Unconfirmed []matchEntryBody `json:"unconfirmed"` + } `json:"groups"` + Truncated bool `json:"truncated"` +} + +func (body matchSearchBody) handles() map[string]string { + handles := make(map[string]string) + for group, entries := range map[string][]matchEntryBody{"main": body.Groups.Main, "near": body.Groups.Near, "unconfirmed": body.Groups.Unconfirmed} { + for _, entry := range entries { + handles[entry.CandidateHandle+"/"+entry.Specialization] = group + } + } + return handles +} + +func TestMatchSearchOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), matchSearchHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newMatchSearchHarness(ctx, t, &isolatedEnv) + // The scenarios below read banks of 11 and 16 entries, so the group limit is + // widened here; the demo value is checked by its own subtest. + wideLimit := func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = 100 } + widePolicy := domain.DemoProductPolicyV4() + wideLimit(&widePolicy) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, widePolicy, true) + threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) + client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} + transactor := postgresadapter.NewTransactor(harness.pool) + + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, + organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + + const profileMarkers = "Private Marker" + allFields := []string{"categories", "stack", "experience", "self_assessment", "work_formats"} + unconfirmedFields := []string{"stack", "self_assessment", "work_formats"} + profileBody := func(stack []string, roles map[string]string) string { + stackItems := make([]map[string]any, 0, len(stack)) + for _, tag := range stack { + stackItems = append(stackItems, map[string]any{"tag": tag, "status": "confirmed"}) + } + roleItems := make([]map[string]any, 0, len(roles)) + for _, specialization := range []string{"backend", "network_engineer"} { + if grade, ok := roles[specialization]; ok { + roleItems = append(roleItems, map[string]any{"specialization": specialization, "self_assessed_grade": grade, "status": "confirmed"}) + } + } + body, err := json.Marshal(map[string]any{ + "expected_version": 0, + "full_name": map[string]any{"value": profileMarkers + " Name", "status": "confirmed"}, + "contacts": map[string]any{ + "email": map[string]any{"value": "private-marker-contact@example.test", "status": "confirmed"}, "phone": nil, "telegram": nil, + }, + "stack": stackItems, "roles": roleItems, + "experience": []any{map[string]any{ + "employer_name": profileMarkers + " Employer", "specialization": "backend", "started_on": "2020-01", + "ended_on": "2023-12", "summary": profileMarkers + " Summary", "status": "confirmed", + }}, + "confirmed_parallel_periods": []any{}, "soft_skills": []any{}, + "terms": map[string]any{ + "location": map[string]any{"value": profileMarkers + " Location", "status": "confirmed"}, "relocation": nil, + "salary_minimum": map[string]any{"value": map[string]any{ + "amount": 731000, "currency": "RUB", "period": "month", "tax_basis": "net", + }, "status": "confirmed"}, + }, + }) + if err != nil { + t.Fatalf("marshal profile: %v", err) + } + return string(body) + } + call := func(who categoryHTTPCandidate, method, path, body string) (int, []byte) { + t.Helper() + return client.call(t, who, method, path, body, "") + } + mustCall := func(who categoryHTTPCandidate, method, path, body string, want int) []byte { + t.Helper() + status, response := call(who, method, path, body) + if status != want { + t.Fatalf("%s %s for %s = %d %s, want %d", method, path, who.email, status, response, want) + } + return response + } + // publish saves a profile and publishes the given card fields through the + // real candidate operations: the profile, the C2 consent, and the + // publication setting. + publish := func(who categoryHTTPCandidate, stack []string, roles map[string]string, fields []string) { + t.Helper() + mustCall(who, http.MethodPut, "/api/v1/me/profile", profileBody(stack, roles), http.StatusOK) + mustCall(who, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK) + encoded, err := json.Marshal(fields) + if err != nil { + t.Fatalf("marshal fields: %v", err) + } + mustCall(who, http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":0,"state":"published","fields":%s}`, encoded), http.StatusOK) + } + passing := func(who categoryHTTPCandidate) attemptRun { + t.Helper() + run := client.run(t, who, "backend", "intern", func(int) int { return threshold }) + if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" { + t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result) + } + return run + } + + bothRoles := map[string]string{"backend": "junior", "network_engineer": "middle"} + backendRole := map[string]string{"backend": "junior"} + + // G1: confirmed Backend with the Go tag; seven candidates so that each + // organization still sees six after one is hidden from it. + withGo := make([]categoryHTTPCandidate, 0, 7) + for index := range 7 { + member := client.candidate(t, fmt.Sprintf("match-go-%d@example.test", index)) + passing(member) + publish(member, []string{"go"}, bothRoles, allFields) + withGo = append(withGo, member) + } + // G2: the same confirmed category without any stack tag. + withoutStack := make([]categoryHTTPCandidate, 0, 5) + var promotionSource attemptRun + for index := range 5 { + member := client.candidate(t, fmt.Sprintf("match-plain-%d@example.test", index)) + run := passing(member) + if index == 4 { + promotionSource = run + } + publish(member, nil, bothRoles, allFields) + withoutStack = append(withoutStack, member) + } + // U: a declared Backend without a confirmed grade. One of them failed the + // attempt, which must change nothing in the result. + declaredOnly := make([]categoryHTTPCandidate, 0, 5) + for index := range 5 { + member := client.candidate(t, fmt.Sprintf("match-declared-%d@example.test", index)) + if index == 0 { + failed := client.run(t, member, "backend", "intern", func(int) int { return threshold - 1 }) + if failed.result["outcome"] != "not_confirmed" { + t.Fatalf("failing run = %v, want not_confirmed", failed.result["outcome"]) + } + } + publish(member, []string{"go"}, backendRole, unconfirmedFields) + declaredOnly = append(declaredOnly, member) + } + + employer := client.employer(t, "match-employer@example.test") + foreign := client.employer(t, "match-foreign@example.test") + recruiter := client.employer(t, "match-recruiter@example.test") + candidateOnly := client.candidate(t, "match-candidate-only@example.test") + orgA := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization A"), now) + orgB := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Match organization B"), now) + foreignOrg := organizations.create(t, domain.User{ID: foreign.id}, organizations.completeProfile(t, "Match foreign organization"), now) + insertOrganizationHTTPMembership(ctx, t, harness.sessionHTTPHarness, orgA.ID(), recruiter.id, "recruiter", "active", now) + hiddenFromA, hiddenFromB := withGo[0], withGo[1] + privacy.hide(t, hiddenFromA.id, orgA.ID(), now) + privacy.hide(t, hiddenFromB.id, orgB.ID(), now) + // The policy and the organizations take effect when they are stored, which + // is after the clock of the harness was read. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) + + candidateIDs := make(map[uuid.UUID]string) + for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { + for _, member := range group { + candidateIDs[member.id] = member.email + } + } + aliasIn := func(organizationID, candidateID uuid.UUID) string { + t.Helper() + alias, err := harness.key.ForOrganization(organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return alias + } + candidateOfHandle := func(organizationID uuid.UUID) map[string]uuid.UUID { + handles := make(map[string]uuid.UUID, len(candidateIDs)) + for id := range candidateIDs { + handles[aliasIn(organizationID, id)] = id + } + return handles + } + searchPath := func(organizationID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/matches", organizationID) + } + search := func(who categoryHTTPCandidate, organizationID uuid.UUID, body string) (matchSearchBody, *httptest.ResponseRecorder) { + t.Helper() + response := harness.request(t, http.MethodPost, searchPath(organizationID), body, sessionHTTPTestOrigin, who.cookie, who.csrf, client.remote()) + var decoded matchSearchBody + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &decoded); err != nil { + t.Fatalf("decode search result: %v\n%s", err, response.Body.String()) + } + } + return decoded, response + } + mustSearch := func(organizationID uuid.UUID, body string) matchSearchBody { + t.Helper() + result, response := search(employer, organizationID, body) + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("search = %d Cache-Control=%q %s, want a no-store 200", response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + return result + } + handlesOf := func(entries []matchEntryBody) []string { + handles := make([]string, 0, len(entries)) + for _, entry := range entries { + handles = append(handles, entry.CandidateHandle) + } + return handles + } + handlesFor := func(organizationID uuid.UUID, groups ...[]categoryHTTPCandidate) []string { + var handles []string + for _, group := range groups { + for _, member := range group { + handles = append(handles, aliasIn(organizationID, member.id)) + } + } + slices.Sort(handles) + return handles + } + sortedHandles := func(entries []matchEntryBody) []string { + handles := handlesOf(entries) + slices.Sort(handles) + return handles + } + almost := func(got, want float64) bool { return math.Abs(got-want) <= matchScoreTolerance } + assertScores := func(t *testing.T, label string, entries []matchEntryBody, want map[string]float64) { + t.Helper() + for _, entry := range entries { + for name, value := range want { + if got := entry.component(name); !almost(got, value) { + t.Errorf("%s entry %s %s = %v, want %v", label, entry.Specialization, name, got, value) + } + } + } + } + // assertOrder checks the documented order of a group from the internal + // identifiers that the test knows and the response never shows. + assertOrder := func(t *testing.T, organizationID uuid.UUID, entries []matchEntryBody, confirmed bool) { + t.Helper() + candidates := candidateOfHandle(organizationID) + for index := 1; index < len(entries); index++ { + previous, current := entries[index-1], entries[index] + var previousKeys, currentKeys []float64 + if confirmed { + previousKeys = []float64{previous.component("rank_score"), previous.component("coverage")} + currentKeys = []float64{current.component("rank_score"), current.component("coverage")} + } else { + previousKeys = []float64{previous.component("fit"), previous.component("coverage")} + currentKeys = []float64{current.component("fit"), current.component("coverage")} + } + for key := range previousKeys { + if previousKeys[key] > currentKeys[key] { + break + } + if previousKeys[key] < currentKeys[key] { + t.Fatalf("entry %d precedes %d although its scores are lower: %v then %v", index-1, index, previousKeys, currentKeys) + } + if key == len(previousKeys)-1 { + previousID, currentID := candidates[previous.CandidateHandle].String(), candidates[current.CandidateHandle].String() + if previousID > currentID || (previousID == currentID && previous.Specialization > current.Specialization) { + t.Fatalf("equal scores are not ordered by the internal identifier: %s before %s", previousID, currentID) + } + } + } + } + } + countRows := func(query string, args ...any) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count rows: %v", err) + } + return count + } + revealedBy := func(organizationID uuid.UUID) int { + t.Helper() + return countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1`, organizationID) + } + historyOf := func(candidateID, organizationID uuid.UUID) [][]string { + t.Helper() + rows, err := harness.pool.Query(ctx, `SELECT field_codes FROM candidate_card_access_events + WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' ORDER BY occurred_at, id`, candidateID, organizationID) + if err != nil { + t.Fatalf("read access history: %v", err) + } + defer rows.Close() + var history [][]string + for rows.Next() { + var fields []string + if err := rows.Scan(&fields); err != nil { + t.Fatalf("scan access history: %v", err) + } + history = append(history, fields) + } + return history + } + clockOffset := time.Minute + publishPolicy := func(change func(*domain.ProductPolicy)) { + t.Helper() + product := domain.DemoProductPolicyV4() + wideLimit(&product) + if change != nil { + change(&product) + } + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + if _, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: product, + }); err != nil { + t.Fatalf("Publish(policy) error = %v", err) + } + clockOffset += time.Minute + harness.clock.Set(time.Now().UTC().Add(clockOffset).Truncate(time.Microsecond)) + } + createNeed := func(organizationID uuid.UUID, body, key string) (uuid.UUID, int64) { + t.Helper() + status, response := client.call(t, employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", organizationID), body, key) + var need struct { + ID uuid.UUID `json:"id"` + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + if status != http.StatusCreated || json.Unmarshal(response, &need) != nil || need.ID == uuid.Nil { + t.Fatalf("create need = %d %s, want 201", status, response) + } + return need.ID, need.RequirementsVersion + } + patchNeed := func(organizationID, needID uuid.UUID, body string) (version, requirementsVersion int64) { + t.Helper() + status, response := client.call(t, employer, http.MethodPatch, fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID), body, "") + var need struct { + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + } + if status != http.StatusOK || json.Unmarshal(response, &need) != nil { + t.Fatalf("patch need = %d %s, want 200", status, response) + } + return need.Version, need.RequirementsVersion + } + needRequest := func(needID uuid.UUID, version int64, filters string) string { + body := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d`, needID, version) + if filters != "" { + body += `,"filters":` + filters + } + return body + "}" + } + + // The standing cohort sizes: each organization sees six of the seven + // candidates with the Go tag and all five of the others. + t.Run("the bank search applies visibility and hiding before any group and keeps an unconfirmed category visible", func(t *testing.T) { + bankA := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + if bankA.Truncated { + t.Fatal("a result under the group limit and the allowance is flagged as truncated") + } + wantA := handlesFor(orgA.ID(), withGo[1:], withoutStack) + if got := sortedHandles(bankA.Groups.Main); !slices.Equal(got, wantA) || len(bankA.Groups.Near) != 0 || len(bankA.Groups.Unconfirmed) != 0 { + t.Fatalf("organization A confirmed bank = %d main, %d near, %d unconfirmed; want exactly the eleven visible confirmed candidates", + len(bankA.Groups.Main), len(bankA.Groups.Near), len(bankA.Groups.Unconfirmed)) + } + // Every confirmed category names its basis, so a demonstration grade is + // never presented as a standard confirmation. + for _, entry := range bankA.Groups.Main { + if entry.Category == nil || entry.Category.Basis != "synthetic_demo" { + t.Fatalf("confirmed entry %s category = %+v, want the synthetic_demo basis", entry.CandidateHandle, entry.Category) + } + } + if slices.Contains(handlesOf(bankA.Groups.Main), aliasIn(orgA.ID(), hiddenFromA.id)) { + t.Fatal("organization A received a candidate that hides it") + } + bankB := mustSearch(orgB.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + wantB := handlesFor(orgB.ID(), append([]categoryHTTPCandidate{withGo[0]}, withGo[2:]...), withoutStack) + if got := sortedHandles(bankB.Groups.Main); !slices.Equal(got, wantB) { + t.Fatalf("organization B main handles = %v, want %v", got, wantB) + } + if slices.Contains(handlesOf(bankB.Groups.Main), aliasIn(orgB.ID(), hiddenFromB.id)) { + t.Fatal("organization B received a candidate that hides it") + } + // The same candidate has a different handle in each organization. + if aliasIn(orgA.ID(), withGo[2].id) == aliasIn(orgB.ID(), withGo[2].id) { + t.Fatal("organizations share a candidate handle") + } + + for _, entry := range append(bankA.Groups.Main, bankB.Groups.Main...) { + if entry.ConfirmationStatus != "confirmed" || entry.Category == nil || entry.Category.Specialization != "backend" || + entry.Category.Grade != "intern" || entry.Strength == nil || *entry.Strength != "standard" { + t.Fatalf("confirmed entry = %+v, want the confirmed Backend intern category", entry) + } + if entry.Components["percentile"] != nil || entry.component("competition") != 0 || !almost(entry.component("semantics"), 0.5) || + !slices.Contains(entry.flags(), "semantics:ml_unavailable") || !slices.Contains(entry.flags(), "percentile:cohort_below_30") { + t.Fatalf("confirmed entry components = %v flags %v, want neutral Sem, no percentile, and V = 0", entry.Components, entry.flags()) + } + } + + // Without a filter the same bank also lists the specializations that + // are only declared; a missing confirmation never hides a profile. + general := mustSearch(orgA.ID(), `{"filters":{}}`) + if len(general.Groups.Main) != 11 || len(general.Groups.Near) != 0 { + t.Fatalf("general search = %d main, %d near, want eleven main and no near without a request for skills", len(general.Groups.Main), len(general.Groups.Near)) + } + var networks, backendDeclared []string + for _, entry := range general.Groups.Unconfirmed { + switch entry.Specialization { + case "network_engineer": + networks = append(networks, entry.CandidateHandle) + case "backend": + backendDeclared = append(backendDeclared, entry.CandidateHandle) + } + if entry.ConfirmationStatus != "unconfirmed" || entry.Category != nil || entry.Strength != nil { + t.Fatalf("unconfirmed entry = %+v, want no category and no strength", entry) + } + } + slices.Sort(networks) + slices.Sort(backendDeclared) + if !slices.Equal(networks, handlesFor(orgA.ID(), withGo[1:], withoutStack)) || + !slices.Equal(backendDeclared, handlesFor(orgA.ID(), declaredOnly)) || len(general.Groups.Unconfirmed) != 11+5 { + t.Fatalf("unconfirmed group = %d entries (networks %d, declared Backend %d), want 16", len(general.Groups.Unconfirmed), len(networks), len(backendDeclared)) + } + assertScores(t, "general unconfirmed", general.Groups.Unconfirmed, map[string]float64{"fit": 0.5, "coverage": 0.5}) + assertScores(t, "general confirmed", general.Groups.Main, map[string]float64{"fit": 0.5, "coverage": 0.5, "rank_score": 0.45125}) + if source, _ := general.Source["kind"].(string); source != "bank" { + t.Fatalf("source = %v, want the bank basis", general.Source) + } + }) + + var needID uuid.UUID + var needRequirementsV1 int64 + var firstNeedSearch, secondNeedSearch matchSearchBody + var secondRequirementsVersion int64 + t.Run("a need search scores the confirmed requirements and the explanation follows the same components", func(t *testing.T) { + needID, needRequirementsV1 = createNeed(orgA.ID(), + `{"title":"Payments backend","specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Go","status":"confirmed"}]}`, + "match-need-1") + firstNeedSearch = mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, "")) + if source := firstNeedSearch.Source; source["kind"] != "need" || source["need_id"] != needID.String() || source["requirements_version"] != float64(needRequirementsV1) { + t.Fatalf("source = %v, want the need snapshot", source) + } + // A Go tag is a stated claim worth 0.25 and meets the near threshold; a + // backend measurement is broader than the requested skill, worth + // 0.6 * 1.0 * 0.4 = 0.24, and falls below it. + if got, want := sortedHandles(firstNeedSearch.Groups.Main), handlesFor(orgA.ID(), withGo[1:]); !slices.Equal(got, want) { + t.Fatalf("main = %v, want the six candidates with the Go tag", got) + } + if got, want := sortedHandles(firstNeedSearch.Groups.Near), handlesFor(orgA.ID(), withoutStack); !slices.Equal(got, want) { + t.Fatalf("near = %v, want the five candidates without the tag", got) + } + if got, want := sortedHandles(firstNeedSearch.Groups.Unconfirmed), handlesFor(orgA.ID(), declaredOnly); !slices.Equal(got, want) { + t.Fatalf("unconfirmed = %v, want the five declared Backend profiles, and no other specialization of a Backend need", got) + } + assertScores(t, "main", firstNeedSearch.Groups.Main, map[string]float64{"coverage": 0.25, "fit": 0.3125, "rank_score": 0.366641}) + assertScores(t, "near", firstNeedSearch.Groups.Near, map[string]float64{"coverage": 0.24, "fit": 0.305, "rank_score": 0.363256}) + assertScores(t, "unconfirmed", firstNeedSearch.Groups.Unconfirmed, map[string]float64{"coverage": 0.25, "fit": 0.3125}) + wantMain := []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:declared_only"} + wantNear := []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:partial"} + wantUnconfirmed := []string{"declared_grade:declared_only", "required_skill_evidence:declared_only"} + for _, check := range []struct { + entries []matchEntryBody + want []string + }{{firstNeedSearch.Groups.Main, wantMain}, {firstNeedSearch.Groups.Near, wantNear}, {firstNeedSearch.Groups.Unconfirmed, wantUnconfirmed}} { + for _, entry := range check.entries { + if got := entry.summary(); !slices.Equal(got, check.want) { + t.Fatalf("explanation of %s = %v, want %v", entry.Specialization, got, check.want) + } + } + } + + // Changing the required skills moves the numbers, the groups, and the + // explanation together. + version, requirementsVersion := patchNeed(orgA.ID(), needID, + `{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"Kafka","status":"confirmed"}]}`) + secondRequirementsVersion = requirementsVersion + if requirementsVersion != version || requirementsVersion == needRequirementsV1 { + t.Fatalf("requirements version after the change = %d (version %d), want a new snapshot", requirementsVersion, version) + } + secondNeedSearch = mustSearch(orgA.ID(), needRequest(needID, requirementsVersion, "")) + if len(secondNeedSearch.Groups.Main) != 0 || len(secondNeedSearch.Groups.Near) != 11 || len(secondNeedSearch.Groups.Unconfirmed) != 5 { + t.Fatalf("second search = %d main, %d near, %d unconfirmed, want every confirmed profile in near", len(secondNeedSearch.Groups.Main), len(secondNeedSearch.Groups.Near), len(secondNeedSearch.Groups.Unconfirmed)) + } + for _, entry := range secondNeedSearch.Groups.Near { + if entry.PublicContext.Stack == nil { + assertScores(t, "near without a tag", []matchEntryBody{entry}, map[string]float64{"coverage": 0.24, "fit": 0.305, "rank_score": 0.363256}) + continue + } + // (2 * 0.25 + 2 * 0.24) / 4 = 0.245 + assertScores(t, "near with the Go tag", []matchEntryBody{entry}, map[string]float64{"coverage": 0.245, "fit": 0.30875, "rank_score": 0.364948}) + if got := entry.summary(); !slices.Equal(got, []string{"confirmed_category:supports", "declared_grade:declared_only", "required_skill_evidence:partial"}) { + t.Fatalf("explanation with the Kafka requirement = %v", got) + } + } + // (2 * 0.25 + 2 * 0) / 4 = 0.125: Kafka has no evidence, and that is a gap, not a ban. + assertScores(t, "unconfirmed", secondNeedSearch.Groups.Unconfirmed, map[string]float64{"coverage": 0.125, "fit": 0.21875}) + for _, entry := range secondNeedSearch.Groups.Unconfirmed { + if got := entry.summary(); !slices.Equal(got, []string{"declared_grade:declared_only", "required_skill_evidence:partial"}) { + t.Fatalf("explanation of an unconfirmed entry with the Kafka requirement = %v", got) + } + } + + // The first snapshot is immutable: it answers as it did. + again := mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, "")) + if !jsonEqual(t, again, firstNeedSearch) { + t.Fatal("the search of the first requirements version changed after the need was edited") + } + // A title edit makes a need version but no requirements version. + titleVersion, titleRequirements := patchNeed(orgA.ID(), needID, `{"expected_version":2,"title":"Payments backend team"}`) + if titleVersion != 3 || titleRequirements != secondRequirementsVersion { + t.Fatalf("title edit = version %d, requirements %d, want 3 and %d", titleVersion, titleRequirements, secondRequirementsVersion) + } + if _, response := search(employer, orgA.ID(), needRequest(needID, titleVersion, "")); response.Code != http.StatusNotFound { + t.Fatalf("search by a need version that is not a requirements version = %d, want 404", response.Code) + } + if _, response := search(employer, orgA.ID(), needRequest(needID, secondRequirementsVersion+5, "")); response.Code != http.StatusNotFound { + t.Fatalf("search by an unknown requirements version = %d, want 404", response.Code) + } + // Another organization cannot search a need it does not own. + if _, response := search(employer, orgB.ID(), needRequest(needID, needRequirementsV1, "")); response.Code != http.StatusNotFound { + t.Fatalf("search of a need of another organization = %d, want 404", response.Code) + } + if _, response := search(employer, orgA.ID(), needRequest(uuid.New(), 1, "")); response.Code != http.StatusNotFound { + t.Fatalf("search of an unknown need = %d, want 404", response.Code) + } + // A need without a confirmed specialization searches every + // specialization, and the unconfirmed group then mixes them: Fit + // decides, then coverage, then the internal identifier. + anyID, anyVersion := createNeed(orgA.ID(), + `{"title":"Any specialization","required_skills":[{"name":"Go","status":"confirmed"},{"name":"Kafka","status":"confirmed"}]}`, + "match-need-any") + anySearch := mustSearch(orgA.ID(), needRequest(anyID, anyVersion, "")) + if len(anySearch.Groups.Main) != 0 || len(anySearch.Groups.Near) != 11 || len(anySearch.Groups.Unconfirmed) != 16 { + t.Fatalf("search without a need specialization = %d main, %d near, %d unconfirmed, want 0, 11, 16", + len(anySearch.Groups.Main), len(anySearch.Groups.Near), len(anySearch.Groups.Unconfirmed)) + } + // The five Networks entries of candidates without the Go tag have no + // evidence for either skill and come last, as a gap and not as a ban. + lastFive := anySearch.Groups.Unconfirmed[11:] + for _, entry := range lastFive { + if entry.Specialization != "network_engineer" || entry.component("coverage") != 0 || !almost(entry.component("fit"), 0.125) { + t.Fatalf("last unconfirmed entry = %+v %v, want a Networks entry without evidence", entry.Specialization, entry.Components) + } + if got := entry.summary(); !slices.Equal(got, []string{"declared_grade:declared_only", "required_skill_evidence:gap"}) { + t.Fatalf("explanation of an entry without evidence = %v", got) + } + } + assertScores(t, "unconfirmed with evidence", anySearch.Groups.Unconfirmed[:11], map[string]float64{"coverage": 0.125, "fit": 0.21875}) + assertOrder(t, orgA.ID(), anySearch.Groups.Unconfirmed, false) + assertOrder(t, orgA.ID(), anySearch.Groups.Near, true) + // A different specialization filter than the need leaves nothing. + empty := mustSearch(orgA.ID(), needRequest(needID, needRequirementsV1, `{"specialization":"frontend"}`)) + if len(empty.Groups.Main)+len(empty.Groups.Near)+len(empty.Groups.Unconfirmed) != 0 { + t.Fatalf("search with a specialization filter that contradicts the need returned entries: %+v", empty.Groups) + } + }) + + t.Run("the same data and policy give the same order and scores, and each organization its own handles", func(t *testing.T) { + request := needRequest(needID, needRequirementsV1, "") + var first []byte + for range 3 { + _, response := search(employer, orgA.ID(), request) + if response.Code != http.StatusOK { + t.Fatalf("repeat search = %d %s", response.Code, response.Body.String()) + } + if first == nil { + first = bytes.Clone(response.Body.Bytes()) + } else if !bytes.Equal(first, response.Body.Bytes()) { + t.Fatalf("repeat search changed:\n%s\n%s", first, response.Body.Bytes()) + } + } + assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Main, true) + assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Near, true) + assertOrder(t, orgA.ID(), firstNeedSearch.Groups.Unconfirmed, false) + assertOrder(t, orgA.ID(), secondNeedSearch.Groups.Near, true) + // Organization B sees the bank through its own handles and its own + // hiding, with the same scores. + bank := `{"filters":{"specialization":"backend"}}` + forA, forB := mustSearch(orgA.ID(), bank), mustSearch(orgB.ID(), bank) + for _, handle := range handlesOf(forB.Groups.Main) { + if slices.Contains(handlesOf(forA.Groups.Main), handle) { + t.Fatalf("handle %s is shared by two organizations", handle) + } + } + if slices.Contains(handlesOf(forB.Groups.Main), aliasIn(orgB.ID(), hiddenFromB.id)) || !slices.Contains(handlesOf(forB.Groups.Main), aliasIn(orgB.ID(), hiddenFromA.id)) { + t.Fatal("organization B does not get exactly the cards that are not hidden from B") + } + }) + + t.Run("a candidate keeps a separate state for each specialization", func(t *testing.T) { + general := mustSearch(orgA.ID(), `{"filters":{}}`) + member := withGo[3] + handle := aliasIn(orgA.ID(), member.id) + var confirmedEntry, networkEntry *matchEntryBody + for index := range general.Groups.Main { + if general.Groups.Main[index].CandidateHandle == handle { + confirmedEntry = &general.Groups.Main[index] + } + } + for index := range general.Groups.Unconfirmed { + if general.Groups.Unconfirmed[index].CandidateHandle == handle { + networkEntry = &general.Groups.Unconfirmed[index] + } + } + if confirmedEntry == nil || networkEntry == nil || confirmedEntry.Specialization != "backend" || networkEntry.Specialization != "network_engineer" { + t.Fatalf("entries of one handle = %+v and %+v, want confirmed Backend and unconfirmed Networks", confirmedEntry, networkEntry) + } + if confirmedEntry.DeclaredGrade == nil || *confirmedEntry.DeclaredGrade != "junior" || + networkEntry.DeclaredGrade == nil || *networkEntry.DeclaredGrade != "middle" { + t.Fatalf("declared grades = %v and %v, want junior for Backend and middle for Networks", confirmedEntry.DeclaredGrade, networkEntry.DeclaredGrade) + } + if got := networkEntry.flags(); !slices.Equal(got, []string{ + "semantics:ml_unavailable", "assessment:no_confirmation_for_specialization", "salary_compatibility:not_in_public_card", "domain:need_field_unconfirmed", + }) { + t.Fatalf("unknown flags of the unconfirmed entry = %v", got) + } + // The unconfirmed object holds a fit and a coverage and nothing else: + // no theta, T, P, percentile, or rank score. + if len(networkEntry.Components) != 2 || networkEntry.Components["fit"] == nil || networkEntry.Components["coverage"] == nil { + t.Fatalf("unconfirmed components = %v, want only fit and coverage", networkEntry.Components) + } + // A search for Networks shows Backend's confirmation nowhere. + networks := mustSearch(orgA.ID(), `{"filters":{"specialization":"network_engineer"}}`) + if len(networks.Groups.Main)+len(networks.Groups.Near) != 0 || len(networks.Groups.Unconfirmed) != 11 { + t.Fatalf("Networks search = %d confirmed, %d unconfirmed, want 11 unconfirmed and no transferred confirmation", + len(networks.Groups.Main)+len(networks.Groups.Near), len(networks.Groups.Unconfirmed)) + } + // An explicit filter on a confirmed grade or category excludes every + // unconfirmed profile; a declared grade is a separate claim. + for _, filters := range []string{ + `{"confirmed_grade":"intern"}`, `{"confirmed_category":{"specialization":"backend","grade":"intern"}}`, `{"confirmation_status":"confirmed"}`, + } { + filtered := mustSearch(orgA.ID(), fmt.Sprintf(`{"filters":%s}`, filters)) + if len(filtered.Groups.Unconfirmed) != 0 || len(filtered.Groups.Main) != 11 { + t.Fatalf("filters %s = %d main, %d unconfirmed, want only the confirmed profiles", filters, len(filtered.Groups.Main), len(filtered.Groups.Unconfirmed)) + } + } + if filtered := mustSearch(orgA.ID(), `{"filters":{"confirmed_grade":"senior"}}`); len(filtered.Groups.Main)+len(filtered.Groups.Unconfirmed) != 0 { + t.Fatalf("a confirmed senior filter matched %d entries, want none", len(filtered.Groups.Main)+len(filtered.Groups.Unconfirmed)) + } + onlyUnconfirmed := mustSearch(orgA.ID(), `{"filters":{"confirmation_status":"unconfirmed"}}`) + if len(onlyUnconfirmed.Groups.Main)+len(onlyUnconfirmed.Groups.Near) != 0 || len(onlyUnconfirmed.Groups.Unconfirmed) != 16 { + t.Fatalf("unconfirmed-only search = %d entries, want the 16 unconfirmed", len(onlyUnconfirmed.Groups.Unconfirmed)) + } + declared := mustSearch(orgA.ID(), `{"filters":{"declared_grade":"middle"}}`) + if len(declared.Groups.Main)+len(declared.Groups.Near) != 0 || len(declared.Groups.Unconfirmed) != 11 { + t.Fatalf("declared middle search = %d entries, want the 11 Networks declarations and no confirmed entry", len(declared.Groups.Unconfirmed)) + } + // Safe card conditions and stack filters narrow the visible set. + stack := mustSearch(orgA.ID(), `{"filters":{"stack":["go"]}}`) + if len(stack.Groups.Main) != 6 || len(stack.Groups.Unconfirmed) != 6+5 { + t.Fatalf("stack filter = %d main, %d unconfirmed, want the six candidates with the tag and their entries", len(stack.Groups.Main), len(stack.Groups.Unconfirmed)) + } + conditions := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["office"]}}}`) + if len(conditions.Groups.Main)+len(conditions.Groups.Near)+len(conditions.Groups.Unconfirmed) != 0 { + t.Fatal("a work format that no card offers matched a candidate") + } + remote := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["remote","office"],"salary_compatibility":"compatible"}}}`) + if len(remote.Groups.Main)+len(remote.Groups.Near)+len(remote.Groups.Unconfirmed) != 0 { + t.Fatal("an unknown salary compatibility satisfied a compatibility filter") + } + if remoteOnly := mustSearch(orgA.ID(), `{"filters":{"conditions":{"work_formats":["remote"]}}}`); len(remoteOnly.Groups.Main) != 11 { + t.Fatalf("remote filter = %d main, want 11", len(remoteOnly.Groups.Main)) + } + }) + + t.Run("a failed promotion keeps the confirmed category and leaves no trace in the result", func(t *testing.T) { + member := withoutStack[4] + before := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + // The promotion interval counts on database time, so the finished + // intern attempt is moved past it instead of waiting for days. + moveFinishedAttemptBack(t, ctx, harness.pool, promotionSource.id, categoryHTTPPromotionGap) + failed := client.run(t, member, "backend", "junior", func(int) int { return threshold - 1 }) + if failed.result["outcome"] != "not_confirmed" || failed.result["previous_confirmed_grade"] != "intern" { + t.Fatalf("failed promotion = %v, want not_confirmed with the intern grade in force", failed.result) + } + after := mustSearch(orgA.ID(), `{"filters":{"confirmed_category":{"specialization":"backend","grade":"intern"}}}`) + if !jsonEqual(t, before, after) { + t.Fatal("a failed promotion changed the search result: the confirmed grade must stay and the failure must not count") + } + }) + + t.Run("the response holds no contact, minimum, identifier, failure, or percentile", func(t *testing.T) { + _, response := search(employer, orgA.ID(), `{"filters":{}}`) + text := response.Body.String() + for _, forbidden := range []string{ + profileMarkers, "private-marker-contact", "731000", "email", "phone", "telegram", "salary_minimum", "full_name", "location", + "theta", "not_confirmed", "failed", "attempt", "answer", "score_id", "fsp", "FSP", "policy", orgA.ID().String(), orgB.ID().String(), + } { + if strings.Contains(text, forbidden) { + t.Fatalf("search result contains %q: %s", forbidden, text) + } + } + for id, email := range candidateIDs { + if strings.Contains(text, id.String()) || strings.Contains(text, email) { + t.Fatalf("search result contains an account identifier or email of %s", email) + } + } + // The candidate whose attempt failed is scored exactly like the others + // who declared the same profile: no failure and no missing FSP is a penalty. + var reference *matchEntryBody + for index, entry := range mustSearch(orgA.ID(), `{"filters":{"specialization":"backend","confirmation_status":"unconfirmed"}}`).Groups.Unconfirmed { + if index == 0 { + reference = &entry + continue + } + if entry.component("fit") != reference.component("fit") || entry.component("coverage") != reference.component("coverage") { + t.Fatalf("an unconfirmed entry is scored differently from its twin: %v vs %v", entry.Components, reference.Components) + } + } + }) + + t.Run("a search is charged like card reads and the candidate sees it in the access history", func(t *testing.T) { + // Each organization has paid once for each candidate it was shown: the + // sixteen visible ones, never the candidate who hides it, and the + // organizations are counted independently. + if got := revealedBy(orgA.ID()); got != 16 { + t.Fatalf("organization A paid for %d candidates, want 16", got) + } + if got := revealedBy(orgB.ID()); got != 16 { + t.Fatalf("organization B paid for %d candidates, want 16", got) + } + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgA.ID(), hiddenFromA.id) != 0 || + countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgB.ID(), hiddenFromB.id) != 0 { + t.Fatal("an organization paid for a candidate who hides it") + } + if countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2`, hiddenFromA.id, orgA.ID()) != 0 { + t.Fatal("a candidate who hides the organization has a card view from it") + } + // The history names the fields actually returned: a candidate with a + // confirmed category shows all five published fields in a full search and + // a declared profile never shows the ones it did not publish. + confirmedHistory := historyOf(withGo[3].id, orgA.ID()) + fullFields := []string{"categories", "experience", "self_assessment", "stack", "work_formats"} + full := false + for _, fields := range confirmedHistory { + full = full || slices.Equal(fields, fullFields) + for _, field := range fields { + if !slices.Contains(fullFields, field) { + t.Fatalf("history of a confirmed candidate names %q, which no entry shows", field) + } + } + } + if len(confirmedHistory) == 0 || !full { + t.Fatalf("history of a confirmed candidate = %v, want card views including the five fields", confirmedHistory) + } + declaredHistory := historyOf(declaredOnly[1].id, orgA.ID()) + if len(declaredHistory) == 0 { + t.Fatal("a declared candidate has no card view in the history") + } + for _, fields := range declaredHistory { + if !slices.Equal(fields, []string{"self_assessment", "stack", "work_formats"}) { + t.Fatalf("history of a declared candidate = %v, want only the published declared fields", fields) + } + } + // Repeating the search charges nothing new, and a card read afterwards + // does not charge a second time. + before := revealedBy(orgA.ID()) + mustSearch(orgA.ID(), `{"filters":{}}`) + if revealedBy(orgA.ID()) != before { + t.Fatal("a repeated search charged the organization again") + } + // A search that is refused writes nothing. + eventsBefore := countRows(`SELECT count(*) FROM candidate_card_access_events`) + if _, response := search(recruiter, orgA.ID(), `{"filters":{}}`); response.Code != http.StatusForbidden { + t.Fatalf("recruiter search = %d, want 403", response.Code) + } + if countRows(`SELECT count(*) FROM candidate_card_access_events`) != eventsBefore || revealedBy(orgA.ID()) != before { + t.Fatal("a refused search charged or recorded") + } + }) + + t.Run("a profile published without a grade appears last, a confirmed filter excludes it, and a revoked C2 removes it", func(t *testing.T) { + extra := client.candidate(t, "match-declared-extra@example.test") + handle := aliasIn(orgA.ID(), extra.id) + candidateIDs[extra.id] = extra.email + listed := func() string { + result := mustSearch(orgA.ID(), `{"filters":{}}`) + return result.handles()[handle+"/backend"] + } + if listed() != "" { + t.Fatal("an unpublished profile is listed") + } + publish(extra, []string{"go"}, backendRole, unconfirmedFields) + if group := listed(); group != "unconfirmed" { + t.Fatalf("a profile published without a grade is in group %q, want unconfirmed", group) + } + for _, filters := range []string{`{"confirmed_grade":"intern"}`, `{"confirmation_status":"confirmed"}`, `{"confirmed_category":{"specialization":"backend","grade":"junior"}}`} { + if _, listed := mustSearch(orgA.ID(), fmt.Sprintf(`{"filters":%s}`, filters)).handles()[handle+"/backend"]; listed { + t.Fatalf("filters %s kept an unconfirmed profile", filters) + } + } + mustCall(extra, http.MethodDelete, "/api/v1/me/consents/c2", "", http.StatusNoContent) + if group := listed(); group != "" { + t.Fatalf("a profile whose C2 was revoked is still in group %q", group) + } + }) + + t.Run("a card that the cohort rules suppress is not searched, and a listed handle opens as a card", func(t *testing.T) { + single := client.candidate(t, "match-unique@example.test") + candidateIDs[single.id] = single.email + publish(single, []string{"kafka"}, map[string]string{"backend": "senior"}, unconfirmedFields) + handle := aliasIn(orgA.ID(), single.id) + general := mustSearch(orgA.ID(), `{"filters":{}}`) + if _, listed := general.handles()[handle+"/backend"]; listed { + t.Fatal("a profile alone in its cohort is listed although its card would not open") + } + if got := harness.request(t, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgA.ID(), handle), "", + "", employer.cookie, "", client.remote()); got.Code != http.StatusNotFound { + t.Fatalf("card of the suppressed profile = %d, want 404", got.Code) + } + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgA.ID(), single.id) != 0 || + len(historyOf(single.id, orgA.ID())) != 0 { + t.Fatal("a suppressed profile was charged or recorded") + } + opened := general.Groups.Main[0].CandidateHandle + openedID := candidateOfHandle(orgA.ID())[opened] + paid, seen := revealedBy(orgA.ID()), len(historyOf(openedID, orgA.ID())) + if got := harness.request(t, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgA.ID(), opened), "", + "", employer.cookie, "", client.remote()); got.Code != http.StatusOK { + t.Fatalf("card of a listed handle = %d %s, want 200", got.Code, got.Body.String()) + } + // The candidate was already paid for by the search, so opening the card + // charges nothing again, and the card read is one more history entry. + if revealedBy(orgA.ID()) != paid || len(historyOf(openedID, orgA.ID())) != seen+1 { + t.Fatalf("after the card read: paid %d (was %d), history %d (was %d), want no new charge and one new entry", + revealedBy(orgA.ID()), paid, len(historyOf(openedID, orgA.ID())), seen) + } + }) + + t.Run("only the active owner of the organization may search, and the body is closed", func(t *testing.T) { + body := `{"filters":{}}` + path := searchPath(orgA.ID()) + unauthenticated := harness.request(t, http.MethodPost, path, body, sessionHTTPTestOrigin, "", "", client.remote()) + requireSessionProblem(t, unauthenticated, http.StatusUnauthorized, "unauthenticated") + if _, response := search(candidateOnly, orgA.ID(), body); response.Code != http.StatusForbidden { + t.Fatalf("candidate account search = %d, want 403", response.Code) + } + if _, response := search(foreign, orgA.ID(), body); response.Code != http.StatusNotFound { + t.Fatalf("search of an organization without membership = %d, want 404", response.Code) + } + if _, response := search(employer, uuid.New(), body); response.Code != http.StatusNotFound { + t.Fatalf("search of an unknown organization = %d, want 404", response.Code) + } + // A recruiter has an active membership, which grants nothing without + // the owner role in the minimal milestone. + if _, response := search(recruiter, orgA.ID(), body); response.Code != http.StatusForbidden { + t.Fatalf("recruiter search = %d, want 403", response.Code) + } + noCSRF := harness.request(t, http.MethodPost, path, body, sessionHTTPTestOrigin, employer.cookie, "", client.remote()) + requireSessionProblem(t, noCSRF, http.StatusForbidden, "csrf_check_failed") + foreignOrigin := harness.request(t, http.MethodPost, path, body, "https://attacker.example", employer.cookie, employer.csrf, client.remote()) + requireSessionProblem(t, foreignOrigin, http.StatusForbidden, "csrf_check_failed") + for _, invalid := range []string{ + `{"filters":{"unknown":1}}`, `{"filters":{"stack":["go","go"]}}`, `{"filters":{"confirmed_grade":"principal"}}`, + `{"filters":{"conditions":{"salary_compatibility":"maybe"}}}`, `{"filters":{},"need_id":"` + uuid.NewString() + `"}`, `{}`, + } { + if _, response := search(employer, orgA.ID(), invalid); response.Code != http.StatusBadRequest { + t.Fatalf("search with body %s = %d %s, want 400", invalid, response.Code, response.Body.String()) + } + } + _ = foreignOrg + }) + + t.Run("the batch evidence read equals the single read and honors hiding", func(t *testing.T) { + categories := []domain.CandidateViewCategory{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Strength: domain.CandidateViewStrengthStandard}} + members := []categoryHTTPCandidate{withGo[0], withGo[2], withoutStack[0], declaredOnly[0]} + requests := make([]outbound.EvidenceCandidateCategories, 0, len(members)) + for _, member := range members { + requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: member.id, Categories: categories}) + } + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + batch, err := unit.Evidence().ListOrganizationFactsBatch(ctx, orgA.ID(), requests) + if err != nil { + return err + } + for _, member := range members { + single, err := unit.Evidence().ListOrganizationFacts(ctx, orgA.ID(), member.id, categories) + if err != nil { + return err + } + if len(batch[member.id]) != len(single) || len(single) > 0 && !reflect.DeepEqual(batch[member.id], single) { + t.Errorf("batch facts of %s = %v, single = %v", member.email, batch[member.id], single) + } + } + // The candidate who hides organization A and the candidate without a + // published category have no fact in the batch. + if len(batch[hiddenFromA.id]) != 0 || len(batch[declaredOnly[0].id]) != 0 || len(batch[withGo[2].id]) != 1 { + t.Errorf("batch = %v, want one fact for a visible confirmed candidate and none for hidden or declared ones", batch) + } + counts, err := unit.Evidence().CountComparableRealCategories(ctx, []outbound.CategoryKey{{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern}}) + if err != nil { + return err + } + if len(counts) != 0 { + t.Errorf("real cohort counts = %v, want none: every stored category is a synthetic demonstration", counts) + } + return nil + }) + if err != nil { + t.Fatalf("read evidence in a batch: %v", err) + } + }) + + t.Run("the allowance of an organization ends the output and the group limit cuts it, without a total", func(t *testing.T) { + // Organizations of one owner share the E0 pool, so this one gets an owner of its own. + ownerC := client.employer(t, "match-employer-c@example.test") + orgC := organizations.create(t, domain.User{ID: ownerC.id}, organizations.completeProfile(t, "Match organization C"), now) + bounded := func(product *domain.ProductPolicy) { + product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 + } + publishPolicy(bounded) + searchC := func() (matchSearchBody, string) { + result, response := search(ownerC, orgC.ID(), `{"filters":{}}`) + if response.Code != http.StatusOK { + t.Fatalf("search of organization C = %d %s", response.Code, response.Body.String()) + } + return result, response.Body.String() + } + first, firstBody := searchC() + returned := len(first.Groups.Main) + len(first.Groups.Near) + len(first.Groups.Unconfirmed) + if !first.Truncated || len(first.Groups.Main) != 8 || returned != 8 || revealedBy(orgC.ID()) != 8 { + t.Fatalf("first search = %d main, %d near, %d unconfirmed, truncated %v, paid %d; want eight confirmed entries, the flag, and eight paid", + len(first.Groups.Main), len(first.Groups.Near), len(first.Groups.Unconfirmed), first.Truncated, revealedBy(orgC.ID())) + } + for _, forbidden := range []string{"total", "count", "remaining", "quota"} { + if strings.Contains(firstBody, forbidden) { + t.Fatalf("a truncated result exposes %q: %s", forbidden, firstBody) + } + } + assertOrder(t, orgC.ID(), first.Groups.Main, true) + // The same search again returns the same entries and charges nothing. + if _, secondBody := searchC(); secondBody != firstBody || revealedBy(orgC.ID()) != 8 { + t.Fatal("a repeated search of an exhausted organization changed or charged") + } + // Each returned candidate has the card view in the history, and opening + // the card of a returned handle is free, while the ninth candidate's card + // is refused by the same allowance. + candidates := candidateOfHandle(orgC.ID()) + for _, entry := range first.Groups.Main { + if len(historyOf(candidates[entry.CandidateHandle], orgC.ID())) < 2 { + t.Fatalf("a returned candidate has %d card views from organization C, want one for each search", + len(historyOf(candidates[entry.CandidateHandle], orgC.ID()))) + } + } + cardPath := func(handle string) string { + return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", orgC.ID(), handle) + } + if got := harness.request(t, http.MethodGet, cardPath(first.Groups.Main[0].CandidateHandle), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusOK || + revealedBy(orgC.ID()) != 8 { + t.Fatalf("card of a paid candidate = %d, paid %d, want 200 and no new charge", got.Code, revealedBy(orgC.ID())) + } + unpaid := "" + for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { + for _, member := range group { + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgC.ID(), member.id) == 0 { + unpaid = aliasIn(orgC.ID(), member.id) + } + } + } + if got := harness.request(t, http.MethodGet, cardPath(unpaid), "", "", ownerC.cookie, "", client.remote()); got.Code != http.StatusTooManyRequests { + t.Fatalf("card of an unpaid candidate = %d, want 429 from the same allowance", got.Code) + } + // The organizations pay independently of each other. + if revealedBy(orgA.ID()) < 16 || revealedBy(orgB.ID()) != 16 { + t.Fatalf("paid by A and B = %d and %d, want the counts of earlier searches untouched", revealedBy(orgA.ID()), revealedBy(orgB.ID())) + } + + // The group limit cuts the output of an organization that still has + // allowance, ranks the whole bank first, and also raises the flag. + publishPolicy(func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = 4 }) + paidBefore := revealedBy(orgA.ID()) + cut := mustSearch(orgA.ID(), `{"filters":{}}`) + if len(cut.Groups.Main) != 4 || len(cut.Groups.Unconfirmed) != 4 || !cut.Truncated { + t.Fatalf("limited search = %d main, %d unconfirmed, truncated %v, want both groups cut at four and the flag", + len(cut.Groups.Main), len(cut.Groups.Unconfirmed), cut.Truncated) + } + if revealedBy(orgA.ID()) != paidBefore { + t.Fatal("a limited search charged candidates that were already paid for") + } + // The head of the cut group is the head of the full ranking. + publishPolicy(nil) + full := mustSearch(orgA.ID(), `{"filters":{}}`) + if full.Truncated || !slices.Equal(handlesOf(cut.Groups.Main), handlesOf(full.Groups.Main[:4])) || + !slices.Equal(handlesOf(cut.Groups.Unconfirmed), handlesOf(full.Groups.Unconfirmed[:4])) { + t.Fatal("the limited result is not the head of the full ranking") + } + }) + + t.Run("the demo group limit is 10, at most 30 reveals for a search, below the daily allowance", func(t *testing.T) { + demo := domain.DemoMatchingPolicy().MaxResultsPerGroup + if demo != 10 || 3*demo >= domain.DemoProductPolicyV4().OrganizationQuotas.TierE0.DistinctCardViewsPerWindow { + t.Fatalf("demo group limit = %d, want 10 and three groups under the E0 allowance", demo) + } + publishPolicy(func(product *domain.ProductPolicy) { product.Matching.MaxResultsPerGroup = demo }) + paid := revealedBy(orgA.ID()) + cut := mustSearch(orgA.ID(), `{"filters":{}}`) + if len(cut.Groups.Main) != 10 || len(cut.Groups.Unconfirmed) != 10 || !cut.Truncated || revealedBy(orgA.ID()) != paid { + t.Fatalf("demo-limited search = %d main, %d unconfirmed, truncated %v, paid %d (was %d); want both groups at 10 and the flag", + len(cut.Groups.Main), len(cut.Groups.Unconfirmed), cut.Truncated, revealedBy(orgA.ID()), paid) + } + publishPolicy(nil) + }) + + t.Run("two concurrent searches of one organization never charge beyond the allowance", func(t *testing.T) { + ownerD := client.employer(t, "match-employer-d@example.test") + orgD := organizations.create(t, domain.User{ID: ownerD.id}, organizations.completeProfile(t, "Match organization D"), now) + publishPolicy(func(product *domain.ProductPolicy) { product.OrganizationQuotas.TierE0.DistinctCardViewsPerWindow = 8 }) + type outcome struct { + status int + body string + } + const parallel = 4 + outcomes := make(chan outcome, parallel) + remotes := make([]string, parallel) + for index := range remotes { + remotes[index] = client.remote() + } + var group sync.WaitGroup + for _, remote := range remotes { + group.Add(1) + go func() { + defer group.Done() + response := harness.request(t, http.MethodPost, searchPath(orgD.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerD.cookie, ownerD.csrf, remote) + outcomes <- outcome{status: response.Code, body: response.Body.String()} + }() + } + group.Wait() + close(outcomes) + var bodies []string + for result := range outcomes { + if result.status != http.StatusOK { + t.Fatalf("concurrent search = %d %s, want 200; log: %s", result.status, result.body, harness.logs.String()) + } + bodies = append(bodies, result.body) + } + if got := revealedBy(orgD.ID()); got != 8 { + t.Fatalf("organization D paid for %d candidates under concurrent searches, want exactly 8", got) + } + paid := make(map[string]bool) + for id := range candidateIDs { + if countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE organization_id = $1 AND candidate_id = $2`, orgD.ID(), id) == 1 { + paid[aliasIn(orgD.ID(), id)] = true + } + } + for _, body := range bodies { + var decoded matchSearchBody + if err := json.Unmarshal([]byte(body), &decoded); err != nil { + t.Fatalf("decode concurrent result: %v", err) + } + if !decoded.Truncated || len(decoded.Groups.Main) != 8 || len(decoded.Groups.Near)+len(decoded.Groups.Unconfirmed) != 0 { + t.Fatalf("concurrent result = %d main, truncated %v, want eight paid entries and the flag", len(decoded.Groups.Main), decoded.Truncated) + } + for _, handle := range handlesOf(decoded.Groups.Main) { + if !paid[handle] { + t.Fatalf("a response holds %s, a candidate the organization did not pay for", handle) + } + } + } + for _, body := range bodies[1:] { + if body != bodies[0] { + t.Fatal("two concurrent searches of one organization answered differently") + } + } + publishPolicy(nil) + }) + + t.Run("concurrent card reads, evidence reads, and searches of one organization neither deadlock nor overcharge", func(t *testing.T) { + ownerF := client.employer(t, "match-employer-f@example.test") + orgF := organizations.create(t, domain.User{ID: ownerF.id}, organizations.completeProfile(t, "Match organization F"), now) + visible := make([]categoryHTTPCandidate, 0, 17) + for _, group := range [][]categoryHTTPCandidate{withGo, withoutStack, declaredOnly} { + visible = append(visible, group...) + } + type outcome struct { + what string + status int + } + run := func(jobs []func() outcome) []outcome { + results := make(chan outcome, len(jobs)) + var group sync.WaitGroup + for _, job := range jobs { + group.Add(1) + go func() { + defer group.Done() + results <- job() + }() + } + group.Wait() + close(results) + var all []outcome + for result := range results { + all = append(all, result) + } + return all + } + card := func(member categoryHTTPCandidate, suffix string) func() outcome { + remote := client.remote() + path := fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s%s", orgF.ID(), aliasIn(orgF.ID(), member.id), suffix) + return func() outcome { + response := harness.request(t, http.MethodGet, path, "", "", ownerF.cookie, "", remote) + return outcome{what: "card" + suffix, status: response.Code} + } + } + searchJob := func() func() outcome { + remote := client.remote() + return func() outcome { + response := harness.request(t, http.MethodPost, searchPath(orgF.ID()), `{"filters":{}}`, sessionHTTPTestOrigin, ownerF.cookie, ownerF.csrf, remote) + return outcome{what: "search", status: response.Code} + } + } + check := func(results []outcome) { + t.Helper() + for _, result := range results { + if result.status != http.StatusOK { + t.Fatalf("concurrent %s = %d, want 200; log: %s", result.what, result.status, harness.logs.String()) + } + } + if strings.Contains(harness.logs.String(), "40P01") { + t.Fatal("a concurrent read of one organization hit a deadlock") + } + } + + // Several card reads of one organization at once. + var jobs []func() outcome + for _, member := range visible[:6] { + jobs = append(jobs, card(member, "")) + } + check(run(jobs)) + if got := revealedBy(orgF.ID()); got != 6 { + t.Fatalf("six concurrent card reads charged %d candidates, want 6", got) + } + + // A mixed round: searches, card reads, and evidence reads together. + jobs = []func() outcome{searchJob(), searchJob()} + for _, member := range visible[3:9] { + jobs = append(jobs, card(member, ""), card(member, "/evidence")) + } + check(run(jobs)) + if got := revealedBy(orgF.ID()); got != len(visible) { + t.Fatalf("the mixed round charged %d candidates, want %d: one row for each visible candidate and no more", got, len(visible)) + } + if countRows(`SELECT count(*) FROM (SELECT candidate_id FROM company_card_view_quota_usage WHERE organization_id = $1 + GROUP BY candidate_id HAVING count(*) > 1) AS repeated`, orgF.ID()) != 0 { + t.Fatal("a candidate was charged twice") + } + }) + + t.Run("the skill taxonomy is part of the policy version", func(t *testing.T) { + request := needRequest(needID, needRequirementsV1, "") + withTaxonomy := mustSearch(orgA.ID(), request) + publishPolicy(func(product *domain.ProductPolicy) { product.Matching.SkillTaxonomy = nil }) + without := mustSearch(orgA.ID(), request) + if len(withTaxonomy.Groups.Near) != 5 || len(without.Groups.Near) != 5 { + t.Fatalf("near = %d and %d, want the five candidates without the tag in both", len(withTaxonomy.Groups.Near), len(without.Groups.Near)) + } + assertScores(t, "near with the taxonomy", withTaxonomy.Groups.Near, map[string]float64{"coverage": 0.24}) + assertScores(t, "near without the taxonomy", without.Groups.Near, map[string]float64{"coverage": 0}) + assertScores(t, "main without the taxonomy", without.Groups.Main, map[string]float64{"coverage": 0.25}) + publishPolicy(nil) + }) + + t.Run("a policy without the matching section fails closed", func(t *testing.T) { + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + if _, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: policyTestAuthor, Policy: domain.DemoProductPolicyV3(), + }); err != nil { + t.Fatalf("Publish(policy without matching) error = %v", err) + } + clockOffset += time.Minute + harness.clock.Set(time.Now().UTC().Add(clockOffset).Truncate(time.Microsecond)) + if _, response := search(employer, orgA.ID(), `{"filters":{}}`); response.Code != http.StatusInternalServerError { + t.Fatalf("search under a policy without matching = %d %s, want 500 and no ranking from defaults", response.Code, response.Body.String()) + } + }) +} diff --git a/backend/integration_test/need_http_test.go b/backend/integration_test/need_http_test.go new file mode 100644 index 0000000..760d812 --- /dev/null +++ b/backend/integration_test/need_http_test.go @@ -0,0 +1,446 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + needusecase "lincodex/backend/internal/usecase/need" + "lincodex/backend/internal/usecase/organization" +) + +func TestOrganizationNeedOwnerWorkflowOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout) + defer cancel() + harness := newNeedHTTPHarness(ctx, t, env) + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + owner := createOrganizationHTTPUser(ctx, t, harness, "need-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreign := createOrganizationHTTPUser(ctx, t, harness, "need-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) + recruiter := createOrganizationHTTPUser(ctx, t, harness, "need-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidate := createOrganizationHTTPUser(ctx, t, harness, "need-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + unverified := createOrganizationHTTPUser(ctx, t, harness, "need-unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) + recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass, + env.Config.AppPublicURL, "", "192.0.2.44:1234") + requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified") + + organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "need-http-company") + insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now) + basePath := "/api/v1/organizations/" + organizationID.String() + "/needs" + initialSource := `{"title":"Payments backend","source_text":"Ищем бэкенд-разработчика в команду платежей. Обязательно: Go, PostgreSQL и Temporal. Желательно опыт с Kafka. Задачи: развивать сервис выплат и переводить его на событийную модель. Работа удаленно."}` + createdResponses := parallelNeedRequests(t, harness, http.MethodPost, basePath, initialSource, + env.Config.AppPublicURL, ownerSession, "need-http-create-1", 2) + if createdResponses[0].Code != http.StatusCreated || createdResponses[1].Code != http.StatusCreated || + createdResponses[0].Header().Get("Cache-Control") != "no-store" || string(createdResponses[0].Body.Bytes()) != string(createdResponses[1].Body.Bytes()) { + t.Fatalf("concurrent need create responses = %d %s and %d %s, want the same 201 response", + createdResponses[0].Code, createdResponses[0].Body.String(), createdResponses[1].Code, createdResponses[1].Body.String()) + } + originalBody := append([]byte(nil), createdResponses[0].Body.Bytes()...) + created := decodeNeedHTTPResponse(t, originalBody) + if created.ID == uuid.Nil || created.Version != 1 || created.RequirementsVersion != 1 || created.Recommendations.Status != string(domain.NeedRecommendationsNotAvailable) { + t.Fatalf("created need identity or recommendation state = %+v", created) + } + if created.Requirements.Specialization.Status != string(domain.NeedValueExtracted) || + created.Requirements.Specialization.Source == nil || created.Requirements.Specialization.Source.Origin != string(domain.NeedValueExtractedFromText) || + created.Requirements.Grade.Status != string(domain.NeedValueUnknown) || created.Requirements.Grade.Value != nil { + t.Fatalf("source extraction invented or omitted a need value: %+v", created.Requirements) + } + gotSkills := make([]string, 0, len(created.Requirements.RequiredSkills)) + for _, skill := range created.Requirements.RequiredSkills { + if skill.Status == string(domain.NeedItemExtracted) && skill.Source.Origin == string(domain.NeedValueExtractedFromText) { + gotSkills = append(gotSkills, skill.Name) + } + } + if !equalNeedStrings(gotSkills, []string{"Go", "PostgreSQL", "Temporal"}) { + t.Fatalf("extracted required skills = %v, want Go, PostgreSQL, Temporal", gotSkills) + } + if len(created.Readiness.MissingFields) == 0 { + t.Fatal("incomplete source text need has no readiness questions") + } + needPath := basePath + "/" + created.ID.String() + + changedKeyBody := `{"title":"Different request"}` + changedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, changedKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-create-1") + requireSessionProblem(t, changedKey, http.StatusUnprocessableEntity, "idempotency_key_reused") + + invalidNUL := organizationHTTPRequest(t, harness, http.MethodPost, basePath, + `{"title":"Bad\u0000title"}`, env.Config.AppPublicURL, ownerSession, "need-http-invalid-nul") + requireSessionProblem(t, invalidNUL, http.StatusBadRequest, "validation_failed") + var invalidProblem struct { + Errors []struct { + Pointer string `json:"pointer"` + } `json:"errors"` + } + if err := json.Unmarshal(invalidNUL.Body.Bytes(), &invalidProblem); err != nil || len(invalidProblem.Errors) == 0 { + t.Fatalf("NUL validation body = %s, decode error %v", invalidNUL.Body.String(), err) + } + updated := organizationHTTPRequest(t, harness, http.MethodPatch, needPath, + `{"expected_version":1,"required_skills":[{"name":"Go","status":"confirmed"}]}`, + env.Config.AppPublicURL, ownerSession, "") + if updated.Code != http.StatusOK { + t.Fatalf("confirm extracted skill = %d %s, want 200", updated.Code, updated.Body.String()) + } + confirmed := decodeNeedHTTPResponse(t, updated.Body.Bytes()) + if confirmed.Version != 2 || confirmed.RequirementsVersion != 2 || confirmed.Recommendations.Status != string(domain.NeedRecommendationsPending) || + len(confirmed.Requirements.RequiredSkills) != 1 || confirmed.Requirements.RequiredSkills[0].Name != "Go" || + confirmed.Requirements.RequiredSkills[0].Status != string(domain.NeedItemConfirmed) { + t.Fatalf("confirmed need state = %+v", confirmed) + } + currentRead := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", ownerSession, "") + if currentRead.Code != http.StatusOK || string(currentRead.Body.Bytes()) == string(originalBody) { + t.Fatalf("current need read = %d %s, want edited current version", currentRead.Code, currentRead.Body.String()) + } + immutableReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, initialSource, + env.Config.AppPublicURL, ownerSession, "need-http-create-1") + if immutableReplay.Code != http.StatusCreated || string(immutableReplay.Body.Bytes()) != string(originalBody) { + t.Fatalf("live create replay = %d %s, want the original 201 body %s", immutableReplay.Code, immutableReplay.Body.String(), originalBody) + } + + expiryKeyBody := `{"title":"Boundary need"}` + expiryKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary") + if expiryKey.Code != http.StatusCreated { + t.Fatalf("create need for expiry boundary = %d %s, want 201", expiryKey.Code, expiryKey.Body.String()) + } + expiryOriginal := decodeNeedHTTPResponse(t, expiryKey.Body.Bytes()) + boundary := harness.clock.Now() + expired, err := harness.pool.Exec(ctx, + `UPDATE idempotency_records AS record + SET created_at = $1, expires_at = $2 + WHERE EXISTS ( + SELECT 1 FROM organization_need_creation_results AS result + WHERE result.scope_hash = record.scope_hash + AND result.snapshot #>> '{need,title}' = 'Boundary need' + )`, + boundary.Add(-outbound.IdempotencyRetention), boundary) + if err != nil { + t.Fatalf("expire need create key at exact 24-hour boundary: %v", err) + } + if expired.RowsAffected() != 1 { + t.Fatalf("expired need create rows = %d, want 1", expired.RowsAffected()) + } + reusedKey := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary") + if reusedKey.Code != http.StatusCreated { + t.Fatalf("create after exact 24-hour replay boundary = %d %s, want a new 201", reusedKey.Code, reusedKey.Body.String()) + } + replacement := decodeNeedHTTPResponse(t, reusedKey.Body.Bytes()) + if replacement.ID == expiryOriginal.ID || replacement.Version != 1 { + t.Fatalf("expired key reused old need snapshot: %+v", replacement) + } + expiredReplay := organizationHTTPRequest(t, harness, http.MethodPost, basePath, expiryKeyBody, + env.Config.AppPublicURL, ownerSession, "need-http-expiry-boundary") + if expiredReplay.Code != http.StatusCreated || string(expiredReplay.Body.Bytes()) != string(reusedKey.Body.Bytes()) { + t.Fatalf("replay after expired-key reuse = %d %s, want exact replacement response %s", expiredReplay.Code, expiredReplay.Body.String(), reusedKey.Body.String()) + } + + identicalUpdates := parallelNeedRequests(t, harness, http.MethodPatch, needPath, + `{"expected_version":2,"title":"Platform engineer"}`, env.Config.AppPublicURL, ownerSession, "", 2) + for index, response := range identicalUpdates { + if response.Code != http.StatusOK { + t.Fatalf("identical concurrent update %d = %d %s, want 200", index, response.Code, response.Body.String()) + } + } + concurrentCurrent := decodeNeedHTTPResponse(t, identicalUpdates[0].Body.Bytes()) + if concurrentCurrent.Version != 3 || concurrentCurrent.Title != "Platform engineer" { + t.Fatalf("identical concurrent update result = version %d title %q, want version 3", concurrentCurrent.Version, concurrentCurrent.Title) + } + differentUpdates := parallelNeedRequestsWithBodies(t, harness, http.MethodPatch, needPath, + []string{`{"expected_version":3,"title":"Payments platform"}`, `{"expected_version":3,"title":"Cloud platform"}`}, + env.Config.AppPublicURL, ownerSession) + var winner needHTTPResponse + successes := 0 + conflicts := 0 + for index, response := range differentUpdates { + switch response.Code { + case http.StatusOK: + successes++ + winner = decodeNeedHTTPResponse(t, response.Body.Bytes()) + case http.StatusPreconditionFailed: + conflicts++ + default: + t.Fatalf("different concurrent update %d = %d %s, want 200 or 412", index, response.Code, response.Body.String()) + } + } + if successes != 1 || conflicts != 1 || winner.Version != 4 { + t.Fatalf("different concurrent updates had %d successes and %d conflicts; winner = %+v, want one version 4 success", successes, conflicts, winner) + } + + staleNoOp := organizationHTTPRequest(t, harness, http.MethodPatch, needPath, + fmt.Sprintf(`{"expected_version":3,"title":%q}`, winner.Title), env.Config.AppPublicURL, ownerSession, "") + if staleNoOp.Code != http.StatusOK || decodeNeedHTTPResponse(t, staleNoOp.Body.Bytes()).Version != 4 { + t.Fatalf("stale no-op update = %d %s, want current version 4", staleNoOp.Code, staleNoOp.Body.String()) + } + staleInvalid := organizationHTTPRequest(t, harness, http.MethodPatch, needPath, + `{"expected_version":3,"required_skills":[{"name":"Go","status":"confirmed"},{"name":"go","status":"confirmed"}]}`, + env.Config.AppPublicURL, ownerSession, "") + requireSessionProblem(t, staleInvalid, http.StatusPreconditionFailed, "version_conflict") + + secondNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Second need"}`, + env.Config.AppPublicURL, ownerSession, "need-http-create-2") + thirdNeed := organizationHTTPRequest(t, harness, http.MethodPost, basePath, `{"title":"Third need"}`, + env.Config.AppPublicURL, ownerSession, "need-http-create-3") + if secondNeed.Code != http.StatusCreated || thirdNeed.Code != http.StatusCreated { + t.Fatalf("create needs for pagination = %d %s and %d %s, want 201", secondNeed.Code, secondNeed.Body.String(), thirdNeed.Code, thirdNeed.Body.String()) + } + firstPage := readNeedHTTPPage(t, harness, ownerSession, basePath+"?limit=1") + if len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" { + t.Fatalf("first need page = %+v, want one item and cursor", firstPage) + } + secondPage := readNeedHTTPPage(t, harness, ownerSession, + basePath+"?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) + if len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil || + firstPage.Items[0].ID == secondPage.Items[0].ID { + t.Fatalf("second need page = %+v, want the next distinct item", secondPage) + } + + for _, test := range []struct { + name string + session organizationHTTPSession + want int + }{ + {name: "foreign owner", session: foreignSession, want: http.StatusNotFound}, + {name: "active recruiter", session: recruiterSession, want: http.StatusForbidden}, + {name: "candidate", session: candidateSession, want: http.StatusForbidden}, + } { + t.Run(test.name, func(t *testing.T) { + response := organizationHTTPRequest(t, harness, http.MethodGet, needPath, "", "", test.session, "") + if response.Code != test.want { + t.Fatalf("need read = %d %s, want %d", response.Code, response.Body.String(), test.want) + } + if strings.Contains(response.Body.String(), "Payments backend") || strings.Contains(response.Body.String(), "PostgreSQL") { + t.Fatalf("denied response contains need data: %s", response.Body.String()) + } + }) + } + var versionCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2", organizationID, created.ID).Scan(&versionCount); err != nil { + t.Fatalf("read immutable need history: %v", err) + } + if versionCount != 4 { + t.Fatalf("need history rows = %d, want 4", versionCount) + } +} + +type needHTTPResponse struct { + ID uuid.UUID `json:"id"` + Title string `json:"title"` + Version int64 `json:"version"` + RequirementsVersion int64 `json:"requirements_version"` + Requirements struct { + Specialization struct { + Status string `json:"status"` + Value *string `json:"value"` + Source *struct { + Origin string `json:"origin"` + } `json:"source"` + } `json:"specialization"` + Grade struct { + Status string `json:"status"` + Value *string `json:"value"` + } `json:"grade"` + RequiredSkills []struct { + Name string `json:"name"` + Status string `json:"status"` + Source struct { + Origin string `json:"origin"` + } `json:"source"` + } `json:"required_skills"` + } `json:"requirements"` + Readiness struct { + MissingFields []json.RawMessage `json:"missing_fields"` + } `json:"readiness"` + Recommendations struct { + Status string `json:"status"` + } `json:"recommendations"` +} + +func decodeNeedHTTPResponse(t *testing.T, encoded []byte) needHTTPResponse { + t.Helper() + var response needHTTPResponse + if err := json.Unmarshal(encoded, &response); err != nil { + t.Fatalf("decode need response: %v", err) + } + return response +} + +func equalNeedStrings(left, right []string) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + +type needHTTPPage struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +func readNeedHTTPPage(t *testing.T, harness *sessionHTTPHarness, session organizationHTTPSession, path string) needHTTPPage { + t.Helper() + response := organizationHTTPRequest(t, harness, http.MethodGet, path, "", "", session, "") + if response.Code != http.StatusOK { + t.Fatalf("list organization needs = %d %s, want 200", response.Code, response.Body.String()) + } + var page needHTTPPage + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode need list response: %v", err) + } + return page +} + +func parallelNeedRequests( + t *testing.T, + harness *sessionHTTPHarness, + method, path, body, origin string, + session organizationHTTPSession, + idempotencyKey string, + count int, +) []*httptest.ResponseRecorder { + t.Helper() + responses := make([]*httptest.ResponseRecorder, count) + var group sync.WaitGroup + start := make(chan struct{}) + for index := range count { + group.Go(func() { + <-start + responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, idempotencyKey) + }) + } + close(start) + group.Wait() + return responses +} + +func parallelNeedRequestsWithBodies( + t *testing.T, + harness *sessionHTTPHarness, + method, path string, + bodies []string, + origin string, + session organizationHTTPSession, +) []*httptest.ResponseRecorder { + t.Helper() + responses := make([]*httptest.ResponseRecorder, len(bodies)) + var group sync.WaitGroup + start := make(chan struct{}) + for index, body := range bodies { + group.Go(func() { + <-start + responses[index] = organizationHTTPRequest(t, harness, method, path, body, origin, session, "") + }) + } + close(start) + group.Wait() + return responses +} + +func newNeedHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), + Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + needService, err := needusecase.NewService(needusecase.Dependencies{ + Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("need.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(io.Discard, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessionService), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + needHandler := v1.NewNeedHandler(needService) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), v1.WithNeed(needHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func needHTTPPath(organizationID, needID uuid.UUID) string { + return fmt.Sprintf("/api/v1/organizations/%s/needs/%s", organizationID, needID) +} diff --git a/backend/integration_test/needs_test.go b/backend/integration_test/needs_test.go new file mode 100644 index 0000000..922b9e6 --- /dev/null +++ b/backend/integration_test/needs_test.go @@ -0,0 +1,589 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func TestOrganizationNeedsStorage(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + fixture := organizationFixture{ + ctx: ctx, + pool: pool, + identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, + transactor: postgresadapter.NewTransactor(pool), + now: now, + } + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("creates current and immutable historical snapshots within organization scope", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Поиск"), now) + otherOrganization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Другая компания"), now.Add(time.Minute)) + created := newIntegrationNeed(t, organization.ID(), "Разработчик", now.Add(2*time.Minute)) + fixture.createNeed(t, created) + + initial, err := fixture.getNeed(organization.ID(), created.ID()) + if err != nil || initial.Version() != 1 || initial.RequirementsVersion() != 1 || + initial.Readiness().Status != domain.NeedReadinessIncomplete { + t.Fatalf("Get(initial need) = version %d requirements %d error %v, want incomplete version 1", initial.Version(), initial.RequirementsVersion(), err) + } + + proposal := initial.Snapshot() + proposal.Title = "Backend developer" + proposal.UpdatedAt = now.Add(3 * time.Minute) + titleOnly, changed, err := initial.Revise(1, proposal) + if err != nil || !changed { + t.Fatalf("Revise(title) = changed %v error %v, want a saved change", changed, err) + } + fixture.saveNeed(t, organization.ID(), created.ID(), 1, titleOnly) + + proposal = titleOnly.Snapshot() + proposal.Requirements.Specialization = domain.NeedValue[domain.SpecializationCode]{ + Status: domain.NeedValueConfirmed, + Value: needIntegrationPointer(domain.SpecializationBackend), + Source: &domain.NeedValueSource{Origin: domain.NeedValueManual}, + } + proposal.UpdatedAt = now.Add(4 * time.Minute) + confirmed, changed, err := titleOnly.Revise(2, proposal) + if err != nil || !changed || confirmed.RequirementsVersion() != 3 { + t.Fatalf("Revise(confirmed specialization) = requirements %d changed %v error %v, want requirements version 3", confirmed.RequirementsVersion(), changed, err) + } + fixture.saveNeed(t, organization.ID(), created.ID(), 2, confirmed) + + current, err := fixture.getNeed(organization.ID(), created.ID()) + if err != nil || current.Version() != 3 || current.RequirementsVersion() != 3 || current.Snapshot().Title != "Backend developer" { + t.Fatalf("Get(current need) = version %d requirements %d title %q error %v", current.Version(), current.RequirementsVersion(), current.Snapshot().Title, err) + } + first, err := fixture.getNeedVersion(organization.ID(), created.ID(), 1) + if err != nil || first.Snapshot().Title != "Разработчик" || first.RequirementsVersion() != 1 { + t.Fatalf("GetVersion(1) = title %q requirements %d error %v", first.Snapshot().Title, first.RequirementsVersion(), err) + } + second, err := fixture.getNeedVersion(organization.ID(), created.ID(), 2) + if err != nil || second.Snapshot().Title != "Backend developer" || second.RequirementsVersion() != 1 { + t.Fatalf("GetVersion(2) = title %q requirements %d error %v", second.Snapshot().Title, second.RequirementsVersion(), err) + } + if _, err := fixture.getNeed(otherOrganization.ID(), created.ID()); !errors.Is(err, outbound.ErrNeedNotFound) { + t.Fatalf("Get from another organization error = %v, want ErrNeedNotFound", err) + } + if _, err := fixture.getNeedVersion(otherOrganization.ID(), created.ID(), 1); !errors.Is(err, outbound.ErrNeedNotFound) { + t.Fatalf("GetVersion from another organization error = %v, want ErrNeedNotFound", err) + } + if _, err := fixture.getNeedVersion(organization.ID(), created.ID(), 4); !errors.Is(err, outbound.ErrNeedNotFound) { + t.Fatalf("GetVersion(missing version) error = %v, want ErrNeedNotFound", err) + } + if err := fixture.createNeedError(created); !errors.Is(err, outbound.ErrNeedAlreadyExists) { + t.Fatalf("Create(duplicate ID) error = %v, want ErrNeedAlreadyExists", err) + } + }) + + t.Run("rejects nil scope and noninitial creation snapshots", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Первая версия"), now) + created := newIntegrationNeed(t, organization.ID(), "Черновик", now.Add(time.Minute)) + for _, scope := range []struct { + name string + organizationID uuid.UUID + needID uuid.UUID + }{ + {name: "organization", organizationID: uuid.Nil, needID: created.ID()}, + {name: "need", organizationID: organization.ID(), needID: uuid.Nil}, + } { + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := integrationNeedRepositoryForTest(unit).Get(ctx, scope.organizationID, scope.needID) + return err + }) + if !errors.Is(err, domain.ErrInvalidNeed) { + t.Errorf("Get with nil %s ID error = %v, want ErrInvalidNeed", scope.name, err) + } + } + if err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return integrationNeedRepositoryForTest(unit).Create(ctx, domain.Need{}) + }); !errors.Is(err, domain.ErrInvalidNeed) { + t.Fatalf("Create(zero need) error = %v, want ErrInvalidNeed", err) + } + + laterSnapshot := created.Snapshot() + laterSnapshot.Version = 2 + later, err := domain.RestoreNeed(laterSnapshot) + if err != nil { + t.Fatalf("RestoreNeed(version 2) error = %v", err) + } + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return integrationNeedRepositoryForTest(unit).Create(ctx, later) + }) + if !errors.Is(err, domain.ErrInvalidNeed) { + t.Fatalf("Create(version 2) error = %v, want ErrInvalidNeed", err) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"organization_needs"}, 0) + assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 0) + }) + + t.Run("competing compare-and-swap updates have one winner", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Конкурент"), now) + created := newIntegrationNeed(t, organization.ID(), "Исходное название", now.Add(time.Minute)) + fixture.createNeed(t, created) + concurrent := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, 3)) + + ready := make(chan error, 2) + start := make(chan struct{}) + errs := make([]error, 2) + var group sync.WaitGroup + for index := range 2 { + group.Go(func() { + errs[index] = concurrent.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + repository := integrationNeedRepositoryForTest(unit) + current, err := repository.Get(ctx, organization.ID(), created.ID()) + if err != nil { + ready <- err + return err + } + proposal := current.Snapshot() + proposal.Title = fmt.Sprintf("Вариант %d", index+1) + proposal.UpdatedAt = now.Add(time.Duration(index+2) * time.Minute) + next, changed, err := current.Revise(1, proposal) + if err != nil { + ready <- err + return fmt.Errorf("prepare concurrent need: %w", err) + } + if !changed { + err := domain.ErrInvalidNeed + ready <- err + return fmt.Errorf("prepare concurrent need: %w", err) + } + ready <- nil + <-start + return repository.Save(ctx, organization.ID(), created.ID(), 1, next) + }) + }) + } + setupErrors := []error{<-ready, <-ready} + close(start) + group.Wait() + for _, err := range setupErrors { + if err != nil { + t.Fatalf("prepare concurrent need: %v", err) + } + } + + successes := 0 + conflicts := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrNeedVersionConflict): + conflicts++ + default: + t.Fatalf("concurrent update %d error = %v, want success or ErrNeedVersionConflict", index, err) + } + } + if successes != 1 || conflicts != 1 { + t.Fatalf("concurrent updates had %d successes and %d conflicts, want one each", successes, conflicts) + } + current, err := fixture.getNeed(organization.ID(), created.ID()) + if err != nil || current.Version() != 2 { + t.Fatalf("Get after concurrent updates = version %d, error %v, want version 2", current.Version(), err) + } + }) + + t.Run("create and save participate in caller rollback", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Откат"), now) + created := newIntegrationNeed(t, organization.ID(), "Новый профиль", now.Add(time.Minute)) + rollback := errors.New("roll back need write") + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := integrationNeedRepositoryForTest(unit).Create(ctx, created); err != nil { + return err + } + return rollback + }) + if !errors.Is(err, rollback) { + t.Fatalf("create transaction error = %v, want rollback sentinel", err) + } + if _, err := fixture.getNeed(organization.ID(), created.ID()); !errors.Is(err, outbound.ErrNeedNotFound) { + t.Fatalf("Get rolled-back need error = %v, want ErrNeedNotFound", err) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"organization_needs"}, 0) + assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 0) + + fixture.createNeed(t, created) + current, err := fixture.getNeed(organization.ID(), created.ID()) + if err != nil { + t.Fatalf("Get need before save rollback: %v", err) + } + proposal := current.Snapshot() + proposal.Title = "Не сохранять" + proposal.UpdatedAt = now.Add(2 * time.Minute) + next, changed, err := current.Revise(1, proposal) + if err != nil || !changed { + t.Fatalf("Revise before rollback = changed %t, error %v", changed, err) + } + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := integrationNeedRepositoryForTest(unit).Save(ctx, organization.ID(), created.ID(), 1, next); err != nil { + return err + } + return rollback + }) + if !errors.Is(err, rollback) { + t.Fatalf("save transaction error = %v, want rollback sentinel", err) + } + current, err = fixture.getNeed(organization.ID(), created.ID()) + if err != nil || current.Version() != 1 || current.Snapshot().Title != "Новый профиль" { + t.Fatalf("Get after rolled-back save = version %d title %q error %v", current.Version(), current.Snapshot().Title, err) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 1) + }) + + t.Run("database bounds snapshots and rejects update or deletion", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Версии"), now) + created := newIntegrationNeed(t, organization.ID(), "Неизменяемая версия", now.Add(time.Minute)) + fixture.createNeed(t, created) + + _, err := pool.Exec(ctx, `UPDATE organization_need_versions SET snapshot = snapshot WHERE organization_id = $1 AND need_id = $2 AND version = 1`, organization.ID(), created.ID()) + assertSQLError(t, "update immutable need snapshot", err, "23000", "organization_need_versions_immutable") + _, err = pool.Exec(ctx, `DELETE FROM organization_need_versions WHERE organization_id = $1 AND need_id = $2 AND version = 1`, organization.ID(), created.ID()) + assertSQLError(t, "delete immutable need snapshot", err, "23000", "organization_need_versions_immutable") + assertRowCount(ctx, t, pool, pgx.Identifier{"organization_need_versions"}, 1) + + padded := created.Snapshot() + encoded, err := json.Marshal(padded) + if err != nil { + t.Fatalf("marshal snapshot for storage-bound check: %v", err) + } + var body map[string]any + if err := json.Unmarshal(encoded, &body); err != nil { + t.Fatalf("decode snapshot for storage-bound check: %v", err) + } + insertRejectedSnapshot := func(id uuid.UUID, snapshot []byte, name string) { + t.Helper() + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin %s transaction: %v", name, err) + } + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + if _, err := tx.Exec(ctx, `INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at) VALUES ($1, $2, 1, 1, $3, $3)`, id, organization.ID(), now); err != nil { + t.Fatalf("insert parent for %s: %v", name, err) + } + _, err = tx.Exec(ctx, `INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot) VALUES ($1, $2, 1, $3::jsonb)`, organization.ID(), id, snapshot) + assertSQLError(t, name, err, organizationCheckViolation, "organization_need_versions_snapshot_shape") + } + + invalidTypeID := uuid.New() + body["id"] = invalidTypeID.String() + body["requirements_version"] = "1" + invalidRequirementsVersion, err := json.Marshal(body) + if err != nil { + t.Fatalf("encode snapshot with invalid requirements version type: %v", err) + } + insertRejectedSnapshot(invalidTypeID, invalidRequirementsVersion, "insert string requirements version") + + largeID := uuid.New() + body["id"] = largeID.String() + body["requirements_version"] = 1 + body["padding"] = strings.Repeat("x", domain.MaxNeedSnapshotStorageBytes+1) + oversized, err := json.Marshal(body) + if err != nil { + t.Fatalf("encode oversized storage snapshot: %v", err) + } + insertRejectedSnapshot(largeID, oversized, "insert oversized snapshot") + }) + + t.Run("maximum bounded need shape stays within JSONB representation headroom", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Большой профиль"), now) + maximum := maximumBoundedIntegrationNeed(t, organization.ID(), now.Add(time.Minute)) + compact, err := json.Marshal(maximum.Snapshot()) + if err != nil { + t.Fatalf("marshal maximum bounded need: %v", err) + } + if len(compact) > domain.MaxNeedSnapshotBytes { + t.Fatalf("maximum bounded need compact JSON = %d bytes, exceeds %d", len(compact), domain.MaxNeedSnapshotBytes) + } + if len(compact) < 64*1024 { + t.Fatalf("maximum bounded need compact JSON = %d bytes, want a substantial combined source and requirement payload", len(compact)) + } + fixture.createNeed(t, maximum) + var storedBytes int + if err := pool.QueryRow(ctx, ` + SELECT octet_length(snapshot::text) + FROM organization_need_versions + WHERE organization_id = $1 AND need_id = $2 AND version = 1 + `, organization.ID(), maximum.ID()).Scan(&storedBytes); err != nil { + t.Fatalf("measure maximum need JSONB text size: %v", err) + } + if storedBytes < len(compact) || storedBytes-len(compact) > domain.MaxNeedJSONBTextHeadroom || storedBytes > domain.MaxNeedSnapshotStorageBytes { + t.Fatalf("maximum need storage = %d bytes, compact=%d headroom=%d; want storage within the explicit JSONB margin", + storedBytes, len(compact), domain.MaxNeedJSONBTextHeadroom) + } + if _, err := fixture.getNeed(organization.ID(), maximum.ID()); err != nil { + t.Fatalf("restore maximum bounded need: %v", err) + } + }) +} + +// needCreationResultMigrationVersion is the migration that creates +// organization_need_creation_results. +const needCreationResultMigrationVersion = 26 + +func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations to rollback test database: %v", err) + } + // The preflight belongs to the migration that created the replay table, so + // the migrations added after it are rolled back first. The one organization + // below has its own holding, so their guarded rollbacks do not refuse. + pool := newPoolFor(ctx, t, databaseURL) + now := time.Now().UTC().Truncate(time.Microsecond) + fixture := organizationFixture{ + ctx: ctx, pool: pool, + identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, + transactor: postgresadapter.NewTransactor(pool), now: now, + } + // The organization is created while the latest schema is in place: its + // creation needs the holdings table, which the rollback below removes. + owner := fixture.employer(t, "need-migration-owner@example.test") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Миграция needs"), now) + rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion) + scope := []byte(strings.Repeat("s", outbound.IdempotencyDigestSize)) + fingerprint := []byte(strings.Repeat("f", outbound.IdempotencyDigestSize)) + if _, err := pool.Exec(ctx, ` + INSERT INTO idempotency_records (scope_hash, fingerprint, created_at, expires_at) + VALUES ($1, $2, $3, $4) + `, scope, fingerprint, now, now.Add(outbound.IdempotencyRetention)); err != nil { + t.Fatalf("insert live idempotency row: %v", err) + } + if _, err := pool.Exec(ctx, ` + INSERT INTO organization_need_creation_results (scope_hash, snapshot) + VALUES ($1, '{"need":{},"readiness":{},"recommendations":{}}'::jsonb) + `, scope); err != nil { + t.Fatalf("insert live creation result: %v", err) + } + if _, err := migrator.DownOne(ctx); err == nil { + t.Fatal("DownOne() succeeded while a need creation replay remained live") + } + assertNeedResultMigrationPresent(ctx, t, pool, 1) + + if _, err := pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2 WHERE scope_hash = $3", + now.Add(-outbound.IdempotencyRetention-time.Second), now.Add(-time.Second), scope); err != nil { + t.Fatalf("expire idempotency replay before checking historical bounds: %v", err) + } + need := newIntegrationNeed(t, organization.ID(), "Bounded rollback fixture", now.Add(time.Minute)) + encoded, err := json.Marshal(need.Snapshot()) + if err != nil { + t.Fatalf("marshal rollback snapshot: %v", err) + } + var body map[string]any + if err := json.Unmarshal(encoded, &body); err != nil { + t.Fatalf("decode rollback snapshot: %v", err) + } + body["rollback_bound_fixture"] = strings.Repeat("p", 265000) + encoded, err = json.Marshal(body) + if err != nil { + t.Fatalf("encode rollback-bound snapshot: %v", err) + } + var storageSize int + if err := pool.QueryRow(ctx, "SELECT octet_length($1::jsonb::text)", encoded).Scan(&storageSize); err != nil { + t.Fatalf("measure rollback-bound snapshot: %v", err) + } + if storageSize <= domain.MaxNeedSnapshotBytes || storageSize > domain.MaxNeedSnapshotStorageBytes { + t.Fatalf("rollback fixture JSONB size = %d, want (%d, %d]", storageSize, domain.MaxNeedSnapshotBytes, domain.MaxNeedSnapshotStorageBytes) + } + tx, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin oversized-history fixture transaction: %v", err) + } + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + if _, err := tx.Exec(ctx, ` + INSERT INTO organization_needs (id, organization_id, current_version, requirements_version, created_at, updated_at) + VALUES ($1, $2, 1, 1, $3, $3) + `, need.ID(), organization.ID(), now.Add(time.Minute)); err != nil { + t.Fatalf("insert oversized-history need parent: %v", err) + } + if _, err := tx.Exec(ctx, ` + INSERT INTO organization_need_versions (organization_id, need_id, version, snapshot) + VALUES ($1, $2, 1, $3::jsonb) + `, organization.ID(), need.ID(), encoded); err != nil { + t.Fatalf("insert snapshot within current storage bound: %v", err) + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit oversized-history fixture: %v", err) + } + if _, err := migrator.DownOne(ctx); err == nil { + t.Fatal("DownOne() succeeded while retained need history exceeded the prior bound") + } + assertNeedResultMigrationPresent(ctx, t, pool, 1) +} + +func assertNeedResultMigrationPresent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, resultRows int64) { + t.Helper() + var tableExists bool + var rows int64 + if err := pool.QueryRow(ctx, ` + SELECT to_regclass('organization_need_creation_results') IS NOT NULL, + (SELECT count(*) FROM organization_need_creation_results) + `).Scan(&tableExists, &rows); err != nil { + t.Fatalf("inspect migration preflight after rollback attempt: %v", err) + } + if !tableExists || rows != resultRows { + t.Fatalf("migration rollback changed state: result table exists=%t rows=%d, want true/%d", tableExists, rows, resultRows) + } +} + +func maximumBoundedIntegrationNeed(t *testing.T, organizationID uuid.UUID, at time.Time) domain.Need { + t.Helper() + quote := strings.Repeat("q", 300) + extractedVersion := int64(1) + extractor := "need-rules.2026-10.1" + source := domain.NeedValueSource{ + Origin: domain.NeedValueExtractedFromText, Quote: "e, + ExtractedInVersion: &extractedVersion, ExtractionVersion: &extractor, + } + makeSkills := func(prefix string) []domain.NeedSkill { + skills := make([]domain.NeedSkill, 0, 30) + for index := range 30 { + name := fmt.Sprintf("%s-%02d-%s", prefix, index, strings.Repeat("s", 80)) + skills = append(skills, domain.NeedSkill{Name: name, Status: domain.NeedItemExtracted, Source: source}) + } + return skills + } + tasks := make([]domain.NeedTask, 0, 20) + for index := range 20 { + prefix := fmt.Sprintf("task-%02d-", index) + tasks = append(tasks, domain.NeedTask{ + Text: prefix + strings.Repeat("t", 290-len(prefix)), Status: domain.NeedItemExtracted, Source: source, + }) + } + rejected := make([]domain.NeedRejectedSuggestion, 0, domain.MaxNeedRejectedSuggestions) + for index := range domain.MaxNeedRejectedSuggestions { + rejected = append(rejected, domain.NeedRejectedSuggestion{ + Field: domain.NeedRejectedSkills, Value: fmt.Sprintf("rejected-%02d-%s", index, strings.Repeat("r", 280)), + }) + } + manual := &domain.NeedValueSource{Origin: domain.NeedValueManual} + formats := []domain.NeedWorkFormat{domain.NeedWorkFormatRemote, domain.NeedWorkFormatOffice, domain.NeedWorkFormatHybrid} + grade := domain.GradeSenior + specialization := domain.SpecializationBackend + domainName := strings.Repeat("d", 100) + location := strings.Repeat("l", 100) + formatValue := formats + salary := domain.NeedSalaryRange{SalaryFrom: 100000, SalaryTo: 120000, Currency: "RUB", Period: "month", TaxBasis: "gross"} + requirements := domain.NeedRequirements{ + Specialization: domain.NeedValue[domain.SpecializationCode]{Status: domain.NeedValueConfirmed, Value: &specialization, Source: manual}, + Grade: domain.NeedValue[domain.GradeCode]{Status: domain.NeedValueConfirmed, Value: &grade, Source: manual}, + RequiredSkills: makeSkills("required"), DesiredSkills: makeSkills("desired"), Tasks: tasks, + Domain: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &domainName, Source: manual}, + WorkFormats: domain.NeedValue[[]domain.NeedWorkFormat]{Status: domain.NeedValueConfirmed, Value: &formatValue, Source: manual}, + Location: domain.NeedValue[string]{Status: domain.NeedValueConfirmed, Value: &location, Source: manual}, + Salary: domain.NeedValue[domain.NeedSalaryRange]{Status: domain.NeedValueConfirmed, Value: &salary, Source: manual}, + } + need, err := domain.NewNeed(domain.NeedSnapshot{ + ID: uuid.New(), OrganizationID: organizationID, Title: strings.Repeat("n", 200), SourceText: needIntegrationPointer(strings.Repeat("s", 10000)), + Version: 1, RequirementsVersion: 1, Requirements: requirements, RejectedSuggestions: rejected, + CreatedAt: at, UpdatedAt: at, + }) + if err != nil { + t.Fatalf("NewNeed(maximum bounded shape) error = %v", err) + } + return need +} + +func (fixture organizationFixture) createNeed(t *testing.T, need domain.Need) { + t.Helper() + if err := fixture.createNeedError(need); err != nil { + t.Fatalf("Create(need) error = %v", err) + } +} + +func (fixture organizationFixture) createNeedError(need domain.Need) error { + return fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return integrationNeedRepositoryForTest(unit).Create(ctx, need) + }) +} + +func (fixture organizationFixture) getNeed(organizationID, needID uuid.UUID) (domain.Need, error) { + var need domain.Need + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + need, err = integrationNeedRepositoryForTest(unit).Get(ctx, organizationID, needID) + return err + }) + return need, err +} + +func (fixture organizationFixture) getNeedVersion(organizationID, needID uuid.UUID, version int64) (domain.Need, error) { + var need domain.Need + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + need, err = integrationNeedRepositoryForTest(unit).GetVersion(ctx, organizationID, needID, version) + return err + }) + return need, err +} + +func (fixture organizationFixture) saveNeed(t *testing.T, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) { + t.Helper() + if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return integrationNeedRepositoryForTest(unit).Save(ctx, organizationID, needID, expectedVersion, next) + }); err != nil { + t.Fatalf("Save(need) error = %v", err) + } +} + +func integrationNeedRepositoryForTest(unit outbound.UnitOfWork) outbound.NeedRepository { + repositories, ok := unit.(outbound.NeedRepositories) + if !ok { + panic("unit of work does not expose need repositories") + } + return repositories.Needs() +} + +func newIntegrationNeed(t *testing.T, organizationID uuid.UUID, title string, at time.Time) domain.Need { + t.Helper() + need, err := domain.NewNeed(domain.NeedSnapshot{ + ID: uuid.New(), OrganizationID: organizationID, Title: title, Version: 1, RequirementsVersion: 1, + Requirements: domain.EmptyNeedRequirements(), CreatedAt: at, UpdatedAt: at, + }) + if err != nil { + t.Fatalf("NewNeed() error = %v", err) + } + return need +} + +func needIntegrationPointer[T any](value T) *T { return &value } diff --git a/backend/integration_test/notification_inbox_migration_test.go b/backend/integration_test/notification_inbox_migration_test.go new file mode 100644 index 0000000..d056835 --- /dev/null +++ b/backend/integration_test/notification_inbox_migration_test.go @@ -0,0 +1,137 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/google/uuid" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" +) + +const ( + // syntheticNotificationMigrationVersion adds the synthetic event type to + // the inbox allowlist. + syntheticNotificationMigrationVersion = 36 + checkViolation = "23514" + notificationTypeConstraint = "notification_inbox_events_type_known" +) + +func TestSyntheticNotificationMigrationAllowlistAndGuardedRollback(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + // The candidate and the organization are created while the latest schema is in + // place: their creation needs the holdings table, which the rollback removes. + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + candidate := identity.createUser(t, "inbox-migration@example.com", domain.ScenarioCandidate, now.Add(-time.Hour)) + organizations := organizationFixture{ + ctx: ctx, pool: pool, identity: identity, transactor: postgresadapter.NewTransactor(pool), now: now, + } + owner := organizations.employer(t, "inbox-migration-owner@example.com") + organization := organizations.create(t, owner, organizations.completeProfile(t, "Example Company"), now) + + rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion) + + insert := func(eventType, sourceType string, schemaVersion int) error { + _, err := pool.Exec(ctx, `INSERT INTO notification_inbox_events ( + recipient_user_id, event_id, organization_id, event_type, schema_version, source_type, source_id, occurred_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, + candidate.ID, uuid.New(), organization.ID(), eventType, schemaVersion, sourceType, organization.ID(), now) + return err + } + if err := insert("invitation.delivered", "invitation", 1); err != nil { + t.Fatalf("insert invitation event: %v", err) + } + if err := insert("notification.synthetic_delivered", "organization", 1); err != nil { + t.Fatalf("insert synthetic event: %v", err) + } + for name, args := range map[string][3]any{ + "synthetic event with the invitation source": {"notification.synthetic_delivered", "invitation", 1}, + "invitation event with the organization": {"invitation.delivered", "organization", 1}, + "unknown event type": {"notification.mail_requested", "organization", 1}, + "unsupported schema version": {"notification.synthetic_delivered", "organization", 2}, + } { + err := insert(args[0].(string), args[1].(string), args[2].(int)) + assertPgError(t, name, err, checkViolation, notificationTypeConstraint) + } + + // A rollback refuses to orphan a synthetic row and leaves the migration + // applied. + _, err := migrator.DownOne(ctx) + assertPgError(t, "DownOne() with a synthetic inbox event", err, privacyIntegrityViolation, notificationTypeConstraint) + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + for _, status := range statuses { + if status.Version == syntheticNotificationMigrationVersion && !status.Applied { + t.Fatal("the migration was rolled back despite a synthetic inbox event") + } + } +} + +func TestSyntheticNotificationMigrationRollsBackWithoutSyntheticRows(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + rollBackAboveVersion(ctx, t, migrator, syntheticNotificationMigrationVersion) + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != syntheticNotificationMigrationVersion { + t.Fatalf("DownOne() = %+v, %v, want version %d rolled back", result, err, syntheticNotificationMigrationVersion) + } + var constraint string + if err := pool.QueryRow(ctx, `SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname = $1`, notificationTypeConstraint).Scan(&constraint); err != nil { + t.Fatalf("read the restored constraint: %v", err) + } + if constraint != "CHECK (((event_type = 'invitation.delivered'::text) AND (schema_version = 1) AND (source_type = 'invitation'::text)))" { + t.Fatalf("restored constraint = %s, want the invitation-only allowlist", constraint) + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} + +// rollBackAboveVersion rolls back every migration newer than version, so a +// test of one migration keeps working when later migrations exist. +func rollBackAboveVersion(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, version int64) { + t.Helper() + for { + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() while preparing migration %d: %v", version, err) + } + latest := int64(0) + for _, status := range statuses { + if status.Applied && status.Version > latest { + latest = status.Version + } + } + if latest < version { + t.Fatalf("migration %d is not applied", version) + } + if latest == version { + return + } + if _, err := migrator.DownOne(ctx); err != nil { + t.Fatalf("DownOne() while preparing migration %d: %v", version, err) + } + } +} diff --git a/backend/integration_test/notification_inbox_test.go b/backend/integration_test/notification_inbox_test.go new file mode 100644 index 0000000..8dce141 --- /dev/null +++ b/backend/integration_test/notification_inbox_test.go @@ -0,0 +1,431 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/organization" +) + +const ( + notificationHTTPTimeout = 5 * time.Minute + notificationConsumerTTL = 10 * time.Second + // inboxRenamedConsumer stands for a consumer renamed after a deployment: + // its markers are empty, so only the inbox key can absorb the replay. + inboxRenamedConsumer = "notification_inbox_renamed" +) + +type notificationBody struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + OrganizationID uuid.UUID `json:"organization_id"` + DeliveredAt time.Time `json:"delivered_at"` + ReadAt *time.Time `json:"read_at"` + Content *struct { + Title string `json:"title"` + Summary string `json:"summary"` + LinkPath *string `json:"link_path"` + } `json:"content"` +} + +type notificationPageBody struct { + Items []notificationBody `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +func newNotificationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: transactor, Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + inbox, err := notification.NewInboxService(transactor, + notification.NewInboxContentResolver(notification.DefaultInboxSourceResolvers(true)), clock.Now) + if err != nil { + t.Fatalf("notification.NewInboxService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.DiscardHandler) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessionService), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), + v1.WithNotifications(v1.NewNotificationHandler(inbox)), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +// appendSyntheticNotice records a synthetic inbox event through the real +// outbox writer, as a producer does in its own transaction, and returns the +// envelope a consumer would receive for it. +func appendSyntheticNotice( + ctx context.Context, + t *testing.T, + transactor outbound.Transactor, + recipientID, organizationID uuid.UUID, + occurredAt time.Time, +) outbound.ConsumedEvent { + t.Helper() + payload, err := notification.SyntheticNoticeEventPayload(recipientID, organizationID) + if err != nil { + t.Fatalf("SyntheticNoticeEventPayload() error = %v", err) + } + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: string(domain.NotificationInboxSyntheticDelivered), SchemaVersion: 1, + AggregateType: notification.SyntheticNoticeAggregateType, AggregateID: uuid.New(), + AggregateVersion: notification.SyntheticNoticeAggregateVersion, Payload: payload, + }) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, event) + }) + if err != nil { + t.Fatalf("Append(synthetic notice) error = %v", err) + } + return outbound.ConsumedEvent{ + EventID: event.EventID(), EventType: event.EventType(), SchemaVersion: event.SchemaVersion(), + AggregateType: event.AggregateType(), AggregateID: event.AggregateID(), AggregateVersion: event.AggregateVersion(), + OccurredAt: occurredAt, Payload: event.Payload(), + } +} + +func deliverToInbox( + ctx context.Context, + t *testing.T, + store *postgresadapter.EventConsumerStore, + consumer string, + event outbound.ConsumedEvent, +) bool { + t.Helper() + handler := notification.NewInboxHandler(slog.New(slog.DiscardHandler), true) + applied, err := store.ApplyOnce(ctx, consumer, event.EventID, func(ctx context.Context, unit outbound.UnitOfWork) error { + return handler.Handle(ctx, unit, event) + }) + if err != nil { + t.Fatalf("ApplyOnce(%s, %s) error = %v", consumer, event.EventID, err) + } + return applied +} + +func notificationRequest( + t *testing.T, + harness *sessionHTTPHarness, + method, path, origin string, + session organizationHTTPSession, +) *httptest.ResponseRecorder { + t.Helper() + return organizationHTTPRequest(t, harness, method, path, "", origin, session, "") +} + +func decodeNotificationPage(t *testing.T, response *httptest.ResponseRecorder) notificationPageBody { + t.Helper() + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("notification list = %d %q %s, want a no-store 200", response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + var page notificationPageBody + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode notification page: %v", err) + } + return page +} + +func requireNotificationProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) { + t.Helper() + requireSessionProblem(t, response, status, code) +} + +func TestNotificationInboxOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), notificationHTTPTimeout) + defer cancel() + harness := newNotificationHTTPHarness(ctx, t, env) + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + transactor := postgresadapter.NewTransactor(harness.pool) + consumerStore := postgresadapter.NewEventConsumerStore(harness.pool, notificationConsumerTTL) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + candidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + otherCandidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-other-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + owner := createOrganizationHTTPUser(ctx, t, harness, "inbox-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreign := createOrganizationHTTPUser(ctx, t, harness, "inbox-foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) + recruiter := createOrganizationHTTPUser(ctx, t, harness, "inbox-recruiter@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + otherCandidateSession := loginOrganizationHTTP(t, harness, otherCandidate.Email.Address()) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) + recruiterSession := loginOrganizationHTTP(t, harness, recruiter.Email.Address()) + origin := env.Config.AppPublicURL + organizationID := createCompanyForContextTest(t, harness, origin, ownerSession, "inbox-company") + foreignOrganizationID := createCompanyForContextTest(t, harness, origin, foreignSession, "inbox-foreign-company") + var organizationName string + if err := harness.pool.QueryRow(ctx, `SELECT name FROM organizations WHERE id = $1`, organizationID).Scan(&organizationName); err != nil { + t.Fatalf("read organization name: %v", err) + } + + // One synthetic event delivered twice, and once more by a renamed + // consumer, stores exactly one row. + deliveredAt := now.Add(-time.Hour) + event := appendSyntheticNotice(ctx, t, transactor, candidate.ID, organizationID, deliveredAt) + if !deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, event) { + t.Fatal("the first delivery was reported as a duplicate") + } + if deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, event) { + t.Fatal("the second delivery of the same event ID was applied again") + } + deliverToInbox(ctx, t, consumerStore, inboxRenamedConsumer, event) + var rows int + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM notification_inbox_events WHERE event_id = $1`, event.EventID).Scan(&rows); err != nil || rows != 1 { + t.Fatalf("inbox rows for the repeated event = %d, %v, want 1", rows, err) + } + + list := func(session organizationHTTPSession) notificationPageBody { + t.Helper() + return decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", session)) + } + page := list(candidateSession) + if len(page.Items) != 1 || page.Page.HasMore || page.Page.NextCursor != nil { + t.Fatalf("candidate inbox = %+v, want one item on the last page", page) + } + item := page.Items[0] + if item.ID != event.EventID || item.Kind != "synthetic" || item.OrganizationID != organizationID || + item.ReadAt != nil || !item.DeliveredAt.Equal(deliveredAt.Truncate(time.Second)) { + t.Fatalf("candidate item = %+v, want the unread synthetic event", item) + } + if item.Content == nil || item.Content.Title != "Тестовое уведомление" || !strings.Contains(item.Content.Summary, organizationName) || + item.Content.LinkPath != nil { + t.Fatalf("candidate item content = %+v, want the current organization name", item.Content) + } + if got := list(otherCandidateSession); len(got.Items) != 0 { + t.Fatalf("another candidate's inbox = %+v, want empty", got) + } + + // Account and cabinet boundaries. + markPath := "/api/v1/me/notifications/" + event.EventID.String() + "/read" + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", organizationHTTPSession{}), http.StatusUnauthorized, "unauthenticated") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", ownerSession), http.StatusForbidden, "forbidden") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, ownerSession), http.StatusForbidden, "forbidden") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, otherCandidateSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, "/api/v1/me/notifications/"+uuid.NewString()+"/read", origin, candidateSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, "/api/v1/me/notifications/not-a-uuid/read", origin, candidateSession), http.StatusBadRequest, "validation_failed") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, "https://evil.example", candidateSession), http.StatusForbidden, "csrf_check_failed") + noCSRFSession := candidateSession + noCSRFSession.csrf = "" + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, markPath, origin, noCSRFSession), http.StatusForbidden, "csrf_check_failed") + if got := list(candidateSession); got.Items[0].ReadAt != nil { + t.Fatal("a refused request marked the item read") + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, + "/api/v1/organizations/"+organizationID.String()+"/notifications", "", candidateSession), http.StatusForbidden, "forbidden") + + // Mark read twice: the first time stays, and the list persists it. + first := notificationRequest(t, harness, http.MethodPost, markPath, origin, candidateSession) + var receipt struct { + ID uuid.UUID `json:"id"` + ReadAt time.Time `json:"read_at"` + } + if first.Code != http.StatusOK || first.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("mark read = %d %s, want a no-store 200", first.Code, first.Body.String()) + } + if err := json.Unmarshal(first.Body.Bytes(), &receipt); err != nil || receipt.ID != event.EventID || receipt.ReadAt.IsZero() { + t.Fatalf("mark read receipt = %s, %v", first.Body.String(), err) + } + harness.clock.Advance(time.Hour) + again := notificationRequest(t, harness, http.MethodPost, markPath, origin, candidateSession) + var repeated struct { + ReadAt time.Time `json:"read_at"` + } + if err := json.Unmarshal(again.Body.Bytes(), &repeated); err != nil || !repeated.ReadAt.Equal(receipt.ReadAt) { + t.Fatalf("repeated mark = %s, %v, want the first read time %s", again.Body.String(), err, receipt.ReadAt) + } + if got := list(candidateSession); got.Items[0].ReadAt == nil || !got.Items[0].ReadAt.Equal(receipt.ReadAt) { + t.Fatalf("list after mark = %+v, want the persisted read time", got.Items) + } + + // Hiding the organization removes the content from the next read; the + // item and its read state stay. + if _, err := harness.pool.Exec(ctx, `INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, + candidate.ID, organizationID, now); err != nil { + t.Fatalf("hide organization: %v", err) + } + hidden := list(candidateSession) + if len(hidden.Items) != 1 || hidden.Items[0].Content != nil || hidden.Items[0].ReadAt == nil { + t.Fatalf("list after hiding = %+v, want the item without content and still read", hidden.Items) + } + if strings.Contains(notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications", "", candidateSession).Body.String(), organizationName) { + t.Fatal("the organization name still reaches a candidate who hid the organization") + } + + // Pagination: newest first, a cursor bound to the account. + for offset := 1; offset <= 3; offset++ { + extra := appendSyntheticNotice(ctx, t, transactor, candidate.ID, organizationID, now.Add(-time.Duration(offset)*time.Minute)) + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, extra) + } + firstPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=2", "", candidateSession)) + if len(firstPage.Items) != 2 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || + !firstPage.Items[0].DeliveredAt.After(firstPage.Items[1].DeliveredAt) { + t.Fatalf("first page = %+v, want two newest-first items and a cursor", firstPage) + } + cursor := url.QueryEscape(*firstPage.Page.NextCursor) + secondPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=2&cursor="+cursor, "", candidateSession)) + if len(secondPage.Items) != 2 || secondPage.Page.HasMore || secondPage.Items[0].ID == firstPage.Items[1].ID || + !secondPage.Items[0].DeliveredAt.Before(firstPage.Items[1].DeliveredAt) { + t.Fatalf("second page = %+v, want the remaining two items after the first page", secondPage) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?cursor="+cursor, "", otherCandidateSession), http.StatusBadRequest, "validation_failed") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/me/notifications?limit=101", "", candidateSession), http.StatusBadRequest, "validation_failed") + + // The employer cabinet: only the caller's items of this organization, and + // no access after the membership ends. + employerEvent := appendSyntheticNotice(ctx, t, transactor, owner.ID, organizationID, now.Add(-time.Minute)) + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, employerEvent) + foreignOrganizationEvent := appendSyntheticNotice(ctx, t, transactor, owner.ID, foreignOrganizationID, now.Add(-time.Minute)) + // An owner of another organization is not a member of it: the row exists + // but stays out of the cabinet of the first organization. + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, foreignOrganizationEvent) + organizationPath := "/api/v1/organizations/" + organizationID.String() + "/notifications" + organizationPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", ownerSession)) + if len(organizationPage.Items) != 1 || organizationPage.Items[0].ID != employerEvent.EventID || organizationPage.Items[0].Content == nil { + t.Fatalf("employer inbox = %+v, want only the item of this organization with content", organizationPage.Items) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", foreignSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+uuid.NewString()+"/notifications", "", ownerSession), http.StatusNotFound, "not_found") + employerMark := organizationPath + "/" + employerEvent.EventID.String() + "/read" + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, foreignSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, + organizationPath+"/"+foreignOrganizationEvent.EventID.String()+"/read", origin, ownerSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, + organizationPath+"/"+event.EventID.String()+"/read", origin, ownerSession), http.StatusNotFound, "not_found") + if marked := notificationRequest(t, harness, http.MethodPost, employerMark, origin, ownerSession); marked.Code != http.StatusOK { + t.Fatalf("employer mark read = %d %s, want 200", marked.Code, marked.Body.String()) + } + // A member of another role reads and marks its own items only, although the + // owner-only operations refuse it. + insertOrganizationHTTPMembership(ctx, t, harness, organizationID, recruiter.ID, "recruiter", "active", now) + recruiterEvent := appendSyntheticNotice(ctx, t, transactor, recruiter.ID, organizationID, now.Add(-time.Minute)) + deliverToInbox(ctx, t, consumerStore, notification.InboxConsumerName, recruiterEvent) + recruiterPage := decodeNotificationPage(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", recruiterSession)) + if len(recruiterPage.Items) != 1 || recruiterPage.Items[0].ID != recruiterEvent.EventID || recruiterPage.Items[0].Content == nil { + t.Fatalf("recruiter inbox = %+v, want only its own item with content", recruiterPage.Items) + } + if marked := notificationRequest(t, harness, http.MethodPost, organizationPath+"/"+recruiterEvent.EventID.String()+"/read", origin, recruiterSession); marked.Code != http.StatusOK { + t.Fatalf("recruiter mark read = %d %s, want 200", marked.Code, marked.Body.String()) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, recruiterSession), http.StatusNotFound, "not_found") + if _, err := harness.pool.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1 AND user_id = $2`, organizationID, owner.ID); err != nil { + t.Fatalf("revoke membership: %v", err) + } + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodGet, organizationPath, "", ownerSession), http.StatusNotFound, "not_found") + requireNotificationProblem(t, notificationRequest(t, harness, http.MethodPost, employerMark, origin, ownerSession), http.StatusNotFound, "not_found") +} + +// A recipient or an organization that does not exist is told apart, so a +// handler can retry and skip a deleted account but reject a broken reference. +func TestNotificationInboxStoreNamesTheMissingReference(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), notificationHTTPTimeout) + defer cancel() + harness := newNotificationHTTPHarness(ctx, t, env) + truncateTables(ctx, t, harness.pool, append([]pgx.Identifier{}, usersDependentTables...)...) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + candidate := createOrganizationHTTPUser(ctx, t, harness, "inbox-ref-candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + owner := createOrganizationHTTPUser(ctx, t, harness, "inbox-ref-owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + organizationID := createCompanyForContextTest(t, harness, env.Config.AppPublicURL, ownerSession, "inbox-ref-company") + + repository := postgresadapter.NewNotificationInboxRepository(harness.pool) + entry := func(recipientID, orgID uuid.UUID) domain.NotificationInboxEntry { + built, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{ + EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: orgID, + EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1, + SourceType: domain.NotificationInboxSourceOrganization, SourceID: orgID, OccurredAt: now, + }) + if err != nil { + t.Fatalf("NewNotificationInboxEntry() error = %v", err) + } + return built + } + if _, err := repository.Store(ctx, entry(uuid.New(), organizationID)); !errors.Is(err, outbound.ErrNotificationInboxRecipientMissing) { + t.Fatalf("Store(unknown recipient) error = %v, want ErrNotificationInboxRecipientMissing", err) + } + if _, err := repository.Store(ctx, entry(candidate.ID, uuid.New())); !errors.Is(err, outbound.ErrNotificationInboxReferenceMissing) { + t.Fatalf("Store(unknown organization) error = %v, want ErrNotificationInboxReferenceMissing", err) + } + if created, err := repository.Store(ctx, entry(candidate.ID, organizationID)); err != nil || !created { + t.Fatalf("Store(valid) = %t, %v, want true, nil", created, err) + } +} diff --git a/backend/integration_test/notification_restart_test.go b/backend/integration_test/notification_restart_test.go new file mode 100644 index 0000000..23093b1 --- /dev/null +++ b/backend/integration_test/notification_restart_test.go @@ -0,0 +1,222 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/twmb/franz-go/pkg/kgo" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/worker/eventconsumer" +) + +// noticeConsumers names the Kafka groups of the two notification consumers +// of one deployment. A restarted process keeps its groups; a group that lost +// its offsets is a new name. +type noticeConsumers struct { + inboxGroup string + deliveryGroup string +} + +func newNoticeConsumers() noticeConsumers { + return noticeConsumers{inboxGroup: newConsumerGroup(), deliveryGroup: newConsumerGroup()} +} + +// TestInvitationNoticesSurviveRelayAndConsumerRestarts follows the real send +// of two invitations through the outbox, the relay, Kafka, and the two +// notification consumers that bootstrap registers. The relay dies after the +// broker acknowledged the events and before the mark committed; the backend +// is then restarted, so the same event IDs are published and consumed again; +// finally a consumer group that lost its offsets replays the whole topic. +// Each recipient keeps exactly one internal notification and one mail +// delivery, and the mail worker sends one message to each. +func TestInvitationNoticesSurviveRelayAndConsumerRestarts(t *testing.T) { + env := bootstrap(t, postgresService, kafkaService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + recipients := []domain.User{ + fixture.candidate(t, "restart-first@example.test"), + fixture.candidate(t, "restart-second@example.test"), + } + for _, recipient := range recipients { + fixture.invite(t, recipient.ID) + } + // Each send appends invitation.delivered for the inbox and + // notification.mail_requested for the mail, each its own aggregate. + events := readOutboxEvents(ctx, t, fixture.pool) + if len(events) != 2*len(recipients) { + t.Fatalf("outbox holds %d events after %d sends, want %d", len(events), len(recipients), 2*len(recipients)) + } + published := int64(len(events)) + + // One partition keeps the committed offset equal to the number of + // records a consumer has finished. + topic := env.createKafkaTopic(ctx, t, 1) + relays := &relayHarness{ + env: env, pool: fixture.pool, transactor: fixture.transactor, + store: postgresadapter.NewOutboxRelayStore(fixture.pool, relayStoreTimeouts), + } + store := postgresadapter.NewEventConsumerStore(fixture.pool, consumerHandlerTime) + + // The relay produces every event and is killed before its mark commits. + passCtx, killPass := context.WithCancel(ctx) + defer killPass() + dying := relays.newRelay(crashAfterPublish{EventPublisher: relays.newPublisher(t, topic), crash: killPass}) + if result, err := dying.PublishPending(passCtx); !errors.Is(err, context.Canceled) || result.Published != 0 || result.Claimed != len(events) { + t.Fatalf("PublishPending() of the dying relay = %+v, %v; want every event claimed, none marked, and context.Canceled", result, err) + } + assertUnpublished(ctx, t, fixture.pool, len(events)) + + // The consumers of the first process apply the records. + deployment := newNoticeConsumers() + firstRun := prometheus.New() + fixture.runNoticeConsumers(ctx, t, env, store, topic, deployment, firstRun, published) + assertNoticeRecords(t, firstRun, notification.InboxConsumerName, len(recipients), 0) + assertNoticeRecords(t, firstRun, notification.DeliveryConsumerName, len(recipients), 0) + fixture.assertOneNoticePerRecipient(t, recipients) + + // After the restart the relay finds the events unmarked and publishes them + // again under the same event IDs, and the restarted consumers resume + // from their committed offsets. + restarted := relays.newRelay(relays.newPublisher(t, topic)) + if got := relays.publishUntilDrained(ctx, t, restarted); got != len(events) { + t.Fatalf("restarted relay published %d events, want the %d unmarked ones", got, len(events)) + } + assertUnpublished(ctx, t, fixture.pool, 0) + republished := env.consumeKafkaRecords(ctx, t, topic, int(2*published)) + assertSameEventIDs(t, republished, events) + secondRun := prometheus.New() + fixture.runNoticeConsumers(ctx, t, env, store, topic, deployment, secondRun, 2*published) + assertNoticeRecords(t, secondRun, notification.InboxConsumerName, 0, len(recipients)) + assertNoticeRecords(t, secondRun, notification.DeliveryConsumerName, 0, len(recipients)) + fixture.assertOneNoticePerRecipient(t, recipients) + + // Groups that lost their offsets replay the whole topic: every record is + // a duplicate. + replay := prometheus.New() + fixture.runNoticeConsumers(ctx, t, env, store, topic, newNoticeConsumers(), replay, 2*published) + assertNoticeRecords(t, replay, notification.InboxConsumerName, 0, 2*len(recipients)) + assertNoticeRecords(t, replay, notification.DeliveryConsumerName, 0, 2*len(recipients)) + fixture.assertOneNoticePerRecipient(t, recipients) + assertRowCount(ctx, t, fixture.pool, pgx.Identifier{"consumer_dead_letters"}, 0) + + // The mail worker sends one message to each recipient and then idles. + sender := fixture.sender(t, 100, 3000, 0, 0) + for range recipients { + if result := fixture.harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("notification pass = %+v, want accepted", result) + } + } + if result := fixture.harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after every notice was sent = %+v, want idle", result) + } + for _, recipient := range recipients { + if sent := fixture.requestsFor(recipient.Email.Address()); len(sent) != 1 { + t.Fatalf("provider requests to one recipient = %d, want exactly one", len(sent)) + } + } +} + +// runNoticeConsumers runs the inbox and delivery consumers, as bootstrap +// builds them, in the groups of deployment until both committed offset, and +// then stops them as a process shutdown does. +func (fixture *productNoticeFixture) runNoticeConsumers( + ctx context.Context, + t *testing.T, + env *testEnvironment, + store *postgresadapter.EventConsumerStore, + topic string, + deployment noticeConsumers, + metrics *prometheus.Metrics, + offset int64, +) { + t.Helper() + logger := slog.New(slog.DiscardHandler) + handlers := map[string]inbound.EventHandler{ + deployment.inboxGroup: notification.NewInboxHandler(logger, false), + deployment.deliveryGroup: notification.NewDeliveryHandler( + notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, logger), + } + sources := &consumerHarness{env: env} + stops := make([]func(), 0, len(handlers)) + for group, handler := range handlers { + source, closeSource := sources.newSource(t, topic, group) + consumer, err := eventconsumer.New(handler, source, store, metrics, logger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New(%s) error = %v", handler.ConsumerName(), err) + } + stopRun := runConsumer(ctx, t, consumer) + stops = append(stops, func() { + stopRun() + closeSource() + }) + } + for group := range handlers { + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: offset}) + } + for _, stop := range stops { + stop() + } +} + +// assertOneNoticePerRecipient counts the internal notifications and the mail +// deliveries of each recipient. +func (fixture *productNoticeFixture) assertOneNoticePerRecipient(t *testing.T, recipients []domain.User) { + t.Helper() + for _, recipient := range recipients { + var inbox, deliveries int + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT + (SELECT count(*) FROM notification_inbox_events WHERE recipient_user_id = $1), + (SELECT count(*) FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification')`, + recipient.ID).Scan(&inbox, &deliveries); err != nil { + t.Fatalf("count the notices of a recipient: %v", err) + } + if inbox != 1 || deliveries != 1 { + t.Fatalf("a recipient has %d inbox rows and %d notification deliveries, want one of each", inbox, deliveries) + } + } +} + +// assertNoticeRecords checks how many records a consumer applied and how many +// it recognized as duplicates. +func assertNoticeRecords(t *testing.T, metrics *prometheus.Metrics, consumer string, applied, duplicate int) { + t.Helper() + scraped := scrapeMetrics(metrics) + for outcome, want := range map[string]int{eventconsumer.OutcomeApplied: applied, eventconsumer.OutcomeDuplicate: duplicate} { + series := fmt.Sprintf(`lincodex_event_consumer_records_total{consumer=%q,outcome=%q} %d`, consumer, outcome, want) + if !strings.Contains(scraped, series+"\n") { + t.Fatalf("metrics lack %s", series) + } + } +} + +// assertSameEventIDs checks that the topic holds every outbox event exactly +// twice under its original event ID and nothing else. +func assertSameEventIDs(t *testing.T, records []*kgo.Record, events []storedEvent) { + t.Helper() + counts := make(map[string]int, len(events)) + for _, record := range records { + counts[headerValue(record, "event_id")]++ + } + for _, event := range events { + if counts[event.eventID.String()] != 2 { + t.Fatalf("event %s is on the topic %d times, want twice", event.eventID, counts[event.eventID.String()]) + } + } + if len(counts) != len(events) { + t.Fatalf("the topic holds %d event IDs, want the %d of the outbox", len(counts), len(events)) + } +} diff --git a/backend/integration_test/notification_subject_migration_test.go b/backend/integration_test/notification_subject_migration_test.go new file mode 100644 index 0000000..ced7829 --- /dev/null +++ b/backend/integration_test/notification_subject_migration_test.go @@ -0,0 +1,120 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +// notificationSubjectMigrationVersion adds the subject columns of notifications; +// productNoticeMigrationVersion adds the rights reasons, the body clearing of a +// cancelled notice, and the product due index on top of it. +const ( + notificationSubjectMigrationVersion = 44 + productNoticeMigrationVersion = 45 +) + +// TestNotificationSubjectMigrations checks the constraints that the rights +// checks rely on, and that the rollback of the two migrations refuses while +// rows name a subject or carry a rights cancellation, and runs once they are gone. +func TestNotificationSubjectMigrations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + // Migration 00046 (verification codes) and every later one are newer than + // the subject migration under test. Roll them back first, newest first, so + // the rollback checks below act on 00045. + for { + result, err := migrator.DownOne(ctx) + if err != nil || result.Version < 46 { + t.Fatalf("roll back the newer migrations: result %+v, error = %v; want every migration down to 46", result, err) + } + if result.Version == 46 { + break + } + } + + now := time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC) + userID, deliveryID, invitationID, organizationID := uuid.New(), uuid.New(), uuid.New(), uuid.New() + exec := func(statement string, args ...any) error { + t.Helper() + _, err := pool.Exec(ctx, statement, args...) + return err + } + if err := exec(`INSERT INTO users (id, email, email_normalized, password_hash, scenario, onboarding_step, email_verified_at, + registration_version, last_registered_at, version, created_at, updated_at) + VALUES ($1, 'notice@example.com', 'notice@example.com', $2, 'candidate', 'candidate_consents', $3, 1, $3, 1, $3, $3)`, + userID, identityTestPasswordHash, now); err != nil { + t.Fatalf("insert the account: %v", err) + } + + // A cancelled notice that names its invitation and has no bodies is what + // the sending worker stores after a rights check. + if err := exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, + content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, + created_at, updated_at, cancel_reason, body_redacted_at, subject_kind, subject_id, subject_organization_id) + VALUES ($1, $2, 'notice@example.com', 'notification', 'notification.v1', 's', '', '', $3, 'resend', 'main', + 'delivery/notice', 'cancelled', 0, NULL, 2, $4, $4, 'rights_revoked', $4, 'invitation', $5, $6)`, + deliveryID, userID, make([]byte, sha256.Size), now, invitationID, organizationID); err != nil { + t.Fatalf("store a cancelled notice with its subject: %v", err) + } + + // A subject belongs to a notification only, and the three subject columns + // are set together. + if err := exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, + content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, + created_at, updated_at, subject_kind, subject_id, subject_organization_id) + VALUES ($1, $2, 'notice@example.com', 'verification', 'verification.v1', 's', 't', '', $3, 'resend', 'main', + 'delivery/subject-verification', 'pending', 0, $4, 1, $4, $4, 'invitation', $5, $6)`, + uuid.New(), userID, make([]byte, sha256.Size), now, invitationID, organizationID); err == nil || !strings.Contains(err.Error(), "deliveries_subject_complete") { + t.Fatalf("a subject on a verification mail: error = %v, want deliveries_subject_complete", err) + } + // Bodies are cleared only for a cancelled notice or a terminal token mail. + if err := exec(`INSERT INTO deliveries (id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, + content_sha256, provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, + created_at, updated_at, body_redacted_at) + VALUES ($1, $2, 'notice@example.com', 'notification', 'notification.v1', 's', '', '', $3, 'resend', 'main', + 'delivery/cleared-pending', 'pending', 0, $4, 1, $4, $4, $4)`, + uuid.New(), userID, make([]byte, sha256.Size), now); err == nil || !strings.Contains(err.Error(), "deliveries_body_present") { + t.Fatalf("a pending notice without bodies: error = %v, want deliveries_body_present", err) + } + // The subject is fixed with the delivery, like its content. + // The trigger reports its refusal by message, not by constraint name. + if err := exec(`UPDATE deliveries SET subject_id = gen_random_uuid() WHERE id = $1`, deliveryID); err == nil || + !strings.Contains(err.Error(), "content and recipient are immutable") { + t.Fatalf("changing the subject: error = %v, want the content refusal", err) + } + + // The rollback refuses while the schema holds rights cancellations. + if _, err := migrator.DownOne(ctx); err == nil || !strings.Contains(err.Error(), "rights check") { + t.Fatalf("DownOne() with a rights cancellation stored: error = %v, want the refusal that names the rights check", err) + } + // Once the account is gone, its notices go with it, and the rollback runs. + if err := exec(`DELETE FROM users WHERE id = $1`, userID); err != nil { + t.Fatalf("delete the account: %v", err) + } + for _, version := range []int64{productNoticeMigrationVersion, notificationSubjectMigrationVersion} { + result, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("DownOne() to below %d error = %v", version, err) + } + if result.Version != version { + t.Fatalf("DownOne() rolled back %d, want %d", result.Version, version) + } + } + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() after the rollback error = %v", err) + } +} diff --git a/backend/integration_test/organization_http_test.go b/backend/integration_test/organization_http_test.go new file mode 100644 index 0000000..a84f627 --- /dev/null +++ b/backend/integration_test/organization_http_test.go @@ -0,0 +1,434 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/organization" +) + +const organizationHTTPTestTimeout = 5 * time.Minute + +type organizationHTTPSession struct { + cookie *http.Cookie + csrf string +} + +func TestOrganizationCreationAndOwnerEditingOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), organizationHTTPTestTimeout) + defer cancel() + harness := newOrganizationHTTPHarness(ctx, t, env) + initialLogs := harness.logs + resetTables := append(append([]pgx.Identifier{}, usersDependentTables...), pgx.Identifier{"idempotency_records"}) + truncateTables(ctx, t, harness.pool, resetTables...) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + owner := createOrganizationHTTPUser(ctx, t, harness, "owner@example.test", passwordHash, domain.ScenarioEmployer, true, now) + foreign := createOrganizationHTTPUser(ctx, t, harness, "foreign@example.test", passwordHash, domain.ScenarioEmployer, true, now) + candidate := createOrganizationHTTPUser(ctx, t, harness, "candidate@example.test", passwordHash, domain.ScenarioCandidate, true, now) + unverified := createOrganizationHTTPUser(ctx, t, harness, "unverified@example.test", passwordHash, domain.ScenarioEmployer, false, now) + + ownerSession := loginOrganizationHTTP(t, harness, owner.Email.Address()) + foreignSession := loginOrganizationHTTP(t, harness, foreign.Email.Address()) + candidateSession := loginOrganizationHTTP(t, harness, candidate.Email.Address()) + unverifiedLogin := loginSessionHTTP(t, harness, unverified.Email.Address(), sessionHTTPTestPass, + env.Config.AppPublicURL, "", "192.0.2.44:1234") + requireSessionProblem(t, unverifiedLogin, http.StatusForbidden, "email_not_verified") + if len(unverifiedLogin.Header().Values("Set-Cookie")) != 0 { + t.Fatal("unverified account received a session cookie") + } + + createBody := "{\"name\":\"ООО Тестовая компания\",\"description\":\"Профиль компании\",\"contacts\":{\"website\":\"https://company.example.test\",\"email\":\"careers@example.test\",\"phone\":\"+74950000000\",\"telegram\":\"@company_careers\"},\"representatives\":[{\"name\":\"Ирина Проверочная\",\"job_title\":\"Руководитель найма\"}]}" + createResponses := make(chan *httptest.ResponseRecorder, 2) + for range 2 { + go func() { + createResponses <- organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + }() + } + created := <-createResponses + concurrentReplay := <-createResponses + if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("create response = %d %s, Cache-Control=%q, want 201 no-store", created.Code, created.Body.String(), created.Header().Get("Cache-Control")) + } + originalBody := append([]byte(nil), created.Body.Bytes()...) + if concurrentReplay.Code != http.StatusCreated || string(concurrentReplay.Body.Bytes()) != string(originalBody) { + t.Fatalf("concurrent create = %d %s, want the same 201 body %s", concurrentReplay.Code, concurrentReplay.Body.String(), originalBody) + } + var creation struct { + ID string `json:"id"` + Version int64 `json:"version"` + Name string `json:"name"` + Verification struct { + Level string `json:"level"` + Basis string `json:"basis"` + } `json:"verification"` + CandidateCard map[string]json.RawMessage `json:"candidate_card"` + } + if err := json.Unmarshal(originalBody, &creation); err != nil { + t.Fatalf("decode created organization: %v", err) + } + if creation.ID == "" || creation.Version != 1 || creation.Name != "ООО Тестовая компания" || + creation.Verification.Level != "e0" || creation.Verification.Basis != "confirmed_email" { + t.Fatalf("created company has unexpected identity or verification: %+v", creation) + } + for _, key := range []string{"id", "name", "description", "sphere", "contacts", "representatives", "verification_level"} { + if _, ok := creation.CandidateCard[key]; !ok { + t.Fatalf("candidate card has no %q field: %v", key, creation.CandidateCard) + } + } + for _, key := range []string{"owner", "membership", "role", "email_verified", "user_id", "password"} { + if _, ok := creation.CandidateCard[key]; ok { + t.Fatalf("candidate card exposes private %q field", key) + } + } + assertOrganizationHTTPCounts(ctx, t, harness.pool, 1, 1, 1, 1) + organizationID := creation.ID + + var storedRole, storedState string + if err := harness.pool.QueryRow(ctx, + "SELECT role, state FROM memberships WHERE organization_id = $1 AND user_id = $2", organizationID, owner.ID, + ).Scan(&storedRole, &storedState); err != nil { + t.Fatalf("read creator membership: %v", err) + } + if storedRole != "owner" || storedState != "active" { + t.Fatalf("stored creator membership = %s/%s, want active owner", storedRole, storedState) + } + + updated := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, + "{\"expected_version\":1,\"name\":\"ООО Обновленная компания\",\"description\":null}", + env.Config.AppPublicURL, ownerSession, "") + if updated.Code != http.StatusOK { + t.Fatalf("owner update = %d %s, want 200", updated.Code, updated.Body.String()) + } + var updatedBody struct { + Version int64 `json:"version"` + Name string `json:"name"` + Description *string `json:"description"` + Verification struct { + Level string `json:"level"` + Basis string `json:"basis"` + } `json:"verification"` + } + if err := json.Unmarshal(updated.Body.Bytes(), &updatedBody); err != nil { + t.Fatalf("decode updated organization: %v", err) + } + if updatedBody.Version != 2 || updatedBody.Name != "ООО Обновленная компания" || updatedBody.Description != nil || + updatedBody.Verification.Level != "e0" || updatedBody.Verification.Basis != "confirmed_email" { + t.Fatalf("updated organization = %+v, want edited profile and unchanged E0", updatedBody) + } + harness.pool.Close() + harness = newOrganizationHTTPHarness(ctx, t, env) + restartedRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "", + "", ownerSession, "") + if restartedRead.Code != http.StatusOK { + t.Fatalf("read with a new handler and pool = %d %s, want 200", restartedRead.Code, restartedRead.Body.String()) + } + var restartedBody struct { + Version int64 `json:"version"` + Name string `json:"name"` + } + if err := json.Unmarshal(restartedRead.Body.Bytes(), &restartedBody); err != nil { + t.Fatalf("decode organization after handler restart: %v", err) + } + if restartedBody.Version != 2 || restartedBody.Name != "ООО Обновленная компания" { + t.Fatalf("organization after handler restart = %+v, want the persisted owner update", restartedBody) + } + staleUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, + "{\"expected_version\":1,\"name\":\"ООО Устаревшее изменение\"}", + env.Config.AppPublicURL, ownerSession, "") + requireSessionProblem(t, staleUpdate, http.StatusPreconditionFailed, "version_conflict") + + replay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + if replay.Code != http.StatusCreated || replay.Header().Get("Cache-Control") != "no-store" || + string(replay.Body.Bytes()) != string(originalBody) { + t.Fatalf("same-key replay = %d %s, want the exact original 201 body %s", replay.Code, replay.Body.String(), originalBody) + } + changed := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", + "{\"name\":\"ООО Другой запрос\"}", + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + requireSessionProblem(t, changed, http.StatusUnprocessableEntity, "idempotency_key_reused") + replayTime := harness.clock.Now() + expired, err := harness.pool.Exec(ctx, "UPDATE idempotency_records SET created_at = $1, expires_at = $2", + replayTime.Add(-2*time.Second), replayTime.Add(-time.Second)) + if err != nil { + t.Fatalf("expire the original create key: %v", err) + } + if expired.RowsAffected() != 1 { + t.Fatalf("expired idempotency rows = %d, want 1", expired.RowsAffected()) + } + reused := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + if reused.Code != http.StatusCreated { + t.Fatalf("create with an expired key = %d %s, want 201", reused.Code, reused.Body.String()) + } + var reusedBody struct { + ID string `json:"id"` + } + if err := json.Unmarshal(reused.Body.Bytes(), &reusedBody); err != nil { + t.Fatalf("decode organization created after key expiration: %v", err) + } + if reusedBody.ID == organizationID { + t.Fatal("expired key replayed the old company instead of creating a new one") + } + reusedReplay := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", createBody, + env.Config.AppPublicURL, ownerSession, "organization-http-create-1") + if reusedReplay.Code != http.StatusCreated || string(reusedReplay.Body.Bytes()) != string(reused.Body.Bytes()) { + t.Fatalf("replay after key reuse = %d %s, want the replacement snapshot %s", + reusedReplay.Code, reusedReplay.Body.String(), reused.Body.String()) + } + assertOrganizationHTTPCounts(ctx, t, harness.pool, 2, 2, 2, 1) + + foreignRead := organizationHTTPRequest(t, harness, http.MethodGet, "/api/v1/organizations/"+organizationID, "", + "", foreignSession, "") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + foreignUpdate := organizationHTTPRequest(t, harness, http.MethodPatch, "/api/v1/organizations/"+organizationID, + "{\"expected_version\":2,\"name\":\"Не владелец\"}", + env.Config.AppPublicURL, foreignSession, "") + requireSessionProblem(t, foreignUpdate, http.StatusNotFound, "not_found") + candidateCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", + "{\"name\":\"Кандидат не может создать компанию\"}", + env.Config.AppPublicURL, candidateSession, "organization-http-candidate-create") + requireSessionProblem(t, candidateCreate, http.StatusForbidden, "forbidden") + + // The failed owner insert must roll back the organization and idempotency + // reservation together. Reusing the same key after removing the constraint + // proves the request left no partial state. + if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships ADD CONSTRAINT organization_http_reject_owner CHECK (role <> 'owner') NOT VALID"); err != nil { + t.Fatalf("install temporary owner failure constraint: %v", err) + } + t.Cleanup(func() { + _, _ = harness.pool.Exec(context.WithoutCancel(ctx), "ALTER TABLE memberships DROP CONSTRAINT IF EXISTS organization_http_reject_owner") + }) + beforeFailure := readOrganizationHTTPCounts(ctx, t, harness.pool) + rollbackBody := "{\"name\":\"ООО Повтор после отката\"}" + failedCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody, + env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1") + if failedCreate.Code != http.StatusInternalServerError { + t.Fatalf("owner insert failure status = %d %s, want 500", failedCreate.Code, failedCreate.Body.String()) + } + assertOrganizationHTTPCountsEqual(ctx, t, harness.pool, beforeFailure) + if _, err := harness.pool.Exec(ctx, "ALTER TABLE memberships DROP CONSTRAINT organization_http_reject_owner"); err != nil { + t.Fatalf("remove temporary owner failure constraint: %v", err) + } + recoveredCreate := organizationHTTPRequest(t, harness, http.MethodPost, "/api/v1/organizations", rollbackBody, + env.Config.AppPublicURL, ownerSession, "organization-http-rollback-1") + if recoveredCreate.Code != http.StatusCreated { + t.Fatalf("create after rollback = %d %s, want 201 with the same idempotency key", recoveredCreate.Code, recoveredCreate.Body.String()) + } + + for _, marker := range []string{ + owner.Email.Address(), foreign.Email.Address(), candidate.Email.Address(), unverified.Email.Address(), + "Ирина Проверочная", "careers@example.test", "ООО Тестовая компания", "ООО Обновленная компания", + } { + if strings.Contains(initialLogs.String(), marker) || strings.Contains(harness.logs.String(), marker) { + t.Fatalf("organization HTTP logs contain profile or account data %q", marker) + } + } +} + +func newOrganizationHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + sessionService, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), + Users: store.Users(), Sessions: store.Sessions(), Credentials: credentials, + Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + organizationService, err := organization.NewService(organization.Dependencies{ + Transactor: postgresadapter.NewTransactor(pool), Keyring: keyring, Clock: clock.Now, + }) + if err != nil { + t.Fatalf("organization.NewService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessionService), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + organizationHandler := v1.NewOrganizationHandler(organizationService, env.Config.AppPublicURL) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithOrganization(organizationHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil, httpadapter.NewCompanyContextMiddleware(organizationHandler)) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{ + pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs, + } +} + +func createOrganizationHTTPUser( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, + scenario domain.Scenario, + verified bool, + now time.Time, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: scenario, RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(%q) error = %v", email, err) + } + if !verified { + return user + } + user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + return user +} + +func loginOrganizationHTTP(t *testing.T, harness *sessionHTTPHarness, email string) organizationHTTPSession { + t.Helper() + response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.40:1234") + if response.Code != http.StatusCreated { + t.Fatalf("login status = %d %s, want 201", response.Code, response.Body.String()) + } + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode login response: %v", err) + } + if body.CSRFToken == "" { + t.Fatal("login response has no CSRF token") + } + return organizationHTTPSession{cookie: requireSessionCookie(t, response), csrf: body.CSRFToken} +} + +func organizationHTTPRequest( + t *testing.T, + harness *sessionHTTPHarness, + method, path, body, origin string, + session organizationHTTPSession, + idempotencyKey string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if origin != "" { + request.Header.Set("Origin", origin) + } + if session.cookie != nil { + request.AddCookie(&http.Cookie{Name: "__Host-lincodex_session", Value: session.cookie.Value}) + } + if session.csrf != "" { + request.Header.Set("X-CSRF-Token", session.csrf) + } + if idempotencyKey != "" { + request.Header.Set("Idempotency-Key", idempotencyKey) + } + request.RemoteAddr = "192.0.2.41:1234" + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return recorder +} + +type organizationHTTPRowCounts struct { + organizations int64 + representatives int64 + memberships int64 + results int64 + idempotency int64 +} + +func readOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool) organizationHTTPRowCounts { + t.Helper() + var counts organizationHTTPRowCounts + if err := pool.QueryRow(ctx, ` + SELECT + (SELECT count(*) FROM organizations), + (SELECT count(*) FROM organization_representatives), + (SELECT count(*) FROM memberships), + (SELECT count(*) FROM organization_creation_results), + (SELECT count(*) FROM idempotency_records) + `).Scan(&counts.organizations, &counts.representatives, &counts.memberships, &counts.results, &counts.idempotency); err != nil { + t.Fatalf("read organization transaction counts: %v", err) + } + return counts +} + +func assertOrganizationHTTPCounts(ctx context.Context, t *testing.T, pool *pgxpool.Pool, + organizations, representatives, memberships, results int64, +) { + t.Helper() + counts := readOrganizationHTTPCounts(ctx, t, pool) + if counts.organizations != organizations || counts.representatives != representatives || + counts.memberships != memberships || counts.results != results { + t.Fatalf("organization rows = %+v, want org=%d representatives=%d memberships=%d snapshots=%d", + counts, organizations, representatives, memberships, results) + } +} + +func assertOrganizationHTTPCountsEqual(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want organizationHTTPRowCounts) { + t.Helper() + if got := readOrganizationHTTPCounts(ctx, t, pool); got != want { + t.Fatalf("failed organization create changed transactional rows: got %+v, want %+v", got, want) + } +} diff --git a/backend/integration_test/organizations_test.go b/backend/integration_test/organizations_test.go new file mode 100644 index 0000000..39e4a7b --- /dev/null +++ b/backend/integration_test/organizations_test.go @@ -0,0 +1,1019 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + organizationTestTimeout = 3 * time.Minute + // concurrentOrganizationUpdates change one organization at once from the + // same version, each on its own connection. + concurrentOrganizationUpdates = 8 + organizationUniqueViolation = "23505" + organizationCheckViolation = "23514" + organizationRestrictViolation = "23001" +) + +var ( + organizationsTable = pgx.Identifier{"organizations"} + organizationRepresentativesTable = pgx.Identifier{"organization_representatives"} + membershipsTable = pgx.Identifier{"memberships"} + organizationCreationResultsTable = pgx.Identifier{"organization_creation_results"} + // organizationTables are emptied together: memberships reference both + // users and organizations. Creation snapshots reference idempotency records. + organizationTables = []pgx.Identifier{ + {"candidate_card_access_events"}, + {"invitation_creation_results"}, {"invitation_send_results"}, {"invitation_decline_results"}, {"invitation_declines"}, + {"invitation_events"}, {"invitation_terms_versions"}, {"invitation_accept_results"}, {"contact_grants"}, {"invitations"}, + // Stored vectors reference both needs and candidate accounts. + {"semantic_vectors"}, + {"organization_need_versions"}, {"organization_needs"}, + {"organization_need_creation_results"}, + {"company_invitation_quota_usage"}, {"company_card_view_quota_usage"}, + organizationCreationResultsTable, membershipsTable, organizationRepresentativesTable, organizationsTable, + // holdings reference users and are referenced by organizations. + {"holdings"}, + } + candidateQuestionnaireTables = []pgx.Identifier{ + {"candidate_questionnaire_specializations"}, {"candidate_questionnaires"}, + } + assessmentAttemptTables = []pgx.Identifier{ + {"skill_evidence_skills"}, {"skill_evidence_facts"}, + {"candidate_assessment_categories"}, {"assessment_attempt_results"}, + {"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"}, + {"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"}, + {"assessment_practice_jobs"}, {"assessment_practice_submissions"}, {"assessment_practices"}, + {"assessment_attempt_work_leases"}, {"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"}, + } + supportCaseTables = []pgx.Identifier{ + {"support_case_events"}, {"support_cases"}, {"support_case_create_outcomes"}, {"support_case_request_events"}, + } + // userNoticeTables hold per-user notices that refer to users and, for the + // inbox, to organizations. + userNoticeTables = []pgx.Identifier{ + {"assessment_signal_notice_acknowledgements"}, {"notification_inbox_events"}, + } + // usersDependentTables is every table that references users, directly or + // through another table of the list. A TRUNCATE of users must name all of + // them, so a migration that adds such a table adds it here. + usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables, userNoticeTables) +) + +// organizationFixture works on the bootstrap database. The tables are +// truncated between subtests. +type organizationFixture struct { + ctx context.Context + pool *pgxpool.Pool + identity identityFixture + transactor *postgresadapter.Transactor + // now is truncated to microseconds, the precision PostgreSQL stores. + now time.Time +} + +func TestOrganizationsAndMemberships(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + fixture := organizationFixture{ + ctx: ctx, + pool: pool, + identity: identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now}, + transactor: postgresadapter.NewTransactor(pool), + now: now, + } + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, usersDependentTables...) + } + + t.Run("stores an organization with its owner and reads it back for the member", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример Платежи"), now) + + read, membership, err := fixture.read(owner.ID, organization.ID()) + if err != nil { + t.Fatalf("GetForMember() error = %v", err) + } + if !read.Profile().Equal(organization.Profile()) || read.Version() != 1 || !read.CreatedAt().Equal(now) || !read.UpdatedAt().Equal(now) { + t.Fatalf("stored organization = %v, want the created profile at version 1", read) + } + if verification := read.Verification(); verification.Level() != domain.OrganizationVerificationE0 || + verification.Basis() != domain.OrganizationBasisConfirmedEmail || !verification.ChangedAt().Equal(now) { + t.Fatalf("verification = %s %s, want e0 on the confirmed email", verification.Level(), verification.Basis()) + } + if membership.Role() != domain.OrganizationRoleOwner || membership.State() != domain.MembershipStateActive || + membership.UserID() != owner.ID || membership.OrganizationID() != organization.ID() { + t.Fatalf("membership = %+v, want the active owner membership of the creator", membership) + } + if got := read.Profile().Representatives(); len(got) != 2 || got[0].Name() != "Анна Тестова" || got[1].Name() != "Борис Образцов" { + t.Fatalf("representatives = %v, want two in the given order", got) + } + + // The stored values are NULL for a field that is not set, not an + // empty string. + minimal := fixture.create(t, owner, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Только имя"}), now.Add(time.Minute)) + var description, website *string + if err := pool.QueryRow(ctx, `SELECT description, contact_website FROM organizations WHERE id = $1`, minimal.ID()).Scan(&description, &website); err != nil { + t.Fatalf("select the minimal organization: %v", err) + } + if description != nil || website != nil { + t.Fatalf("description = %v, website = %v, want NULL for fields that are not set", description, website) + } + bare, _, err := fixture.read(owner.ID, minimal.ID()) + if err != nil || len(bare.Profile().Representatives()) != 0 { + t.Fatalf("GetForMember(organization without representatives) = %v, %v, want an empty list", bare, err) + } + }) + + t.Run("a repeated membership of the same pair violates the unique constraint in any state", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now) + + for _, role := range domain.OrganizationRoles() { + repeated, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: owner.ID, Role: role, At: now.Add(time.Hour)}) + if err != nil { + t.Fatalf("NewMembership(%s) error = %v", role, err) + } + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Memberships().Insert(ctx, repeated) + }) + if !errors.Is(err, outbound.ErrMembershipExists) || !strings.Contains(err.Error(), "memberships_user_id_organization_id_key") { + t.Fatalf("Insert(repeated %s) error = %v, want ErrMembershipExists naming the constraint", role, err) + } + } + // A membership that ended keeps its row, so the pair stays taken. + fixture.setMembershipState(t, organization.ID(), owner.ID, domain.MembershipStateLeft) + repeated, err := domain.NewOwnerMembership(organization.ID(), owner.ID, now.Add(time.Hour)) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Memberships().Insert(ctx, repeated) + }) + if !errors.Is(err, outbound.ErrMembershipExists) { + t.Fatalf("Insert(after the member left) error = %v, want ErrMembershipExists", err) + } + // The database refuses it without the adapter, too. + _, err = pool.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + VALUES ($1, $2, $3, 'recruiter', 'active', $4, $4)`, uuid.New(), organization.ID(), owner.ID, now) + assertSQLError(t, "raw duplicate membership", err, organizationUniqueViolation, "memberships_user_id_organization_id_key") + assertRowCount(ctx, t, pool, membershipsTable, 1) + + // Another account, or another organization, is another pair. + second := fixture.employer(t, "second@example.com") + fixture.addMember(t, organization, second, domain.OrganizationRoleRecruiter, now.Add(2*time.Hour)) + other := fixture.create(t, owner, fixture.completeProfile(t, "ООО Другое"), now.Add(3*time.Hour)) + if _, _, err := fixture.read(owner.ID, other.ID()); err != nil { + t.Fatalf("GetForMember(second organization of the same account) error = %v", err) + } + assertRowCount(ctx, t, pool, membershipsTable, 3) + + if _, err := fixture.getMembership(organization.ID(), second.ID); err != nil { + t.Fatalf("Get(membership) error = %v", err) + } + if _, err := fixture.getMembership(organization.ID(), uuid.New()); !errors.Is(err, outbound.ErrMembershipNotFound) { + t.Fatalf("Get(unknown account) error = %v, want ErrMembershipNotFound", err) + } + }) + + t.Run("an organization and its owner are stored atomically", func(t *testing.T) { + reset(t) + creator := fixture.employer(t, "creator@example.com") + + // The owner row fails on a foreign key: the organization, its + // representatives, and the membership are all rolled back. + organization := fixture.newOrganization(t, fixture.completeProfile(t, "ООО Пример"), now) + unknownOwner, err := domain.NewOwnerMembership(organization.ID(), uuid.New(), now) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, organization, unknownOwner) + }) + if !errors.Is(err, outbound.ErrUserNotFound) { + t.Fatalf("CreateWithOwner(unknown account) error = %v, want ErrUserNotFound", err) + } + fixture.assertNothingStored(t) + + // A later failure of the same transaction removes the organization. + owner, err := domain.NewOwnerMembership(organization.ID(), creator.ID, now) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + failure := errors.New("the usecase failed after the organization was stored") + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := unit.Organizations().CreateWithOwner(ctx, organization, owner); err != nil { + return err + } + return failure + }) + if !errors.Is(err, failure) { + t.Fatalf("transaction error = %v, want the usecase failure", err) + } + fixture.assertNothingStored(t) + + // The adapter refuses an owner that is not the active owner of the + // organization before it writes anything. + recruiter, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: creator.ID, Role: domain.OrganizationRoleRecruiter, At: now}) + if err != nil { + t.Fatalf("NewMembership() error = %v", err) + } + foreign, err := domain.NewOwnerMembership(uuid.New(), creator.ID, now) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + for name, membership := range map[string]domain.Membership{"recruiter": recruiter, "owner of another organization": foreign, "zero": {}} { + err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, organization, membership) + }) + if !errors.Is(err, domain.ErrInvalidMembership) { + t.Fatalf("CreateWithOwner(%s) error = %v, want ErrInvalidMembership", name, err) + } + } + fixture.assertNothingStored(t) + + // Success stores all three. + fixture.create(t, creator, fixture.completeProfile(t, "ООО Пример"), now) + assertRowCount(ctx, t, pool, organizationsTable, 1) + assertRowCount(ctx, t, pool, organizationRepresentativesTable, 2) + assertRowCount(ctx, t, pool, membershipsTable, 1) + }) + + t.Run("the database refuses to commit an organization without an active owner", func(t *testing.T) { + reset(t) + member := fixture.employer(t, "member@example.com") + insertOrganization := func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { + if _, err := tx.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES ($1, $2, $3) + ON CONFLICT (founder_account_id) DO NOTHING`, uuid.New(), member.ID, now); err != nil { + return err + } + _, err := tx.Exec(ctx, ` + INSERT INTO organizations ( + id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id + ) VALUES ($1, 'ООО Без владельца', 'e0', 'confirmed_email', $2, 1, $2, $2, + (SELECT id FROM holdings WHERE founder_account_id = $3))`, id, now, member.ID) + return err + } + insertMember := func(ctx context.Context, tx pgx.Tx, organizationID uuid.UUID, role, state string) error { + _, err := tx.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $6)`, uuid.New(), organizationID, member.ID, role, state, now) + return err + } + for _, test := range []struct { + name string + work func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error + }{ + {"no membership at all", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { return insertOrganization(ctx, tx, id) }}, + {"only a recruiter", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { + if err := insertOrganization(ctx, tx, id); err != nil { + return err + } + return insertMember(ctx, tx, id, "recruiter", "active") + }}, + {"an owner that is removed in the same transaction", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { + if err := insertOrganization(ctx, tx, id); err != nil { + return err + } + if err := insertMember(ctx, tx, id, "owner", "active"); err != nil { + return err + } + _, err := tx.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1`, id) + return err + }}, + {"only a suspended owner", func(ctx context.Context, tx pgx.Tx, id uuid.UUID) error { + if err := insertOrganization(ctx, tx, id); err != nil { + return err + } + return insertMember(ctx, tx, id, "owner", "suspended") + }}, + } { + t.Run(test.name, func(t *testing.T) { + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + t.Fatal("the unit of work has no PostgreSQL transaction") + } + return test.work(ctx, tx, uuid.New()) + }) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != organizationCheckViolation || pgError.ConstraintName != "organizations_owner_required" { + t.Fatalf("commit error = %v, want SQLSTATE %s on organizations_owner_required", err, organizationCheckViolation) + } + fixture.assertNothingStored(t) + }) + } + + // An active owner inserted after the organization, in the same + // transaction, satisfies the deferred check. + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, _ := postgresadapter.TransactionForIntegrationTest(unit) + id := uuid.New() + if err := insertOrganization(ctx, tx, id); err != nil { + return err + } + return insertMember(ctx, tx, id, "owner", "active") + }) + if err != nil { + t.Fatalf("organization with an owner in one transaction error = %v", err) + } + assertRowCount(ctx, t, pool, organizationsTable, 1) + }) + + t.Run("lists only the active organizations of the caller", func(t *testing.T) { + reset(t) + alice := fixture.employer(t, "alice@example.com") + bob := fixture.employer(t, "bob@example.com") + carol := fixture.employer(t, "carol@example.com") + at := func(minutes int) time.Time { return now.Add(time.Duration(minutes) * time.Minute) } + first := fixture.create(t, alice, fixture.completeProfile(t, "Первая Алисы"), at(1)) + bobs := fixture.create(t, bob, fixture.completeProfile(t, "Бобова"), at(2)) + third := fixture.create(t, alice, fixture.completeProfile(t, "Третья Алисы"), at(3)) + shared := fixture.create(t, bob, fixture.completeProfile(t, "Общая"), at(4)) + fixture.addMember(t, shared, alice, domain.OrganizationRoleRecruiter, at(5)) + suspended := fixture.create(t, bob, fixture.completeProfile(t, "Приостановленная"), at(6)) + fixture.addMember(t, suspended, alice, domain.OrganizationRoleHiringManager, at(7)) + fixture.setMembershipState(t, suspended.ID(), alice.ID, domain.MembershipStateSuspended) + left := fixture.create(t, bob, fixture.completeProfile(t, "Покинутая"), at(8)) + fixture.addMember(t, left, alice, domain.OrganizationRoleTechnicalExpert, at(9)) + fixture.setMembershipState(t, left.ID(), alice.ID, domain.MembershipStateLeft) + removed := fixture.create(t, bob, fixture.completeProfile(t, "Удаленная"), at(10)) + fixture.addMember(t, removed, alice, domain.OrganizationRoleRecruiter, at(11)) + fixture.setMembershipState(t, removed.ID(), alice.ID, domain.MembershipStateRemoved) + + page := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 10}) + wantOrder := []uuid.UUID{shared.ID(), third.ID(), first.ID()} + if got := organizationIDs(page); !slices.Equal(got, wantOrder) || page.HasMore { + t.Fatalf("Alice's organizations = %v (more %v), want %v newest membership first", got, page.HasMore, wantOrder) + } + if page.Items[0].Membership.Role() != domain.OrganizationRoleRecruiter || page.Items[1].Membership.Role() != domain.OrganizationRoleOwner || + page.Items[0].Organization.Name() != "Общая" || page.Items[0].Organization.VerificationLevel() != domain.OrganizationVerificationE0 || + page.Items[0].Membership.UserID() != alice.ID { + t.Fatalf("items = %+v, want each organization with Alice's own membership", page.Items) + } + + bobPage := fixture.list(t, outbound.OrganizationListQuery{UserID: bob.ID, Limit: 10}) + if got := organizationIDs(bobPage); len(got) != 5 || slices.Contains(got, first.ID()) || slices.Contains(got, third.ID()) || !slices.Contains(got, bobs.ID()) { + t.Fatalf("Bob's organizations = %v, want his five and none of Alice's own", got) + } + if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: carol.ID, Limit: 10})); len(got) != 0 { + t.Fatalf("Carol's organizations = %v, want none", got) + } + if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: uuid.New(), Limit: 10})); len(got) != 0 { + t.Fatalf("an unknown account's organizations = %v, want none", got) + } + + // Paging follows the same order without a gap or a repeat. + firstPage := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 2}) + if !firstPage.HasMore || len(firstPage.Items) != 2 { + t.Fatalf("first page = %d items (more %v), want 2 and more", len(firstPage.Items), firstPage.HasMore) + } + last := outbound.OrganizationPositionOf(firstPage.Items[1]) + secondPage := fixture.list(t, outbound.OrganizationListQuery{UserID: alice.ID, Limit: 2, After: &last}) + if got := append(organizationIDs(firstPage), organizationIDs(secondPage)...); !slices.Equal(got, wantOrder) || secondPage.HasMore { + t.Fatalf("pages = %v (more %v), want %v and the end", got, secondPage.HasMore, wantOrder) + } + + // Memberships created at the same instant order by the organization. + tie := fixture.create(t, carol, fixture.completeProfile(t, "Ничья А"), at(20)) + tieB := fixture.create(t, carol, fixture.completeProfile(t, "Ничья Б"), at(20)) + wantTie := []uuid.UUID{tie.ID(), tieB.ID()} + slices.SortFunc(wantTie, func(left, right uuid.UUID) int { return strings.Compare(right.String(), left.String()) }) + if got := organizationIDs(fixture.list(t, outbound.OrganizationListQuery{UserID: carol.ID, Limit: 10})); !slices.Equal(got, wantTie) { + t.Fatalf("tied memberships = %v, want %v by organization ID descending", got, wantTie) + } + + for name, query := range map[string]outbound.OrganizationListQuery{ + "nil user": {Limit: 10}, + "zero limit": {UserID: alice.ID}, + "limit too large": {UserID: alice.ID, Limit: outbound.MaxOrganizationPageSize + 1}, + "zero position": {UserID: alice.ID, Limit: 10, After: &outbound.OrganizationListPosition{}}, + "position without an organization": {UserID: alice.ID, Limit: 10, After: &outbound.OrganizationListPosition{JoinedAt: now}}, + } { + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Organizations().ListForUser(ctx, query) + return err + }) + if !errors.Is(err, domain.ErrInvalidMembership) { + t.Fatalf("ListForUser(%s) error = %v, want ErrInvalidMembership", name, err) + } + } + }) + + t.Run("only an active member reads an organization, and a revoked membership closes the next read", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + outsider := fixture.employer(t, "outsider@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now) + stored := fixture.employer(t, "former@example.com") + fixture.addMember(t, organization, stored, domain.OrganizationRoleRecruiter, now.Add(time.Minute)) + + for name, userID := range map[string]uuid.UUID{"an account that is no member": outsider.ID, "an unknown account": uuid.New()} { + if _, _, err := fixture.read(userID, organization.ID()); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("GetForMember(%s) error = %v, want ErrOrganizationNotFound", name, err) + } + } + if _, _, err := fixture.read(owner.ID, uuid.New()); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("GetForMember(unknown organization) error = %v, want ErrOrganizationNotFound", err) + } + + if _, membership, err := fixture.read(stored.ID, organization.ID()); err != nil || membership.Role() != domain.OrganizationRoleRecruiter { + t.Fatalf("GetForMember(recruiter) = %+v, %v, want the recruiter membership", membership, err) + } + for _, state := range []domain.MembershipState{domain.MembershipStateSuspended, domain.MembershipStateRemoved, domain.MembershipStateLeft} { + fixture.setMembershipState(t, organization.ID(), stored.ID, state) + if _, _, err := fixture.read(stored.ID, organization.ID()); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("GetForMember(%s member) error = %v, want ErrOrganizationNotFound", state, err) + } + // The membership row is still readable in any state for the + // application that manages members. + membership, err := fixture.getMembership(organization.ID(), stored.ID) + if err != nil || membership.State() != state || membership.GrantsAccess() { + t.Fatalf("Get(%s membership) = %+v, %v, want the stored state without access", state, membership, err) + } + } + fixture.setMembershipState(t, organization.ID(), stored.ID, domain.MembershipStateActive) + if _, _, err := fixture.read(stored.ID, organization.ID()); err != nil { + t.Fatalf("GetForMember(restored member) error = %v", err) + } + }) + + t.Run("updates the profile over the version read and never touches the verification", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Старое Имя"), now) + later := now.Add(time.Hour) + + changed := mustOrganizationProfile(t, domain.OrganizationProfileInput{ + Name: "ООО Новое Имя", + Contacts: domain.OrganizationContactsInput{Telegram: "@new_careers"}, + Representatives: []domain.OrganizationRepresentativeInput{ + {Name: "Виктор Новый", JobTitle: "Директор"}, + }, + }) + updated := fixture.update(t, owner.ID, organization, changed, later) + if updated.Version() != 2 || updated.Profile().Name() != "ООО Новое Имя" || !updated.UpdatedAt().Equal(later) || !updated.CreatedAt().Equal(now) { + t.Fatalf("updated = %v, want version 2 with the new name at the new time", updated) + } + read, _, err := fixture.read(owner.ID, organization.ID()) + if err != nil { + t.Fatalf("GetForMember() error = %v", err) + } + profile := read.Profile() + if !profile.Equal(changed) || profile.Description() != "" || profile.Sphere() != "" || profile.Contacts().Website() != "" || + profile.Contacts().Telegram() != "@new_careers" || len(profile.Representatives()) != 1 { + t.Fatalf("stored profile = %+v, want the replaced profile with the cleared fields unset", profile) + } + if read.Version() != 2 || !sameVerification(read.Verification(), organization.Verification()) { + t.Fatalf("stored organization = %v, want version 2 and the unchanged verification", read) + } + + // A level that a verification process set stays through profile edits. + if _, err := pool.Exec(ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, organization.ID(), later); err != nil { + t.Fatalf("simulate a verification process: %v", err) + } + again := fixture.update(t, owner.ID, read, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "ООО Третье Имя"}), later.Add(time.Hour)) + if again.Version() != 3 || again.Verification().Level() != domain.OrganizationVerificationE1 || + again.Verification().Basis() != domain.OrganizationBasisCorporateDomain || !again.Verification().ChangedAt().Equal(later) { + t.Fatalf("after the profile edit = %v, want version 3 and the level e1 set by the process", again) + } + var level, basis string + if err := pool.QueryRow(ctx, `SELECT verification_level, verification_basis FROM organizations WHERE id = $1`, organization.ID()).Scan(&level, &basis); err != nil || + level != "e1" || basis != "corporate_domain" { + t.Fatalf("stored verification = %s %s, %v, want e1 corporate_domain", level, basis, err) + } + }) + + t.Run("a stale version, a non-manager, and a non-member change nothing", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + recruiter := fixture.employer(t, "recruiter@example.com") + suspendedOwner := fixture.employer(t, "suspended@example.com") + outsider := fixture.employer(t, "outsider@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now) + fixture.addMember(t, organization, recruiter, domain.OrganizationRoleRecruiter, now.Add(time.Minute)) + fixture.addMember(t, organization, suspendedOwner, domain.OrganizationRoleOwner, now.Add(time.Minute)) + fixture.setMembershipState(t, organization.ID(), suspendedOwner.ID, domain.MembershipStateSuspended) + changed, err := organization.ApplyProfile(mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Чужая правка"}), now.Add(time.Hour)) + if err != nil { + t.Fatalf("ApplyProfile() error = %v", err) + } + + for _, test := range []struct { + name string + actorID uuid.UUID + want error + }{ + {"a recruiter", recruiter.ID, outbound.ErrOrganizationManagerRequired}, + {"a suspended owner", suspendedOwner.ID, outbound.ErrOrganizationNotFound}, + {"an account that is no member", outsider.ID, outbound.ErrOrganizationNotFound}, + {"an unknown account", uuid.New(), outbound.ErrOrganizationNotFound}, + } { + _, err := fixture.tryUpdate(test.actorID, changed) + if !errors.Is(err, test.want) { + t.Fatalf("UpdateProfile(%s) error = %v, want %v", test.name, err, test.want) + } + } + + // Two owners read version 1; the second write is stale. + first := fixture.update(t, owner.ID, organization, mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Первая правка"}), now.Add(time.Hour)) + if first.Version() != 2 { + t.Fatalf("first update version = %d, want 2", first.Version()) + } + if _, err := fixture.tryUpdate(owner.ID, changed); !errors.Is(err, outbound.ErrOrganizationVersionConflict) { + t.Fatalf("UpdateProfile(stale version) error = %v, want ErrOrganizationVersionConflict", err) + } + // The order of the checks: an outsider with a stale version learns + // nothing about the version. + if _, err := fixture.tryUpdate(outsider.ID, changed); !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("UpdateProfile(outsider, stale version) error = %v, want ErrOrganizationNotFound", err) + } + + read, _, err := fixture.read(owner.ID, organization.ID()) + if err != nil { + t.Fatalf("GetForMember() error = %v", err) + } + if read.Profile().Name() != "Первая правка" || read.Version() != 2 || len(read.Profile().Representatives()) != 0 { + t.Fatalf("stored organization = %v, want only the first update", read) + } + + for name, build := range map[string]func() (domain.Organization, uuid.UUID){ + "a zero organization": func() (domain.Organization, uuid.UUID) { return domain.Organization{}, owner.ID }, + "a nil actor": func() (domain.Organization, uuid.UUID) { return read, uuid.Nil }, + } { + organization, actor := build() + if _, err := fixture.tryUpdate(actor, organization); !errors.Is(err, domain.ErrInvalidOrganization) { + t.Fatalf("UpdateProfile(%s) error = %v, want ErrInvalidOrganization", name, err) + } + } + }) + + t.Run("of concurrent updates from one version exactly one wins", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now) + concurrent := postgresadapter.NewTransactor(env.newPoolWithMaxConns(ctx, t, concurrentOrganizationUpdates+1)) + + errs := make([]error, concurrentOrganizationUpdates) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range concurrentOrganizationUpdates { + group.Go(func() { + <-start + profile, err := domain.NewOrganizationProfile(domain.OrganizationProfileInput{ + Name: "Правка " + string(rune('А'+index)), + Representatives: []domain.OrganizationRepresentativeInput{ + {Name: "Автор " + string(rune('А'+index)), JobTitle: "Должность"}, + }, + }) + if err != nil { + errs[index] = err + return + } + changed, err := organization.ApplyProfile(profile, now.Add(time.Hour)) + if err != nil { + errs[index] = err + return + } + errs[index] = concurrent.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Organizations().UpdateProfile(ctx, owner.ID, changed) + return err + }) + }) + } + close(start) + group.Wait() + + successes := 0 + for index, err := range errs { + switch { + case err == nil: + successes++ + case errors.Is(err, outbound.ErrOrganizationVersionConflict): + default: + t.Fatalf("update %d error = %v, want nil or ErrOrganizationVersionConflict", index, err) + } + } + if successes != 1 { + t.Fatalf("%d updates succeeded, want exactly 1", successes) + } + read, _, err := fixture.read(owner.ID, organization.ID()) + if err != nil { + t.Fatalf("GetForMember() error = %v", err) + } + // The winner's name and representative belong together. + winner := strings.TrimPrefix(read.Profile().Name(), "Правка ") + if read.Version() != 2 || len(read.Profile().Representatives()) != 1 || read.Profile().Representatives()[0].Name() != "Автор "+winner { + t.Fatalf("stored organization = %v, want one winner's name and representative at version 2", read) + } + }) + + t.Run("a revocation that commits while an update waits stops the update", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + second := fixture.employer(t, "second@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now) + fixture.addMember(t, organization, second, domain.OrganizationRoleOwner, now.Add(time.Minute)) + changed, err := organization.ApplyProfile(mustOrganizationProfile(t, domain.OrganizationProfileInput{Name: "Правка отозванного"}), now.Add(time.Hour)) + if err != nil { + t.Fatalf("ApplyProfile() error = %v", err) + } + + // A transaction revokes the second owner and stays open, holding the + // row lock of the membership. + revoker := startHeldTransaction(ctx, t, fixture.transactor, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, _ := postgresadapter.TransactionForIntegrationTest(unit) + _, err := tx.Exec(ctx, `UPDATE memberships SET state = 'removed' WHERE organization_id = $1 AND user_id = $2`, organization.ID(), second.ID) + return err + }, true) + revoker.awaitHeld(ctx, t) + + const applicationName = "organization-update-waiter" + waiting := postgresadapter.NewTransactor(env.newPoolWithApplicationName(ctx, t, applicationName)) + result := make(chan error, 1) + go func() { + result <- waiting.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + _, err := unit.Organizations().UpdateProfile(ctx, second.ID, changed) + return err + }) + }() + if event, ok := waitForLockWait(ctx, pool, applicationName); !ok { + t.Fatalf("the update did not wait for the membership lock, last wait event %q", event) + } + if err := revoker.finish(); err != nil { + t.Fatalf("revoking transaction error = %v", err) + } + + // The update saw the committed revocation and wrote nothing. + if err := <-result; !errors.Is(err, outbound.ErrOrganizationNotFound) { + t.Fatalf("UpdateProfile(revoked while waiting) error = %v, want ErrOrganizationNotFound", err) + } + read, _, err := fixture.read(owner.ID, organization.ID()) + if err != nil || read.Version() != 1 || read.Profile().Name() != "ООО Пример" { + t.Fatalf("stored organization = %v, %v, want it unchanged at version 1", read, err) + } + }) + + t.Run("keeps the role off the organization and refuses malformed rows", func(t *testing.T) { + reset(t) + // The role and the members live only in memberships. + var columns []string + rows, err := pool.Query(ctx, ` + SELECT column_name FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'organizations' ORDER BY ordinal_position`) + if err != nil { + t.Fatalf("list organization columns: %v", err) + } + columns, err = pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("read organization columns: %v", err) + } + for _, column := range columns { + if strings.Contains(column, "role") || strings.Contains(column, "owner") || strings.Contains(column, "member") || strings.Contains(column, "user") { + t.Fatalf("organizations has the column %q; roles and members belong to memberships", column) + } + } + + user := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, user, fixture.completeProfile(t, "ООО Пример"), now) + insertOrganization := func(name, verificationLevel, basis string, version int) error { + // The holding of the owner exists, so only the checked columns can fail. + _, err := pool.Exec(ctx, ` + INSERT INTO organizations ( + id, name, verification_level, verification_basis, verification_changed_at, version, created_at, updated_at, holding_id + ) VALUES ($1, $2, $3, $4, $5, $6, $5, $5, + (SELECT id FROM holdings WHERE founder_account_id = $7))`, uuid.New(), name, verificationLevel, basis, now, version, user.ID) + return err + } + for _, test := range []struct { + name string + err error + constraint string + }{ + {"empty name", insertOrganization("", "e0", "confirmed_email", 1), "organizations_name_format"}, + {"padded name", insertOrganization(" ООО", "e0", "confirmed_email", 1), "organizations_name_format"}, + {"name with a line break", insertOrganization("ООО\nПример", "e0", "confirmed_email", 1), "organizations_name_format"}, + {"name over 200 characters", insertOrganization(strings.Repeat("я", 201), "e0", "confirmed_email", 1), "organizations_name_format"}, + {"unknown level", insertOrganization("ООО", "e4", "confirmed_email", 1), "organizations_verification_known"}, + {"level with the basis of another", insertOrganization("ООО", "e0", "corporate_domain", 1), "organizations_verification_known"}, + {"version zero", insertOrganization("ООО", "e0", "confirmed_email", 0), "organizations_version_positive"}, + } { + assertSQLError(t, test.name, test.err, organizationCheckViolation, test.constraint) + } + for _, test := range []struct { + name string + column string + value string + constraint string + }{ + {"description with a padded end", "description", "текст ", "organizations_description_format"}, + {"description with a control character", "description", "текст\x07", "organizations_description_format"}, + {"sphere with a line break", "sphere", "а\nб", "organizations_sphere_format"}, + {"website over http", "contact_website", "http://example.com", "organizations_contact_website_format"}, + {"website with credentials", "contact_website", "https://user@example.com", "organizations_contact_website_format"}, + {"email with a space", "contact_email", "a b@example.com", "organizations_contact_email_format"}, + {"phone without a plus", "contact_phone", "74950000000", "organizations_contact_phone_format"}, + {"telegram without an at sign", "contact_telegram", "careers_team", "organizations_contact_telegram_format"}, + } { + _, err := pool.Exec(ctx, `UPDATE organizations SET `+test.column+` = $2 WHERE id = $1`, organization.ID(), test.value) + assertSQLError(t, test.name, err, organizationCheckViolation, test.constraint) + } + // Each level takes its own bases, and the composite key of the + // memberships can be the target of a later foreign key. + for _, test := range []struct { + level, basis string + ok bool + }{ + {"e1", "corporate_domain", true}, + {"e2", "requisites_and_authority", true}, + {"e3", "manual_review", true}, + {"e3", "partner_status", true}, + {"e2", "manual_review", false}, + {"e2", "corporate_domain", false}, + {"e3", "requisites_and_authority", false}, + {"e3", "confirmed_email", false}, + {"e1", "partner_status", false}, + } { + _, err := pool.Exec(ctx, `UPDATE organizations SET verification_level = $2, verification_basis = $3 WHERE id = $1`, organization.ID(), test.level, test.basis) + if test.ok && err != nil { + t.Fatalf("level %s with basis %s error = %v, want it accepted", test.level, test.basis, err) + } + if !test.ok { + assertSQLError(t, "level "+test.level+" with basis "+test.basis, err, organizationCheckViolation, "organizations_verification_known") + } + } + if _, err := pool.Exec(ctx, `UPDATE organizations SET verification_level = 'e0', verification_basis = 'confirmed_email' WHERE id = $1`, organization.ID()); err != nil { + t.Fatalf("reset the level: %v", err) + } + composite, err := pool.Begin(ctx) + if err != nil { + t.Fatalf("begin: %v", err) + } + defer func() { _ = composite.Rollback(ctx) }() + if _, err := composite.Exec(ctx, ` + CREATE TABLE membership_reference ( + organization_id uuid NOT NULL, + membership_id uuid NOT NULL, + FOREIGN KEY (organization_id, membership_id) REFERENCES memberships (organization_id, id) + )`); err != nil { + t.Fatalf("composite foreign key on memberships: %v", err) + } + if _, err := composite.Exec(ctx, ` + INSERT INTO membership_reference SELECT organization_id, id FROM memberships WHERE organization_id = $1`, organization.ID()); err != nil { + t.Fatalf("reference a membership of its own organization: %v", err) + } + if _, err := composite.Exec(ctx, ` + INSERT INTO membership_reference SELECT $1::uuid, id FROM memberships WHERE organization_id = $2`, uuid.New(), organization.ID()); err == nil { + t.Fatal("a membership was referenced under another organization") + } + _ = composite.Rollback(ctx) + + // A value in the contract format passes. + if _, err := pool.Exec(ctx, `UPDATE organizations SET contact_website = 'https://example.com/path?q=1', contact_phone = '+74950000000' WHERE id = $1`, organization.ID()); err != nil { + t.Fatalf("update with valid contacts: %v", err) + } + _, err = pool.Exec(ctx, `UPDATE organizations SET updated_at = created_at - interval '1 second' WHERE id = $1`, organization.ID()) + assertSQLError(t, "update before creation", err, organizationCheckViolation, "organizations_timestamps_after_creation") + + for _, test := range []struct { + name string + role string + state string + constraint string + }{ + {"unknown role", "admin", "active", "memberships_role_known"}, + {"manager as a role of the PRD wording", "manager", "active", "memberships_role_known"}, + {"unknown state", "recruiter", "invited", "memberships_state_known"}, + } { + second := fixture.employer(t, test.role+test.state+"@example.com") + _, err := pool.Exec(ctx, ` + INSERT INTO memberships (id, organization_id, user_id, role, state, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $6)`, uuid.New(), organization.ID(), second.ID, test.role, test.state, now) + assertSQLError(t, test.name, err, organizationCheckViolation, test.constraint) + } + _, err = pool.Exec(ctx, ` + INSERT INTO organization_representatives (organization_id, ordinal, name, job_title) + VALUES ($1, 10, 'Имя', 'Должность')`, organization.ID()) + assertSQLError(t, "eleventh representative", err, organizationCheckViolation, "organization_representatives_ordinal_range") + _, err = pool.Exec(ctx, ` + INSERT INTO organization_representatives (organization_id, ordinal, name, job_title) + VALUES ($1, 5, 'Имя', ' Должность')`, organization.ID()) + assertSQLError(t, "padded job title", err, organizationCheckViolation, "organization_representatives_job_title_format") + }) + + t.Run("an account and an organization with memberships cannot be deleted", func(t *testing.T) { + reset(t) + owner := fixture.employer(t, "owner@example.com") + organization := fixture.create(t, owner, fixture.completeProfile(t, "ООО Пример"), now) + + _, err := pool.Exec(ctx, `DELETE FROM users WHERE id = $1`, owner.ID) + assertSQLError(t, "delete of an account with a membership", err, organizationRestrictViolation, "memberships_user_id_fkey") + _, err = pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, organization.ID()) + assertSQLError(t, "delete of an organization with a member", err, organizationRestrictViolation, "memberships_organization_id_fkey") + assertRowCount(ctx, t, pool, organizationsTable, 1) + assertRowCount(ctx, t, pool, membershipsTable, 1) + + // Once the memberships are gone the representatives go with the + // organization. + if _, err := pool.Exec(ctx, `DELETE FROM memberships WHERE organization_id = $1`, organization.ID()); err != nil { + t.Fatalf("delete the memberships: %v", err) + } + if _, err := pool.Exec(ctx, `DELETE FROM organizations WHERE id = $1`, organization.ID()); err != nil { + t.Fatalf("delete the organization: %v", err) + } + assertRowCount(ctx, t, pool, organizationRepresentativesTable, 0) + }) +} + +func (fixture organizationFixture) employer(t *testing.T, email string) domain.User { + t.Helper() + return fixture.identity.createUser(t, email, domain.ScenarioEmployer, fixture.now.Add(-time.Hour)) +} + +func mustOrganizationProfile(t *testing.T, input domain.OrganizationProfileInput) domain.OrganizationProfile { + t.Helper() + profile, err := domain.NewOrganizationProfile(input) + if err != nil { + t.Fatalf("NewOrganizationProfile() error = %v", err) + } + return profile +} + +func (fixture organizationFixture) completeProfile(t *testing.T, name string) domain.OrganizationProfile { + t.Helper() + return mustOrganizationProfile(t, domain.OrganizationProfileInput{ + Name: name, + Description: "Платежный сервис для малого бизнеса.\nСобственное ядро платежей.", + Sphere: "Платежи и финансовые сервисы", + Contacts: domain.OrganizationContactsInput{ + Website: "https://payments.example.com", Email: "careers@payments.example.com", Phone: "+74950000000", Telegram: "@payments_careers", + }, + Representatives: []domain.OrganizationRepresentativeInput{ + {Name: "Анна Тестова", JobTitle: "Руководитель по подбору"}, + {Name: "Борис Образцов", JobTitle: "Технический директор"}, + }, + }) +} + +func (fixture organizationFixture) newOrganization(t *testing.T, profile domain.OrganizationProfile, at time.Time) domain.Organization { + t.Helper() + organization, err := domain.NewOrganization(profile, at) + if err != nil { + t.Fatalf("NewOrganization() error = %v", err) + } + return organization +} + +// create stores an organization with its owner in one transaction. +func (fixture organizationFixture) create(t *testing.T, owner domain.User, profile domain.OrganizationProfile, at time.Time) domain.Organization { + t.Helper() + organization := fixture.newOrganization(t, profile, at) + membership, err := domain.NewOwnerMembership(organization.ID(), owner.ID, at) + if err != nil { + t.Fatalf("NewOwnerMembership() error = %v", err) + } + err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Organizations().CreateWithOwner(ctx, organization, membership) + }) + if err != nil { + t.Fatalf("CreateWithOwner(%q) error = %v", profile.Name(), err) + } + return organization +} + +func (fixture organizationFixture) addMember(t *testing.T, organization domain.Organization, user domain.User, role domain.OrganizationRole, at time.Time) { + t.Helper() + membership, err := domain.NewMembership(domain.MembershipInput{OrganizationID: organization.ID(), UserID: user.ID, Role: role, At: at}) + if err != nil { + t.Fatalf("NewMembership() error = %v", err) + } + err = fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Memberships().Insert(ctx, membership) + }) + if err != nil { + t.Fatalf("Insert(%s membership) error = %v", role, err) + } +} + +// setMembershipState ends or restores a membership the way the planned +// member management will; the repository has no such method yet. +func (fixture organizationFixture) setMembershipState(t *testing.T, organizationID, userID uuid.UUID, state domain.MembershipState) { + t.Helper() + if _, err := fixture.pool.Exec(fixture.ctx, `UPDATE memberships SET state = $3 WHERE organization_id = $1 AND user_id = $2`, organizationID, userID, string(state)); err != nil { + t.Fatalf("set the membership state to %s: %v", state, err) + } +} + +func (fixture organizationFixture) read(userID, organizationID uuid.UUID) (domain.Organization, domain.Membership, error) { + var ( + organization domain.Organization + membership domain.Membership + ) + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + organization, membership, err = unit.Organizations().GetForMember(ctx, organizationID, userID) + return err + }) + return organization, membership, err +} + +func (fixture organizationFixture) getMembership(organizationID, userID uuid.UUID) (domain.Membership, error) { + var membership domain.Membership + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + membership, err = unit.Memberships().Get(ctx, organizationID, userID) + return err + }) + return membership, err +} + +func (fixture organizationFixture) list(t *testing.T, query outbound.OrganizationListQuery) outbound.OrganizationPage { + t.Helper() + var page outbound.OrganizationPage + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + page, err = unit.Organizations().ListForUser(ctx, query) + return err + }) + if err != nil { + t.Fatalf("ListForUser() error = %v", err) + } + return page +} + +// update applies profile to organization as of its version and stores it. +func (fixture organizationFixture) update( + t *testing.T, + actorID uuid.UUID, + organization domain.Organization, + profile domain.OrganizationProfile, + at time.Time, +) domain.Organization { + t.Helper() + changed, err := organization.ApplyProfile(profile, at) + if err != nil { + t.Fatalf("ApplyProfile() error = %v", err) + } + updated, err := fixture.tryUpdate(actorID, changed) + if err != nil { + t.Fatalf("UpdateProfile() error = %v", err) + } + return updated +} + +func (fixture organizationFixture) tryUpdate(actorID uuid.UUID, organization domain.Organization) (domain.Organization, error) { + var updated domain.Organization + err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + updated, err = unit.Organizations().UpdateProfile(ctx, actorID, organization) + return err + }) + return updated, err +} + +func (fixture organizationFixture) assertNothingStored(t *testing.T) { + t.Helper() + for _, table := range organizationTables { + assertRowCount(fixture.ctx, t, fixture.pool, table, 0) + } +} + +func organizationIDs(page outbound.OrganizationPage) []uuid.UUID { + ids := make([]uuid.UUID, 0, len(page.Items)) + for _, item := range page.Items { + ids = append(ids, item.Organization.ID()) + } + return ids +} + +// sameVerification compares the instants, because a stored time carries +// another location than the application clock that wrote it. +func sameVerification(left, right domain.OrganizationVerification) bool { + return left.Level() == right.Level() && left.Basis() == right.Basis() && left.ChangedAt().Equal(right.ChangedAt()) +} diff --git a/backend/integration_test/outbox_relay_test.go b/backend/integration_test/outbox_relay_test.go new file mode 100644 index 0000000..a074ea5 --- /dev/null +++ b/backend/integration_test/outbox_relay_test.go @@ -0,0 +1,768 @@ +//go:build integration + +package integration_test + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/twmb/franz-go/pkg/kgo" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/kafka" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/outboxrelay" + "lincodex/backend/internal/worker/retry" +) + +const ( + relayTestTimeout = 5 * time.Minute + // relayProduceTimeout keeps outage passes short; it is the smallest + // value franz-go accepts plus a margin for a loaded test machine. + relayProduceTimeout = 2 * time.Second + // relayLongProduceTimeout outlasts the shutdown timeout many times, so a + // relay that stops in time proves the shutdown timeout canceled its pass. + relayLongProduceTimeout = 30 * time.Second + // relayShutdownMargin covers the rollback and scheduling after the + // shutdown timeout, far below relayLongProduceTimeout. + relayShutdownMargin = 5 * time.Second + // relayStatementTimeout and relayIdleTimeout are the server-side bounds + // of the shared store; the idle bound outlasts the longest publish. + relayStatementTimeout = 5 * time.Second + relayIdleTimeout = relayLongProduceTimeout + relayStatementTimeout + // shortIdleTimeout is the idle bound of the case that lets the server + // end a silent claim; shortIdleSilence outlasts it. + shortIdleTimeout = 300 * time.Millisecond + shortIdleSilence = 2 * time.Second + // idleInTransactionTimeoutCode is the SQLSTATE of a session that the + // server ended for idle_in_transaction_session_timeout. + idleInTransactionTimeoutCode = "25P03" + // relayBacklogInterval refreshes the backlog metrics often in tests. + relayBacklogInterval = 50 * time.Millisecond + relayTopicPartitions = 3 + relayBatchSize = 5 + relayPollInterval = 20 * time.Millisecond + relayBackoffInitial = 50 * time.Millisecond + relayBackoffMax = 500 * time.Millisecond + relayShutdownTimeout = time.Second + // relayRecoveryTimeout bounds reconnection after the broker resumes. + relayRecoveryTimeout = time.Minute + relayDrainTimeout = time.Minute + competingRelays = 2 + // More aggregates than one batch holds, so a second relay finds + // unlocked aggregate heads while the first relay's pass is in progress. + competingAggregates = 12 + competingVersions = 8 + // competingPublishDelay stretches each pass, as a remote broker would, + // so the relays' passes overlap. + competingPublishDelay = 10 * time.Millisecond + // relayLockTimeout makes a claim fail instead of waiting if SKIP LOCKED + // ever waited for a row lock. + relayLockTimeout = 500 * time.Millisecond +) + +// relayHarness owns the database side of relay tests: the pool, the +// business-transaction writer, and the relay store. +type relayHarness struct { + env *testEnvironment + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + store *postgresadapter.OutboxRelayStore +} + +func TestOutboxRelay(t *testing.T) { + env := bootstrap(t, postgresService, kafkaService) + ctx, cancel := context.WithTimeout(t.Context(), relayTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + if _, err := pool.Exec(ctx, createTestAccountsTable); err != nil { + t.Fatalf("create test aggregate table: %v", err) + } + harness := &relayHarness{ + env: env, + pool: pool, + transactor: postgresadapter.NewTransactor(pool), + store: postgresadapter.NewOutboxRelayStore(pool, relayStoreTimeouts), + } + // Subtests share tables and run sequentially; each starts from empty + // tables and uses its own topic. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, outboxEventsTable, testAccountsTable) + } + + t.Run("publishes a committed event as an envelope and marks it", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + harness.save(ctx, t, account, event) + + relay := harness.newRelay(harness.newPublisher(t, topic)) + result, err := relay.PublishPending(ctx) + if err != nil || result != (outboxrelay.PassResult{Claimed: 1, Published: 1}) { + t.Fatalf("PublishPending() = %+v, %v; want one event published", result, err) + } + records := env.consumeKafkaRecords(ctx, t, topic, 1) + stored := readOutboxEvents(ctx, t, pool) + assertEnvelope(t, records[0], stored[0]) + if stored[0].publishedAt == nil { + t.Fatal("published event is not marked") + } + result, err = relay.PublishPending(ctx) + if err != nil || result.Claimed != 0 { + t.Fatalf("second PublishPending() = %+v, %v; want nothing to claim", result, err) + } + }) + + t.Run("a Kafka outage keeps events pending without affecting business writes, and recovery publishes them", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + relay := harness.newRelay(harness.newPublisher(t, topic)) + before := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + harness.save(ctx, t, before, newAccountEvent(t, before)) + + resume := env.pauseKafka(ctx, t) + // A business transaction only writes the outbox, so it commits while + // the broker is unavailable. + during := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + harness.save(ctx, t, during, newAccountEvent(t, during)) + result, err := relay.PublishPending(ctx) + if err == nil || result.Published != 0 || result.Claimed != 2 { + t.Fatalf("PublishPending() during the outage = %+v, %v; want two claimed, none published, and an error", result, err) + } + t.Logf("pass during the outage failed as expected: %v", err) + assertUnpublished(ctx, t, pool, 2) + assertAccount(ctx, t, pool, before) + assertAccount(ctx, t, pool, during) + + resume() + published := harness.publishUntilDrained(ctx, t, relay) + if published != 2 { + t.Fatalf("published %d events after recovery, want 2", published) + } + assertUnpublished(ctx, t, pool, 0) + stored := readOutboxEvents(ctx, t, pool) + // The broker may also store a record from the request that was in + // flight when it froze; consumers deduplicate it by event_id. + received := consumeUntilEventIDs(ctx, t, env, topic, eventIDs(stored)) + for _, event := range stored { + assertEnvelope(t, received[event.eventID][0], event) + } + }) + + t.Run("a relay that dies between publish and mark republishes the same event_id", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + harness.save(ctx, t, account, event) + + // The publisher really produces and then ends the pass context, as a + // killed process would, so the mark never commits. + passCtx, killPass := context.WithCancel(ctx) + defer killPass() + dying := harness.newRelay(crashAfterPublish{EventPublisher: harness.newPublisher(t, topic), crash: killPass}) + result, err := dying.PublishPending(passCtx) + if !errors.Is(err, context.Canceled) || result.Published != 0 { + t.Fatalf("PublishPending() of the dying relay = %+v, %v; want context.Canceled and nothing marked", result, err) + } + assertUnpublished(ctx, t, pool, 1) + first := env.consumeKafkaRecords(ctx, t, topic, 1) + assertEnvelope(t, first[0], readOutboxEvents(ctx, t, pool)[0]) + + restarted := harness.newRelay(harness.newPublisher(t, topic)) + result, err = restarted.PublishPending(ctx) + if err != nil || result != (outboxrelay.PassResult{Claimed: 1, Published: 1}) { + t.Fatalf("PublishPending() after restart = %+v, %v; want the event published", result, err) + } + assertUnpublished(ctx, t, pool, 0) + both := env.consumeKafkaRecords(ctx, t, topic, 2) + for _, record := range both { + if got := headerValue(record, "event_id"); got != event.EventID().String() { + t.Fatalf("record event_id = %s, want the original %s", got, event.EventID()) + } + } + }) + + t.Run("a competing claim skips locked rows without waiting and never overtakes an aggregate", func(t *testing.T) { + reset(t) + first := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + firstNext := testAccount{id: first.id, version: 2, status: accountStatusArchived} + second := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + third := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + for _, account := range []testAccount{first, firstNext, second, third} { + harness.save(ctx, t, account, newAccountEvent(t, account)) + } + competitor := postgresadapter.NewOutboxRelayStore(env.newPoolWithLockTimeout(ctx, t, relayLockTimeout), relayStoreTimeouts) + + var held, competing []outbound.OutboxEvent + err := harness.store.ClaimPending(ctx, 2, func(ctx context.Context, events []outbound.OutboxEvent) []uuid.UUID { + held = events + // While this batch holds its row locks, another relay claims. + if err := competitor.ClaimPending(ctx, relayBatchSize, func(_ context.Context, events []outbound.OutboxEvent) []uuid.UUID { + competing = events + return ids(events) + }); err != nil { + t.Errorf("competing ClaimPending() error = %v", err) + } + return ids(events) + }) + if err != nil { + t.Fatalf("ClaimPending() error = %v", err) + } + assertClaimed(t, "first relay", held, first, second) + // The first aggregate's version 2 waits for version 1, which the + // first relay holds; the third aggregate is free. + assertClaimed(t, "competing relay", competing, third) + + var next []outbound.OutboxEvent + if err := harness.store.ClaimPending(ctx, relayBatchSize, func(_ context.Context, events []outbound.OutboxEvent) []uuid.UUID { + next = events + return ids(events) + }); err != nil { + t.Fatalf("next ClaimPending() error = %v", err) + } + assertClaimed(t, "next pass", next, firstNext) + assertUnpublished(ctx, t, pool, 0) + assertNoBusyConnections(t, pool) + }) + + t.Run("competing relays publish every event and keep each aggregate in version order", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + runCtx, stopRelays := context.WithCancel(ctx) + defer stopRelays() + var relays sync.WaitGroup + counters := make([]*publishedCounter, competingRelays) + for index := range competingRelays { + counters[index] = &publishedCounter{} + publisher := slowPublisher{EventPublisher: harness.newPublisher(t, topic), delay: competingPublishDelay} + relay := harness.newRelayWithMetrics(publisher, counters[index]) + relays.Go(func() { relay.Run(runCtx) }) + } + + // Writers append versions while the relays run, so claims race with + // commits as well as with each other. + var writers sync.WaitGroup + writeErrs := make([]error, competingAggregates) + for index := range competingAggregates { + writers.Go(func() { + id := uuid.New() + for version := int64(1); version <= competingVersions; version++ { + account := testAccount{id: id, version: version, status: fmt.Sprintf("v%d", version)} + event, err := newAccountEventE(account) + if err == nil { + err = harness.transactor.WithinTransaction(ctx, saveAccountWith(account, event)) + } + if err != nil { + writeErrs[index] = err + return + } + } + }) + } + writers.Wait() + for index, err := range writeErrs { + if err != nil { + t.Fatalf("writer %d error = %v", index, err) + } + } + waitForUnpublished(ctx, t, pool, 0) + stopRelays() + relays.Wait() + + stored := readOutboxEvents(ctx, t, pool) + if want := competingAggregates * competingVersions; len(stored) != want { + t.Fatalf("outbox has %d events, want %d", len(stored), want) + } + received := consumeUntilEventIDs(ctx, t, env, topic, eventIDs(stored)) + assertAggregateOrder(t, received) + for index, counter := range counters { + t.Logf("relay %d published %d events", index+1, counter.published.Load()) + } + }) + + t.Run("shutdown during a batch leaves unacknowledged events unpublished", func(t *testing.T) { + reset(t) + topic := env.createKafkaTopic(ctx, t, relayTopicPartitions) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + harness.save(ctx, t, account, newAccountEvent(t, account)) + + // The broker stays frozen and the produce timeout is far longer than + // the shutdown timeout, so only the shutdown timeout can end the pass + // in time; its transaction then rolls back. + resume := env.pauseKafka(ctx, t) + defer resume() + settings := harness.relayConfig(topic) + settings.RelayProduceTimeout = relayLongProduceTimeout + relay := harness.newRelay(harness.newPublisherWith(t, settings)) + runCtx, stopRelay := context.WithCancel(ctx) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + relay.Run(runCtx) + }() + waitForLockedOutboxRow(ctx, t, pool) + stopRelay() + stopStarted := time.Now() + select { + case <-stopped: + case <-time.After(relayShutdownTimeout + relayShutdownMargin): + t.Fatalf("relay did not stop within the %s shutdown timeout plus %s", relayShutdownTimeout, relayShutdownMargin) + } + if elapsed := time.Since(stopStarted); elapsed < relayShutdownTimeout { + t.Fatalf("relay stopped after %s, before the %s shutdown timeout could cancel the pass", elapsed, relayShutdownTimeout) + } + assertUnpublished(ctx, t, pool, 1) + assertNoBusyConnections(t, pool) + }) + + t.Run("the server ends a claim whose client stays silent past the idle timeout", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + harness.save(ctx, t, account, newAccountEvent(t, account)) + store := postgresadapter.NewOutboxRelayStore(pool, postgresadapter.OutboxRelayTimeouts{ + Statement: relayStatementTimeout, + IdleInTransaction: shortIdleTimeout, + }) + // The callback ignores its context, like a frozen process, and then + // reports the event as acknowledged. + err := store.ClaimPending(ctx, relayBatchSize, func(_ context.Context, events []outbound.OutboxEvent) []uuid.UUID { + time.Sleep(shortIdleSilence) + return ids(events) + }) + var stateError interface{ SQLState() string } + if !errors.As(err, &stateError) || stateError.SQLState() != idleInTransactionTimeoutCode { + t.Fatalf("ClaimPending() error = %v, want SQLSTATE %s from the idle timeout", err, idleInTransactionTimeoutCode) + } + assertUnpublished(ctx, t, pool, 1) + assertNoBusyConnections(t, pool) + }) + + t.Run("the backlog reports pending events and the age of the earliest one", func(t *testing.T) { + reset(t) + if backlog, err := harness.store.Backlog(ctx); err != nil || backlog != (outbound.OutboxBacklog{}) { + t.Fatalf("Backlog() of an empty outbox = %+v, %v; want zero values", backlog, err) + } + for range 2 { + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + harness.save(ctx, t, account, newAccountEvent(t, account)) + } + backlog, err := harness.store.Backlog(ctx) + if err != nil || backlog.Pending != 2 || backlog.OldestAge <= 0 { + t.Fatalf("Backlog() = %+v, %v; want 2 pending events with a positive age", backlog, err) + } + }) + + t.Run("prepare creates the events topic once and accepts an existing topic", func(t *testing.T) { + topic := newKafkaTopicName() + cleanupCtx := context.WithoutCancel(ctx) + t.Cleanup(func() { env.deleteKafkaTopic(cleanupCtx, t, topic) }) + settings := harness.relayConfig(topic) + settings.KafkaProvisionTopics = true + // The broker default replication factor and an explicit + // min.insync.replicas, as a production cluster would be configured. + settings.KafkaEventsTopicReplicationFactor = config.KafkaBrokerDefaultReplicationFactor + settings.KafkaEventsTopicMinInsyncReplicas = kafkaReplicationFactor + publisher, cleanup, err := kafka.NewPublisher(settings, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewPublisher() error = %v", err) + } + t.Cleanup(cleanup) + for attempt := range 2 { + if err := publisher.Prepare(ctx); err != nil { + t.Fatalf("Prepare() attempt %d error = %v", attempt+1, err) + } + } + topics, err := env.KafkaAdmin.ListTopics(ctx, topic) + if err != nil { + t.Fatalf("list topic: %v", err) + } + detail, ok := topics[topic] + if !ok || detail.Err != nil || len(detail.Partitions) != relayTopicPartitions || detail.Partitions.NumReplicas() != kafkaReplicationFactor { + t.Fatalf("topic %s: present %t, error %v, partitions %d, replicas %d; want %d partitions with the broker default replication", + topic, ok, detail.Err, len(detail.Partitions), detail.Partitions.NumReplicas(), relayTopicPartitions) + } + configs, err := env.KafkaAdmin.DescribeTopicConfigs(ctx, topic) + if err != nil { + t.Fatalf("describe topic configs: %v", err) + } + resource, err := configs.On(topic, nil) + if err != nil || resource.Err != nil { + t.Fatalf("topic %s configs: %v, %v", topic, err, resource.Err) + } + minInsync := "" + for _, entry := range resource.Configs { + // Only a topic-level value proves the relay set it; the broker + // default has the same number. + if entry.Key == "min.insync.replicas" && entry.Value != nil && entry.Source.String() == "DYNAMIC_TOPIC_CONFIG" { + minInsync = *entry.Value + } + } + if minInsync != fmt.Sprint(kafkaReplicationFactor) { + t.Fatalf("topic min.insync.replicas = %q, want a topic-level %d", minInsync, kafkaReplicationFactor) + } + }) +} + +// crashAfterPublish produces for real and then ends the pass, like a process +// killed between the broker acknowledgement and the mark. +type crashAfterPublish struct { + outbound.EventPublisher + + crash context.CancelFunc +} + +func (publisher crashAfterPublish) Publish(ctx context.Context, events []outbound.OutboxEvent) []error { + results := publisher.EventPublisher.Publish(ctx, events) + publisher.crash() + return results +} + +// slowPublisher delays every publish while the pass holds its row locks. +type slowPublisher struct { + outbound.EventPublisher + + delay time.Duration +} + +func (publisher slowPublisher) Publish(ctx context.Context, events []outbound.OutboxEvent) []error { + select { + case <-time.After(publisher.delay): + case <-ctx.Done(): + } + return publisher.EventPublisher.Publish(ctx, events) +} + +func (harness *relayHarness) relayConfig(topic string) config.Config { + settings := harness.env.Config + settings.KafkaEventsTopic = topic + settings.KafkaEventsTopicPartitions = relayTopicPartitions + settings.KafkaEventsTopicReplicationFactor = kafkaReplicationFactor + // Test topics are created by the test helpers. + settings.KafkaProvisionTopics = false + settings.RelayProduceTimeout = relayProduceTimeout + return settings +} + +func (harness *relayHarness) newPublisher(t *testing.T, topic string) *kafka.Publisher { + t.Helper() + return harness.newPublisherWith(t, harness.relayConfig(topic)) +} + +func (harness *relayHarness) newPublisherWith(t *testing.T, settings config.Config) *kafka.Publisher { + t.Helper() + publisher, cleanup, err := kafka.NewPublisher(settings, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("NewPublisher() error = %v", err) + } + t.Cleanup(cleanup) + return publisher +} + +// publishedCounter records how many events one relay published. +type publishedCounter struct { + published atomic.Int64 +} + +func (counter *publishedCounter) ObserveOutboxRelayPass(published, _ int) { + counter.published.Add(int64(published)) +} + +func (*publishedCounter) ObserveOutboxBacklog(outbound.OutboxBacklog) {} + +var relayStoreTimeouts = postgresadapter.OutboxRelayTimeouts{ + Statement: relayStatementTimeout, + IdleInTransaction: relayIdleTimeout, +} + +func (harness *relayHarness) newRelay(publisher outbound.EventPublisher) *outboxrelay.Relay { + return harness.newRelayWithMetrics(publisher, &publishedCounter{}) +} + +func (harness *relayHarness) newRelayWithMetrics(publisher outbound.EventPublisher, metrics outboxrelay.Metrics) *outboxrelay.Relay { + return outboxrelay.New(harness.store, publisher, metrics, slog.New(slog.DiscardHandler), outboxrelay.Settings{ + BatchSize: relayBatchSize, + PollInterval: relayPollInterval, + Backoff: retry.Backoff{Initial: relayBackoffInitial, Max: relayBackoffMax}, + ShutdownTimeout: relayShutdownTimeout, + BacklogInterval: relayBacklogInterval, + }) +} + +func (harness *relayHarness) save(ctx context.Context, t *testing.T, account testAccount, event domain.DomainEvent) { + t.Helper() + if err := harness.transactor.WithinTransaction(ctx, saveAccountWith(account, event)); err != nil { + t.Fatalf("save account %s v%d: %v", account.id, account.version, err) + } +} + +// publishUntilDrained runs passes until one claims nothing, tolerating the +// failures of a client that is still reconnecting, and returns the number of +// events published. +func (harness *relayHarness) publishUntilDrained(ctx context.Context, t *testing.T, relay *outboxrelay.Relay) int { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, relayRecoveryTimeout) + defer cancel() + published := 0 + var lastErr error + for { + result, err := relay.PublishPending(ctx) + published += result.Published + if err == nil && result.Claimed == 0 { + return published + } + if err != nil { + lastErr = err + } + select { + case <-ctx.Done(): + t.Fatalf("events still pending after recovery: published %d, last error %v", published, lastErr) + case <-time.After(relayBackoffInitial): + } + } +} + +func ids(events []outbound.OutboxEvent) []uuid.UUID { + result := make([]uuid.UUID, 0, len(events)) + for _, event := range events { + result = append(result, event.EventID) + } + return result +} + +func eventIDs(events []storedEvent) []uuid.UUID { + result := make([]uuid.UUID, 0, len(events)) + for _, event := range events { + result = append(result, event.eventID) + } + return result +} + +func assertClaimed(t *testing.T, name string, claimed []outbound.OutboxEvent, want ...testAccount) { + t.Helper() + if len(claimed) != len(want) { + t.Fatalf("%s claimed %d events, want %d", name, len(claimed), len(want)) + } + for index, account := range want { + if claimed[index].AggregateID != account.id || claimed[index].AggregateVersion != account.version { + t.Fatalf("%s claim %d = %s v%d, want %s v%d", name, index, + claimed[index].AggregateID, claimed[index].AggregateVersion, account.id, account.version) + } + } +} + +func countUnpublished(ctx context.Context, t *testing.T, pool *pgxpool.Pool) int { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*) FROM outbox_events WHERE published_at IS NULL`).Scan(&count); err != nil { + t.Fatalf("count unpublished events: %v", err) + } + return count +} + +func assertUnpublished(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want int) { + t.Helper() + if got := countUnpublished(ctx, t, pool); got != want { + t.Fatalf("outbox has %d unpublished events, want %d", got, want) + } +} + +func waitForUnpublished(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want int) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, relayDrainTimeout) + defer cancel() + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() + for { + got := countUnpublished(ctx, t, pool) + if got == want { + return + } + select { + case <-ctx.Done(): + t.Fatalf("outbox still has %d unpublished events, want %d", got, want) + case <-ticker.C: + } + } +} + +// waitForLockedOutboxRow waits until a relay pass holds the row lock of an +// outbox event, which proves the pass is in progress. +func waitForLockedOutboxRow(ctx context.Context, t *testing.T, pool *pgxpool.Pool) { + t.Helper() + ctx, cancel := context.WithTimeout(ctx, lockWaitTimeout) + defer cancel() + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() + for { + var unlocked int + err := pool.QueryRow(ctx, ` + SELECT count(*) FROM ( + SELECT 1 FROM outbox_events WHERE published_at IS NULL + FOR UPDATE SKIP LOCKED + ) AS free`).Scan(&unlocked) + if err == nil && unlocked == 0 { + return + } + select { + case <-ctx.Done(): + t.Fatalf("no relay pass locked the outbox row: %v", err) + case <-ticker.C: + } + } +} + +// consumeUntilEventIDs reads the topic from the start until every wanted +// event ID has arrived and returns the records grouped by event ID in +// consumption order. Duplicates are kept. +func consumeUntilEventIDs(ctx context.Context, t *testing.T, env *testEnvironment, topic string, want []uuid.UUID) map[uuid.UUID][]*kgo.Record { + t.Helper() + consumer := env.newKafkaClient(t, + kgo.ConsumeTopics(topic), + kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), + ) + ctx, cancel := context.WithTimeout(ctx, relayRecoveryTimeout) + defer cancel() + received := make(map[uuid.UUID][]*kgo.Record, len(want)) + missing := func() int { + count := 0 + for _, eventID := range want { + if len(received[eventID]) == 0 { + count++ + } + } + return count + } + for missing() > 0 { + fetches := consumer.PollFetches(ctx) + if err := ctx.Err(); err != nil { + t.Fatalf("consume topic %s: %d of %d events missing: %v", topic, missing(), len(want), err) + } + if err := fetches.Err(); err != nil { + t.Fatalf("consume topic %s: %v", topic, err) + } + for _, record := range fetches.Records() { + eventID, err := uuid.Parse(headerValue(record, "event_id")) + if err != nil { + t.Fatalf("record without a valid event_id header: %v", err) + } + received[eventID] = append(received[eventID], record) + } + } + return received +} + +// assertAggregateOrder checks that every aggregate's events share one +// partition and that, ignoring duplicates, their first appearances follow +// aggregate_version without gaps. +func assertAggregateOrder(t *testing.T, received map[uuid.UUID][]*kgo.Record) { + t.Helper() + type position struct { + partition int32 + offset int64 + } + type delivery struct { + version int64 + first position + } + byAggregate := make(map[string][]delivery) + partitions := make(map[string]int32) + duplicates := 0 + for _, records := range received { + duplicates += len(records) - 1 + envelope := decodeEnvelope(t, records[0]) + key := string(records[0].Key) + for _, record := range records { + if partition, ok := partitions[key]; ok && partition != record.Partition { + t.Fatalf("aggregate %s has records in partitions %d and %d", key, partition, record.Partition) + } + partitions[key] = record.Partition + } + byAggregate[key] = append(byAggregate[key], delivery{ + version: envelope.AggregateVersion, + first: position{partition: records[0].Partition, offset: records[0].Offset}, + }) + } + if len(byAggregate) != competingAggregates { + t.Fatalf("received %d aggregates, want %d", len(byAggregate), competingAggregates) + } + for key, deliveries := range byAggregate { + slices.SortFunc(deliveries, func(a, b delivery) int { return cmp.Compare(a.first.offset, b.first.offset) }) + for index, delivery := range deliveries { + if want := int64(index + 1); delivery.version != want { + t.Fatalf("aggregate %s: delivery %d has version %d, want %d", key, index, delivery.version, want) + } + } + } + t.Logf("received %d events with %d duplicate deliveries", len(received), duplicates) +} + +type receivedEnvelope struct { + EnvelopeVersion int `json:"envelope_version"` + EventID uuid.UUID `json:"event_id"` + EventType string `json:"event_type"` + SchemaVersion int32 `json:"schema_version"` + AggregateType string `json:"aggregate_type"` + AggregateID uuid.UUID `json:"aggregate_id"` + AggregateVersion int64 `json:"aggregate_version"` + OccurredAt time.Time `json:"occurred_at"` + Payload json.RawMessage `json:"payload"` +} + +func decodeEnvelope(t *testing.T, record *kgo.Record) receivedEnvelope { + t.Helper() + var envelope receivedEnvelope + if err := json.Unmarshal(record.Value, &envelope); err != nil { + t.Fatalf("decode envelope: %v", err) + } + return envelope +} + +func headerValue(record *kgo.Record, key string) string { + for _, header := range record.Headers { + if header.Key == key { + return string(header.Value) + } + } + return "" +} + +// assertEnvelope checks the record against the stored outbox row. +func assertEnvelope(t *testing.T, record *kgo.Record, stored storedEvent) { + t.Helper() + envelope := decodeEnvelope(t, record) + if envelope.EnvelopeVersion != kafka.EnvelopeVersion || envelope.EventID != stored.eventID || + envelope.EventType != stored.eventType || envelope.SchemaVersion != stored.schemaVersion || + envelope.AggregateType != stored.aggregateType || envelope.AggregateID != stored.aggregateID || + envelope.AggregateVersion != stored.aggregateVersion || envelope.OccurredAt.IsZero() { + t.Fatalf("envelope %+v does not match stored event %s", envelope, stored.eventID) + } + assertJSONEqual(t, envelope.Payload, stored.payload) + if want := stored.aggregateType + ":" + stored.aggregateID.String(); string(record.Key) != want { + t.Fatalf("record key = %q, want %q", record.Key, want) + } + for key, want := range map[string]string{ + "event_id": stored.eventID.String(), + "event_type": stored.eventType, + "schema_version": fmt.Sprint(stored.schemaVersion), + } { + if got := headerValue(record, key); got != want { + t.Fatalf("header %s = %q, want %q", key, got, want) + } + } +} diff --git a/backend/integration_test/outbox_test.go b/backend/integration_test/outbox_test.go new file mode 100644 index 0000000..6170e13 --- /dev/null +++ b/backend/integration_test/outbox_test.go @@ -0,0 +1,660 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + // The test aggregate lives in its own schema, outside production migrations. + testAggregateSchema = "outbox_test" + testAggregateTable = "accounts" + testAggregateType = "test_account" + testAccountEventType = "test.account_changed" + testEventSchema = 1 + parallelTransactions = 20 + contenderCount = 2 + outboxTestTimeout = 2 * time.Minute + lockWaitTimeout = 10 * time.Second + connectionsTimeout = 5 * time.Second + canceledFnTimeout = 300 * time.Millisecond + pollInterval = 10 * time.Millisecond + checkViolationCode = "23514" + accountStatusActive = "active" + accountStatusArchived = "archived" + contenderApplication = "outbox_contender_b" +) + +var ( + errForcedRollback = errors.New("forced rollback") + errStaleAccountVersion = errors.New("test account version is stale") + outboxEventsTable = pgx.Identifier{"outbox_events"} + testAccountsTable = pgx.Identifier{testAggregateSchema, testAggregateTable} + createTestAccountsTable = fmt.Sprintf(` + CREATE SCHEMA %[1]s; + CREATE TABLE %[2]s ( + id uuid PRIMARY KEY, + version bigint NOT NULL CHECK (version > 0), + status text NOT NULL + )`, pgx.Identifier{testAggregateSchema}.Sanitize(), testAccountsTable.Sanitize()) +) + +type testAccount struct { + id uuid.UUID + version int64 + status string +} + +type storedEvent struct { + position int64 + eventID uuid.UUID + eventType string + schemaVersion int32 + aggregateType string + aggregateID uuid.UUID + aggregateVersion int64 + payload []byte + publishedAt *time.Time +} + +type transactionFn = func(context.Context, outbound.UnitOfWork) error + +func TestOutboxTransactions(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), outboxTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + if _, err := pool.Exec(ctx, createTestAccountsTable); err != nil { + t.Fatalf("create test aggregate table: %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + + // Subtests share tables and run sequentially; each starts from empty tables. + reset := func(t *testing.T) { + t.Helper() + truncateTables(ctx, t, pool, outboxEventsTable, testAccountsTable) + } + + t.Run("commits the aggregate change and its event together", func(t *testing.T) { + reset(t) + created := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + createdEvent := newAccountEvent(t, created) + if err := transactor.WithinTransaction(ctx, saveAccountWith(created, createdEvent)); err != nil { + t.Fatalf("WithinTransaction(create) error = %v", err) + } + archived := testAccount{id: created.id, version: 2, status: accountStatusArchived} + archivedEvent := newAccountEvent(t, archived) + if err := transactor.WithinTransaction(ctx, saveAccountWith(archived, archivedEvent)); err != nil { + t.Fatalf("WithinTransaction(update) error = %v", err) + } + + assertAccount(ctx, t, pool, archived) + events := readOutboxEvents(ctx, t, pool) + if len(events) != 2 { + t.Fatalf("outbox has %d events, want 2", len(events)) + } + assertStoredEvent(t, events[0], createdEvent) + assertStoredEvent(t, events[1], archivedEvent) + if events[0].position >= events[1].position { + t.Fatalf("positions %d and %d do not follow insertion order", events[0].position, events[1].position) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("optimistic version check rejects a stale update before the event", func(t *testing.T) { + reset(t) + created := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + if err := transactor.WithinTransaction(ctx, saveAccountWith(created, newAccountEvent(t, created))); err != nil { + t.Fatalf("WithinTransaction(create) error = %v", err) + } + updated := testAccount{id: created.id, version: 2, status: accountStatusArchived} + if err := transactor.WithinTransaction(ctx, saveAccountWith(updated, newAccountEvent(t, updated))); err != nil { + t.Fatalf("WithinTransaction(update) error = %v", err) + } + // A writer that still expects version 1 must fail on the version check. + stale := testAccount{id: created.id, version: 2, status: "stale"} + err := transactor.WithinTransaction(ctx, saveAccountWith(stale, newAccountEvent(t, stale))) + if !errors.Is(err, errStaleAccountVersion) { + t.Fatalf("WithinTransaction(stale) error = %v, want errStaleAccountVersion", err) + } + assertAccount(ctx, t, pool, updated) + if events := readOutboxEvents(ctx, t, pool); len(events) != 2 { + t.Fatalf("outbox has %d events, want 2", len(events)) + } + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back both writes when the callback fails", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + return errForcedRollback + }) + if !errors.Is(err, errForcedRollback) { + t.Fatalf("WithinTransaction() error = %v, want the callback error", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back both writes and re-raises a panic", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + panicValue := fmt.Sprintf("forced panic %s", account.id) + recovered := func() (recovered any) { + defer func() { recovered = recover() }() + _ = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + panic(panicValue) + }) + return nil + }() + if recovered != panicValue { + t.Fatalf("recovered %v, want the original panic value", recovered) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rolls back and releases the connection when the context is canceled mid-callback", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + callbackCtx, cancelCallback := context.WithTimeout(ctx, canceledFnTimeout) + defer cancelCallback() + err := transactor.WithinTransaction(callbackCtx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + // The deadline interrupts this statement after both writes. + _, err := integrationTx(t, unit).Exec(ctx, "SELECT pg_sleep(30)") + return err + }) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("WithinTransaction() error = %v, want context.DeadlineExceeded", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("rejects a nested transaction without touching the outer one", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + write := saveAccountWith(account, newAccountEvent(t, account)) + innerRan := false + var nestedErr error + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := write(ctx, unit); err != nil { + return err + } + nestedErr = transactor.WithinTransaction(ctx, func(context.Context, outbound.UnitOfWork) error { + innerRan = true + return nil + }) + return nil + }) + if err != nil { + t.Fatalf("outer WithinTransaction() error = %v", err) + } + if !errors.Is(nestedErr, outbound.ErrNestedTransaction) || innerRan { + t.Fatalf("nested WithinTransaction() error = %v, inner ran = %t, want ErrNestedTransaction without running", nestedErr, innerRan) + } + assertAccount(ctx, t, pool, account) + assertNoBusyConnections(t, pool) + }) + + t.Run("fails the commit when the callback ignores a statement error", func(t *testing.T) { + reset(t) + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + event := newAccountEvent(t, account) + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := saveAccountWith(account, event)(ctx, unit); err != nil { + return err + } + // The duplicate aborts the transaction even though the error is dropped. + if err := unit.Outbox().Append(ctx, event); !errors.Is(err, outbound.ErrOutboxEventConflict) { + return fmt.Errorf("duplicate append error = %w, want ErrOutboxEventConflict", err) + } + return nil + }) + if !errors.Is(err, pgx.ErrTxCommitRollback) { + t.Fatalf("WithinTransaction() error = %v, want pgx.ErrTxCommitRollback", err) + } + assertTablesEmpty(ctx, t, pool) + assertNoBusyConnections(t, pool) + }) + + t.Run("stores every domain-valid edge payload", func(t *testing.T) { + reset(t) + prefix, suffix := `{"ids":[`, `0]}` + arrayAtLimit := prefix + strings.Repeat("0,", (domain.MaxDomainEventPayloadBytes-len(prefix)-len(suffix))/2) + suffix + payloads := []string{ + arrayAtLimit, + strings.Repeat(`{"a":`, 32) + "1" + strings.Repeat("}", 32), + `{"text":"\\u0000 is plain text here"}`, + `{"name":"Привет","emoji":"😀"}`, + `{"big":123456789012345678901234567890,"small":1e-300}`, + } + events := make([]domain.DomainEvent, 0, len(payloads)) + for _, payload := range payloads { + event, err := domain.NewDomainEvent(domain.DomainEventInput{ + EventType: testAccountEventType, SchemaVersion: testEventSchema, AggregateType: testAggregateType, + AggregateID: uuid.New(), AggregateVersion: 1, Payload: []byte(payload), + }) + if err != nil { + t.Fatalf("NewDomainEvent(%.40s) error = %v", payload, err) + } + events = append(events, event) + } + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Outbox().Append(ctx, events...) + }) + if err != nil { + t.Fatalf("Append(edge payloads) error = %v", err) + } + stored := readOutboxEvents(ctx, t, pool) + byID := make(map[uuid.UUID]storedEvent, len(stored)) + for _, event := range stored { + byID[event.eventID] = event + } + for _, event := range events { + assertStoredEvent(t, byID[event.EventID()], event) + } + }) + + t.Run("parallel transactions commit independently and a lock waiter conflicts on the aggregate version", func(t *testing.T) { + reset(t) + // One connection per transaction plus a spare, so nothing queues in the pool. + concurrentPool := env.newPoolWithMaxConns(ctx, t, parallelTransactions+contenderCount+1) + concurrentTransactor := postgresadapter.NewTransactor(concurrentPool) + contested := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + if err := transactor.WithinTransaction(ctx, saveAccountWith(contested, newAccountEvent(t, contested))); err != nil { + t.Fatalf("create contested account: %v", err) + } + + // The contenders deliberately skip the optimistic version check to prove + // that the outbox unique key still blocks a second event for version 2. + // A holds its transaction open after writing; B then blocks on A's row + // lock and, once A commits, violates the outbox key. + contenderA := testAccount{id: contested.id, version: 2, status: "contender_a"} + contenderB := testAccount{id: contested.id, version: 2, status: "contender_b"} + writeA := blindSaveAccountWith(contenderA, newAccountEvent(t, contenderA)) + writeB := blindSaveAccountWith(contenderB, newAccountEvent(t, contenderB)) + aWrote, releaseA, aFinished := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseA) }) } + defer release() + + independent := make([]transactionFn, 0, parallelTransactions) + for range parallelTransactions { + account := testAccount{id: uuid.New(), version: 1, status: accountStatusActive} + independent = append(independent, saveAccountWith(account, newAccountEvent(t, account))) + } + independentErrs := make([]error, len(independent)) + var errA, errB error + start := make(chan struct{}) + var group sync.WaitGroup + for index, write := range independent { + group.Go(func() { + <-start + independentErrs[index] = concurrentTransactor.WithinTransaction(ctx, write) + }) + } + group.Go(func() { + defer close(aFinished) + <-start + errA = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := writeA(ctx, unit); err != nil { + return err + } + close(aWrote) + select { + case <-releaseA: + return nil + case <-ctx.Done(): + return ctx.Err() + } + }) + }) + group.Go(func() { + select { + case <-aWrote: + case <-aFinished: + errB = errors.New("contender A finished before writing") + return + } + errB = concurrentTransactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + // Label the session so the test can observe its lock wait. + if _, err := integrationTx(t, unit).Exec(ctx, "SET LOCAL application_name = '"+contenderApplication+"'"); err != nil { + return fmt.Errorf("label contender B: %w", err) + } + return writeB(ctx, unit) + }) + }) + close(start) + + waitEvent, observed := waitForLockWait(ctx, pool, contenderApplication) + release() + group.Wait() + if !observed { + t.Fatalf("contender B was not observed waiting on a lock (last wait event %q)", waitEvent) + } + t.Logf("observed contender B waiting on a lock: wait_event=%s", waitEvent) + + for index, err := range independentErrs { + if err != nil { + t.Fatalf("independent transaction %d error = %v", index, err) + } + } + if errA != nil { + t.Fatalf("contender A error = %v", errA) + } + if !errors.Is(errB, outbound.ErrOutboxEventConflict) { + t.Fatalf("contender B error = %v, want ErrOutboxEventConflict", errB) + } + + assertAccount(ctx, t, pool, contenderA) + events := readOutboxEvents(ctx, t, pool) + if want := 1 + parallelTransactions + 1; len(events) != want { + t.Fatalf("outbox has %d events, want %d", len(events), want) + } + var orphans int + err := pool.QueryRow(ctx, fmt.Sprintf(` + SELECT count(*) FROM outbox_events AS e + WHERE NOT EXISTS ( + SELECT 1 FROM %s AS a + WHERE a.id = e.aggregate_id AND a.version >= e.aggregate_version + )`, testAccountsTable.Sanitize())).Scan(&orphans) + if err != nil { + t.Fatalf("count orphan events: %v", err) + } + if orphans != 0 { + t.Fatalf("found %d events without their aggregate change", orphans) + } + var winnerPayload []byte + err = pool.QueryRow(ctx, ` + SELECT payload FROM outbox_events + WHERE aggregate_id = $1 AND aggregate_version = 2`, contested.id).Scan(&winnerPayload) + if err != nil { + t.Fatalf("read contested event: %v", err) + } + assertJSONEqual(t, winnerPayload, accountPayload(contenderA)) + assertNoBusyConnections(t, concurrentPool) + assertNoBusyConnections(t, pool) + }) + + t.Run("domain validation and database constraints reject invalid versions", func(t *testing.T) { + reset(t) + for _, input := range []domain.DomainEventInput{ + {EventType: testAccountEventType, SchemaVersion: 0, AggregateType: testAggregateType, AggregateID: uuid.New(), AggregateVersion: 1, Payload: []byte(`{}`)}, + {EventType: testAccountEventType, SchemaVersion: 1, AggregateType: testAggregateType, AggregateID: uuid.New(), AggregateVersion: 0, Payload: []byte(`{}`)}, + } { + if _, err := domain.NewDomainEvent(input); !errors.Is(err, domain.ErrInvalidDomainEvent) { + t.Fatalf("NewDomainEvent(%+v) error = %v, want ErrInvalidDomainEvent", input, err) + } + } + + tests := []struct { + constraint string + schemaVersion int32 + aggregateVersion int64 + payload string + }{ + {constraint: "outbox_events_schema_version_positive", schemaVersion: 0, aggregateVersion: 1, payload: `{}`}, + {constraint: "outbox_events_aggregate_version_positive", schemaVersion: 1, aggregateVersion: 0, payload: `{}`}, + {constraint: "outbox_events_payload_object", schemaVersion: 1, aggregateVersion: 1, payload: `[]`}, + } + for _, test := range tests { + // Raw SQL bypasses domain validation to prove the database backstop. + _, err := pool.Exec(ctx, ` + INSERT INTO outbox_events ( + event_id, event_type, schema_version, aggregate_type, + aggregate_id, aggregate_version, payload + ) VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`, + uuid.New(), testAccountEventType, test.schemaVersion, testAggregateType, + uuid.New(), test.aggregateVersion, test.payload) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("insert violating %s error = %v, want a check violation", test.constraint, err) + } + } + assertTablesEmpty(ctx, t, pool) + }) +} + +// integrationTx returns the transaction behind unit through the adapter's +// integration-only seam. +func integrationTx(t *testing.T, unit outbound.UnitOfWork) pgx.Tx { + t.Helper() + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + t.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + return tx +} + +// saveAccountWith returns a transaction callback that writes the aggregate +// with an optimistic version check and then its event through the same unit +// of work. Version 1 inserts; later versions update from the previous version. +func saveAccountWith(account testAccount, event domain.DomainEvent) transactionFn { + insert := fmt.Sprintf(`INSERT INTO %s (id, version, status) VALUES ($1, $2, $3)`, testAccountsTable.Sanitize()) + update := fmt.Sprintf(`UPDATE %s SET version = $2, status = $3 WHERE id = $1 AND version = $2 - 1`, testAccountsTable.Sanitize()) + return func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return fmt.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + statement := update + if account.version == 1 { + statement = insert + } + tag, err := tx.Exec(ctx, statement, account.id, account.version, account.status) + if err != nil { + return fmt.Errorf("save test account: %w", err) + } + if tag.RowsAffected() != 1 { + return errStaleAccountVersion + } + return unit.Outbox().Append(ctx, event) + } +} + +// blindSaveAccountWith overwrites the aggregate without a version check. Only +// the contention test uses it, to exercise the outbox uniqueness backstop. +func blindSaveAccountWith(account testAccount, event domain.DomainEvent) transactionFn { + update := fmt.Sprintf(`UPDATE %s SET version = $2, status = $3 WHERE id = $1`, testAccountsTable.Sanitize()) + return func(ctx context.Context, unit outbound.UnitOfWork) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return fmt.Errorf("unit of work has type %T, want the PostgreSQL adapter", unit) + } + if _, err := tx.Exec(ctx, update, account.id, account.version, account.status); err != nil { + return fmt.Errorf("overwrite test account: %w", err) + } + return unit.Outbox().Append(ctx, event) + } +} + +// waitForLockWait polls pg_stat_activity until the session labeled +// applicationName waits on a heavyweight lock. +func waitForLockWait(ctx context.Context, pool *pgxpool.Pool, applicationName string) (string, bool) { + ctx, cancel := context.WithTimeout(ctx, lockWaitTimeout) + defer cancel() + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() + lastWaitEvent := "" + for { + var waitEventType, waitEvent *string + err := pool.QueryRow(ctx, ` + SELECT wait_event_type, wait_event FROM pg_stat_activity + WHERE application_name = $1 AND state = 'active'`, applicationName).Scan(&waitEventType, &waitEvent) + if err == nil && waitEventType != nil && *waitEventType == "Lock" { + if waitEvent != nil { + return *waitEvent, true + } + return "", true + } + if err == nil && waitEvent != nil { + lastWaitEvent = *waitEvent + } + select { + case <-ctx.Done(): + return lastWaitEvent, false + case <-ticker.C: + } + } +} + +func accountPayload(account testAccount) []byte { + payload, err := json.Marshal(map[string]any{ + "account_id": account.id.String(), + "status": account.status, + }) + if err != nil { + panic(err) + } + return payload +} + +func newAccountEvent(t *testing.T, account testAccount) domain.DomainEvent { + t.Helper() + event, err := newAccountEventE(account) + if err != nil { + t.Fatalf("NewDomainEvent() error = %v", err) + } + return event +} + +// newAccountEventE is newAccountEvent for goroutines, which must not call +// t.Fatal. +func newAccountEventE(account testAccount) (domain.DomainEvent, error) { + return domain.NewDomainEvent(domain.DomainEventInput{ + EventType: testAccountEventType, + SchemaVersion: testEventSchema, + AggregateType: testAggregateType, + AggregateID: account.id, + AggregateVersion: account.version, + Payload: accountPayload(account), + }) +} + +func readOutboxEvents(ctx context.Context, t *testing.T, pool *pgxpool.Pool) []storedEvent { + t.Helper() + rows, err := pool.Query(ctx, ` + SELECT position, event_id, event_type, schema_version, aggregate_type, + aggregate_id, aggregate_version, payload, published_at + FROM outbox_events + ORDER BY position`) + if err != nil { + t.Fatalf("query outbox events: %v", err) + } + events, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (storedEvent, error) { + var event storedEvent + err := row.Scan(&event.position, &event.eventID, &event.eventType, &event.schemaVersion, &event.aggregateType, + &event.aggregateID, &event.aggregateVersion, &event.payload, &event.publishedAt) + return event, err + }) + if err != nil { + t.Fatalf("read outbox events: %v", err) + } + return events +} + +func assertStoredEvent(t *testing.T, stored storedEvent, want domain.DomainEvent) { + t.Helper() + if stored.eventID != want.EventID() || stored.eventType != want.EventType() || + stored.schemaVersion != want.SchemaVersion() || stored.aggregateType != want.AggregateType() || + stored.aggregateID != want.AggregateID() || stored.aggregateVersion != want.AggregateVersion() { + t.Fatalf("stored event %+v does not match written event %s v%d", stored, want.EventID(), want.AggregateVersion()) + } + if stored.publishedAt != nil { + t.Fatalf("new event %s is already marked as published", stored.eventID) + } + assertJSONEqual(t, stored.payload, want.Payload()) +} + +// assertJSONEqual compares JSON values because jsonb normalizes key order and +// whitespace. +func assertJSONEqual(t *testing.T, got, want []byte) { + t.Helper() + var gotValue, wantValue any + if err := json.Unmarshal(got, &gotValue); err != nil { + t.Fatalf("decode stored payload: %v", err) + } + if err := json.Unmarshal(want, &wantValue); err != nil { + t.Fatalf("decode expected payload: %v", err) + } + if !reflect.DeepEqual(gotValue, wantValue) { + t.Fatalf("payload = %.200s, want %.200s", got, want) + } +} + +func assertAccount(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want testAccount) { + t.Helper() + got := testAccount{id: want.id} + err := pool.QueryRow(ctx, fmt.Sprintf(`SELECT version, status FROM %s WHERE id = $1`, testAccountsTable.Sanitize()), + want.id).Scan(&got.version, &got.status) + if err != nil { + t.Fatalf("read test account: %v", err) + } + if got != want { + t.Fatalf("account = %+v, want %+v", got, want) + } +} + +func assertTablesEmpty(ctx context.Context, t *testing.T, pool *pgxpool.Pool) { + t.Helper() + for _, table := range []pgx.Identifier{testAccountsTable, outboxEventsTable} { + var count int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM "+table.Sanitize()).Scan(&count); err != nil { + t.Fatalf("count rows in %s: %v", table.Sanitize(), err) + } + if count != 0 { + t.Fatalf("%s has %d rows after rollback, want 0", table.Sanitize(), count) + } + } +} + +// assertNoBusyConnections proves that every transaction released its +// connection, including after a rollback, a panic, or a canceled query. pgx +// may destroy a connection broken by cancellation asynchronously, so the +// check polls briefly. +func assertNoBusyConnections(t *testing.T, pool *pgxpool.Pool) { + t.Helper() + deadline := time.Now().Add(connectionsTimeout) + for { + acquired := pool.Stat().AcquiredConns() + if acquired == 0 { + return + } + if time.Now().After(deadline) { + t.Fatalf("pool has %d acquired connections after the transactions finished", acquired) + } + time.Sleep(pollInterval) + } +} diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go new file mode 100644 index 0000000..75fe79c --- /dev/null +++ b/backend/integration_test/policy_test.go @@ -0,0 +1,739 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "errors" + "fmt" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const ( + policyTestTimeout = 3 * time.Minute + // concurrentPublishers stays below the publisher's attempt bound, so each + // of them must succeed. + concurrentPublishers = 8 + concurrentSeeders = 4 + // policyImmutableSQLState and policyImmutableConstraint identify the + // refusal raised by the policy_versions trigger. + policyImmutableSQLState = "23000" + policyImmutableConstraint = "policy_versions_immutable" + foreignKeyViolationState = "23503" + policyTestAuthor = domain.PolicyAuthor("operator:integration-test") + // databaseClockTolerance bounds the difference between the test clock and + // the PostgreSQL container clock that stamps created_at. + databaseClockTolerance = time.Minute +) + +// policyFixture works on its own database. "product" is the only policy +// family and the table refuses TRUNCATE, so every subtest gets a fresh +// database instead of a key of its own or a cleanup. +type policyFixture struct { + ctx context.Context + databaseURL string + pool *pgxpool.Pool + store *postgresadapter.PolicyStore + transactor *postgresadapter.Transactor +} + +func TestPolicyVersions(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), policyTestTimeout) + defer cancel() + newFixture := func(t *testing.T) policyFixture { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + return policyFixture{ + ctx: ctx, + databaseURL: databaseURL, + pool: pool, + store: postgresadapter.NewPolicyStore(pool), + transactor: postgresadapter.NewTransactor(pool), + } + } + + t.Run("saves two versions and reads both by ID", func(t *testing.T) { + fixture := newFixture(t) + before := time.Now() + first := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(11)) + scheduledAt := before.Add(time.Hour).Truncate(time.Microsecond) + second := fixture.publish(t, fixture.store.Policies(), 2, scheduledAt, integrationPolicy(12)) + for _, want := range []domain.PolicyVersion{first, second} { + got, err := fixture.store.Policies().GetByID(ctx, want.ID()) + if err != nil { + t.Fatalf("GetByID(%s) error = %v", want.ID(), err) + } + assertSamePolicyVersion(t, got, want) + } + assertDatabaseTime(t, "created_at", first.CreatedAt(), before) + if !first.EffectiveAt().Equal(first.CreatedAt()) || !second.EffectiveAt().Equal(scheduledAt) { + t.Fatalf("effective times = %s and %s, want publication and %s", first.EffectiveAt(), second.EffectiveAt(), scheduledAt) + } + if got := fixture.readMaxPending(t, second.ID()); got != 12 { + t.Fatalf("second version max_pending_per_need = %d, want 12", got) + } + var storedHash []byte + if err := fixture.pool.QueryRow(ctx, `SELECT document_sha256 FROM policy_versions WHERE id = $1`, first.ID().UUID()).Scan(&storedHash); err != nil { + t.Fatalf("read stored hash: %v", err) + } + if want := sha256.Sum256(first.Document()); string(storedHash) != string(want[:]) { + t.Fatal("stored document_sha256 is not the SHA-256 of the canonical document") + } + if _, err := fixture.store.Policies().GetByID(ctx, domain.PolicyVersionID(uuid.New())); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { + t.Fatalf("GetByID(unknown) error = %v, want ErrPolicyVersionNotFound", err) + } + }) + + t.Run("the database sets the publication time", func(t *testing.T) { + fixture := newFixture(t) + before := time.Now() + draft := fixture.draft(t, 1, time.Time{}, integrationPolicy(13)) + hash := draft.DocumentHash() + // A caller-supplied created_at and a missing effective_at are both + // replaced by the stamp trigger. + var createdAt, effectiveAt time.Time + err := fixture.pool.QueryRow(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256, created_at) + VALUES ($1, $2, $3, $4, NULL, $5, $6, $7, '2000-01-01T00:00:00Z') + RETURNING created_at, effective_at`, + draft.ID().UUID(), string(draft.Key()), draft.Version(), string(draft.Kind()), string(draft.Author()), + draft.Document(), hash[:]).Scan(&createdAt, &effectiveAt) + if err != nil { + t.Fatalf("insert with a caller-supplied created_at: %v", err) + } + assertDatabaseTime(t, "created_at", createdAt, before) + if !effectiveAt.Equal(createdAt) { + t.Fatalf("effective_at = %s, want created_at %s", effectiveAt, createdAt) + } + + backdated := fixture.draft(t, 2, time.Now().Add(-time.Hour), integrationPolicy(14)) + _, err = fixture.store.Policies().Create(ctx, backdated) + if !errors.Is(err, outbound.ErrPolicyVersionBackdated) { + t.Fatalf("Create(backdated) error = %v, want ErrPolicyVersionBackdated", err) + } + fixture.assertVersionCount(t, 1) + }) + + t.Run("a conflict inside a unit of work leaves the transaction usable", func(t *testing.T) { + fixture := newFixture(t) + existing := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(15)) + var stored []domain.PolicyVersion + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + duplicate := fixture.draft(t, 1, time.Time{}, integrationPolicy(16)) + if _, err := unit.Policies().Create(ctx, duplicate); !errors.Is(err, outbound.ErrPolicyVersionConflict) { + return fmt.Errorf("Create(duplicate number) error = %w, want ErrPolicyVersionConflict", err) + } + second, err := unit.Policies().Create(ctx, fixture.draft(t, 2, time.Time{}, integrationPolicy(17))) + if err != nil { + return fmt.Errorf("Create(v2) after the conflict: %w", err) + } + // The publisher works through the transaction too. + third, err := policy.NewPublisher(unit.Policies(), time.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, Author: policyTestAuthor, Policy: integrationPolicy(18), + }) + if err != nil { + return fmt.Errorf("Publish() in the transaction: %w", err) + } + got, err := unit.Policies().GetByID(ctx, second.ID()) + if err != nil { + return fmt.Errorf("GetByID() in the transaction: %w", err) + } + assertSamePolicyVersion(t, got, second) + // The pool store must not bypass the transaction. + if _, err := fixture.store.Policies().GetByID(ctx, second.ID()); !errors.Is(err, outbound.ErrNestedTransaction) { + t.Errorf("standalone GetByID inside a transaction error = %v, want ErrNestedTransaction", err) + } + stored = []domain.PolicyVersion{existing, second, third} + return nil + }) + if err != nil { + t.Fatalf("WithinTransaction() error = %v", err) + } + for index, want := range stored { + got, err := fixture.store.Policies().GetByID(ctx, want.ID()) + if err != nil || got.Version() != int32(index+1) { + t.Fatalf("GetByID(v%d) after commit = v%d, %v", index+1, got.Version(), err) + } + } + fixture.assertVersionCount(t, len(stored)) + }) + + t.Run("the newest effective publication wins, also over an earlier schedule", func(t *testing.T) { + fixture := newFixture(t) + policies := fixture.store.Policies() + first := fixture.publish(t, policies, 1, time.Time{}, integrationPolicy(21)) + if _, err := policies.GetEffective(ctx, domain.ProductPolicyKey, first.CreatedAt().Add(-time.Microsecond)); !errors.Is(err, outbound.ErrPolicyVersionNotFound) { + t.Fatalf("GetEffective(before version 1) error = %v, want ErrPolicyVersionNotFound", err) + } + scheduledAt := first.CreatedAt().Add(time.Hour) + scheduled := fixture.publish(t, policies, 2, scheduledAt, integrationPolicy(22)) + fixture.assertEffective(t, first.CreatedAt(), first) + fixture.assertEffective(t, scheduledAt.Add(-time.Minute), first) + fixture.assertEffective(t, scheduledAt, scheduled) + fixture.assertEffective(t, scheduledAt.Add(time.Hour), scheduled) + + // An urgent correction published after the schedule takes effect at + // once and stays in effect when the scheduled time arrives. + urgent := fixture.publish(t, policies, 3, time.Time{}, integrationPolicy(23)) + fixture.assertEffective(t, first.CreatedAt(), first) + fixture.assertEffective(t, urgent.CreatedAt(), urgent) + fixture.assertEffective(t, scheduledAt, urgent) + fixture.assertEffective(t, scheduledAt.Add(time.Hour), urgent) + latest, err := policies.GetLatest(ctx, domain.ProductPolicyKey) + if err != nil || latest.ID() != urgent.ID() { + t.Fatalf("GetLatest() = v%d, %v; want v3", latest.Version(), err) + } + }) + + t.Run("a taken version number or ID is a conflict", func(t *testing.T) { + fixture := newFixture(t) + draft := fixture.draft(t, 1, time.Time{}, integrationPolicy(31)) + if _, err := fixture.store.Policies().Create(ctx, draft); err != nil { + t.Fatalf("Create() error = %v", err) + } + duplicateNumber := fixture.draft(t, 1, time.Time{}, integrationPolicy(32)) + if _, err := fixture.store.Policies().Create(ctx, duplicateNumber); !errors.Is(err, outbound.ErrPolicyVersionConflict) { + t.Fatalf("Create(duplicate number) error = %v, want ErrPolicyVersionConflict", err) + } + sameID, err := draft.WithVersion(2) + if err != nil { + t.Fatalf("WithVersion(2) error = %v", err) + } + if _, err := fixture.store.Policies().Create(ctx, sameID); !errors.Is(err, outbound.ErrPolicyVersionConflict) { + t.Fatalf("Create(same ID) error = %v, want ErrPolicyVersionConflict", err) + } + fixture.assertVersionCount(t, 1) + if got := fixture.readMaxPending(t, draft.ID()); got != 31 { + t.Fatalf("stored version changed: max_pending_per_need = %d, want 31", got) + } + }) + + t.Run("the database refuses UPDATE, DELETE, and TRUNCATE of a version", func(t *testing.T) { + fixture := newFixture(t) + stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(41)) + id := stored.ID().UUID() + statements := []struct { + name string + sql string + args []any + }{ + {name: "update of a value", sql: `UPDATE policy_versions SET author = 'operator:intruder' WHERE id = $1`, args: []any{id}}, + {name: "update without a change", sql: `UPDATE policy_versions SET document = document WHERE id = $1`, args: []any{id}}, + {name: "update of the document", sql: `UPDATE policy_versions + SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '99') WHERE id = $1`, args: []any{id}}, + {name: "delete", sql: `DELETE FROM policy_versions WHERE id = $1`, args: []any{id}}, + {name: "delete of every row", sql: `DELETE FROM policy_versions`}, + // Include referencing tables so PostgreSQL reaches the + // immutable-policy trigger instead of its foreign-key precheck. + {name: "truncate", sql: `TRUNCATE policy_versions, company_invitation_quota_usage, + company_card_view_quota_usage, assessment_training_bank_bindings, + assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items, + assessment_attempt_work_leases, assessment_practice_jobs, assessment_practice_submissions, assessment_practices, + support_cases, support_case_events, assessment_signal_idempotency_outcomes, + assessment_signal_events, assessment_signal_batches, assessment_attempt_results, + assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks, + assessment_synthetic_category_reviews, candidate_assessment_categories, + skill_evidence_facts, skill_evidence_skills, + invitations, invitation_terms_versions, invitation_events, invitation_declines, contact_grants`}, + } + for _, statement := range statements { + _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) + assertPolicyImmutable(t, statement.name, err) + } + + // The same refusal inside a unit of work aborts the transaction. + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx := integrationTx(t, unit) + if _, err := tx.Exec(ctx, `UPDATE policy_versions SET effective_at = effective_at + interval '1 day' WHERE id = $1`, id); err != nil { + return fmt.Errorf("move effective time: %w", postgresadapter.MapPolicyErrorForIntegrationTest(err)) + } + return nil + }) + if !errors.Is(err, outbound.ErrPolicyVersionImmutable) { + t.Fatalf("UPDATE in a transaction error = %v, want ErrPolicyVersionImmutable", err) + } + + got, err := fixture.store.Policies().GetByID(ctx, stored.ID()) + if err != nil { + t.Fatalf("GetByID() after refused changes error = %v", err) + } + assertSamePolicyVersion(t, got, stored) + fixture.assertVersionCount(t, 1) + }) + + t.Run("a document changed behind the trigger fails its hash check", func(t *testing.T) { + fixture := newFixture(t) + stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(45)) + // The table owner can bypass the trigger. The change stays inside a + // transaction that is always rolled back, which also restores the + // trigger. + errTampered := errors.New("roll back tampering") + err := fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + tx := integrationTx(t, unit) + if _, err := tx.Exec(ctx, `ALTER TABLE policy_versions DISABLE TRIGGER policy_versions_refuse_update_delete`); err != nil { + return fmt.Errorf("disable trigger: %w", err) + } + if _, err := tx.Exec(ctx, `UPDATE policy_versions + SET document = jsonb_set(document, '{invitations,max_pending_per_need}', '46') WHERE id = $1`, stored.ID().UUID()); err != nil { + return fmt.Errorf("change document: %w", err) + } + if _, err := unit.Policies().GetByID(ctx, stored.ID()); !errors.Is(err, domain.ErrPolicyDocumentIntegrity) { + t.Errorf("GetByID(changed document) error = %v, want ErrPolicyDocumentIntegrity", err) + } + return errTampered + }) + if !errors.Is(err, errTampered) { + t.Fatalf("WithinTransaction() error = %v, want the rollback marker", err) + } + got, err := fixture.store.Policies().GetByID(ctx, stored.ID()) + if err != nil { + t.Fatalf("GetByID() after rollback error = %v", err) + } + assertSamePolicyVersion(t, got, stored) + _, err = fixture.pool.Exec(ctx, `DELETE FROM policy_versions WHERE id = $1`, stored.ID().UUID()) + assertPolicyImmutable(t, "delete after the rolled-back bypass", err) + }) + + t.Run("CHECK constraints refuse invalid rows from raw SQL", func(t *testing.T) { + fixture := newFixture(t) + demo := fixture.demoDraft(t) + demoHash := demo.DocumentHash() + calibratedDraft := fixture.draft(t, 1, time.Time{}, integrationPolicy(47)) + calibratedHash := calibratedDraft.DocumentHash() + valid := func() []any { + // id, policy_key, version, kind, effective_at, author, document, document_sha256 + return []any{uuid.New(), "product", int32(1), "demo", nil, "system:raw-sql", demo.Document(), demoHash[:]} + } + tests := []struct { + constraint string + mutate func(args []any) + }{ + {constraint: "policy_versions_effective_after_creation", mutate: func(args []any) { + args[4] = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC) + }}, + {constraint: "policy_versions_author_format", mutate: func(args []any) { args[5] = "operator:tester@example.com" }}, + {constraint: "policy_versions_author_format", mutate: func(args []any) { args[5] = "tester" }}, + {constraint: "policy_versions_kind_known", mutate: func(args []any) { args[3] = "draft" }}, + {constraint: "policy_versions_policy_key_known", mutate: func(args []any) { args[1] = "other" }}, + {constraint: "policy_versions_version_positive", mutate: func(args []any) { args[2] = int32(0) }}, + {constraint: "policy_versions_document_object", mutate: func(args []any) { args[6] = []byte(`[]`) }}, + {constraint: "policy_versions_document_sha256_size", mutate: func(args []any) { args[7] = demoHash[:31] }}, + {constraint: "policy_versions_calibrated_kind_matches_document", mutate: func(args []any) { args[3] = "calibrated" }}, + } + for _, test := range tests { + args := valid() + test.mutate(args) + _, err := fixture.pool.Exec(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, args...) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != checkViolationCode || pgError.ConstraintName != test.constraint { + t.Fatalf("insert violating %s error = %v, want a check violation", test.constraint, err) + } + } + fixture.assertVersionCount(t, 0) + // The kind CHECK accepts a calibrated document under a calibrated kind. + args := valid() + args[3], args[6], args[7] = "calibrated", calibratedDraft.Document(), calibratedHash[:] + if _, err := fixture.pool.Exec(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, effective_at, author, document, document_sha256) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, args...); err != nil { + t.Fatalf("insert of a valid calibrated row: %v", err) + } + }) + + t.Run("a referencing record pins its version", func(t *testing.T) { + fixture := newFixture(t) + stored := fixture.publish(t, fixture.store.Policies(), 1, time.Time{}, integrationPolicy(51)) + tx, err := fixture.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin transaction: %v", err) + } + // The probe table exists only inside this transaction, which is + // always rolled back. A temporary table cannot reference a permanent + // one, so it is an ordinary table in a test-only schema. + defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }() + // A future decision table carries policy_version_id the same way. + if _, err := tx.Exec(ctx, ` + CREATE SCHEMA policy_reference_test; + CREATE TABLE policy_reference_test.decisions ( + id uuid PRIMARY KEY, + policy_version_id uuid NOT NULL REFERENCES policy_versions (id) + )`); err != nil { + t.Fatalf("create referencing table: %v", err) + } + if _, err := tx.Exec(ctx, `INSERT INTO policy_reference_test.decisions (id, policy_version_id) VALUES ($1, $2)`, + uuid.New(), stored.ID().UUID()); err != nil { + t.Fatalf("insert record that references the version: %v", err) + } + if _, err := tx.Exec(ctx, `SAVEPOINT unknown_reference`); err != nil { + t.Fatalf("create savepoint: %v", err) + } + _, err = tx.Exec(ctx, `INSERT INTO policy_reference_test.decisions (id, policy_version_id) VALUES ($1, $2)`, uuid.New(), uuid.New()) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != foreignKeyViolationState { + t.Fatalf("insert record that references an unknown version error = %v, want a foreign key violation", err) + } + if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT unknown_reference`); err != nil { + t.Fatalf("roll back to savepoint: %v", err) + } + _, err = tx.Exec(ctx, `DELETE FROM policy_versions WHERE id = $1`, stored.ID().UUID()) + assertPolicyImmutable(t, "delete of a referenced version", err) + }) + + t.Run("concurrent publications get distinct version numbers", func(t *testing.T) { + fixture := newFixture(t) + // One connection per publisher, so they really race. + counting := &conflictCountingPolicies{ + PolicyRepository: postgresadapter.NewPolicyStore(newSizedPoolFor(ctx, t, fixture.databaseURL, concurrentPublishers)).Policies(), + } + publisher := policy.NewPublisher(counting, time.Now) + versions := make([]domain.PolicyVersion, concurrentPublishers) + errs := make([]error, concurrentPublishers) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range concurrentPublishers { + group.Go(func() { + <-start + versions[index], errs[index] = publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, + Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, + Policy: integrationPolicy(int32(60 + index)), + }) + }) + } + close(start) + group.Wait() + numbers := make([]int32, 0, concurrentPublishers) + for index, err := range errs { + if err != nil { + t.Fatalf("publisher %d error = %v", index, err) + } + numbers = append(numbers, versions[index].Version()) + } + slices.Sort(numbers) + for index, number := range numbers { + if number != int32(index+1) { + t.Fatalf("published version numbers = %v, want 1 to %d once each", numbers, concurrentPublishers) + } + } + fixture.assertVersionCount(t, concurrentPublishers) + // Whether publishers collide depends on scheduling, so the count is + // reported rather than asserted. + t.Logf("%d version number conflicts were retried", counting.conflicts.Load()) + }) + + t.Run("the demo seed inserts once under concurrent starts", func(t *testing.T) { + fixture := newFixture(t) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(newSizedPoolFor(ctx, t, fixture.databaseURL, concurrentSeeders)).Policies(), time.Now) + results := make([]policy.DemoSeedResult, concurrentSeeders) + errs := make([]error, concurrentSeeders) + start := make(chan struct{}) + var group sync.WaitGroup + for index := range concurrentSeeders { + group.Go(func() { + <-start + results[index], errs[index] = publisher.EnsureDemoProductPolicy(ctx) + }) + } + close(start) + group.Wait() + var created domain.PolicyVersion + for index, err := range errs { + if err != nil { + t.Fatalf("seeder %d error = %v", index, err) + } + if results[index].Created { + if !created.IsZero() { + t.Fatal("two seeders reported an insert") + } + created = results[index].Version + } + } + if created.IsZero() { + t.Fatal("no seeder reported an insert") + } + again, err := publisher.EnsureDemoProductPolicy(ctx) + if err != nil || again.Created { + t.Fatalf("repeated seed = %+v, %v; want a skip", again, err) + } + fixture.assertVersionCount(t, 1) + + demo, err := fixture.store.Policies().GetEffective(ctx, domain.ProductPolicyKey, created.CreatedAt()) + if err != nil { + t.Fatalf("GetEffective(product) error = %v", err) + } + assertSamePolicyVersion(t, demo, created) + if demo.Version() != 1 || demo.Kind() != domain.PolicyKindDemo || demo.Author() != domain.DemoPolicySeedAuthor || + demo.DocumentHash() != fixture.demoDraft(t).DocumentHash() || !demo.EffectiveAt().Equal(demo.CreatedAt()) { + t.Fatalf("seeded product policy = v%d %s by %s, want version 1 of the demo policy effective at publication", demo.Version(), demo.Kind(), demo.Author()) + } + }) + + t.Run("the demo seed skips existing versions without decoding them", func(t *testing.T) { + fixture := newFixture(t) + // A row of a future document layout that this build cannot decode. + futureHash := make([]byte, sha256.Size) + if _, err := rand.Read(futureHash); err != nil { + t.Fatalf("generate hash bytes: %v", err) + } + if _, err := fixture.pool.Exec(ctx, ` + INSERT INTO policy_versions (id, policy_key, version, kind, author, document, document_sha256) + VALUES ($1, 'product', 1, 'demo', 'system:future-build', '{"schema_version": 2}', $2)`, + uuid.New(), futureHash); err != nil { + t.Fatalf("insert a row of an unknown schema version: %v", err) + } + if _, err := fixture.store.Policies().GetLatest(ctx, domain.ProductPolicyKey); !errors.Is(err, domain.ErrInvalidPolicy) { + t.Fatalf("GetLatest(future layout) error = %v, want ErrInvalidPolicy", err) + } + result, err := policy.NewPublisher(fixture.store.Policies(), time.Now).EnsureDemoProductPolicy(ctx) + if err != nil || result.Created { + t.Fatalf("EnsureDemoProductPolicy() = %+v, %v; want a skip without error", result, err) + } + fixture.assertVersionCount(t, 1) + }) + + t.Run("a new pool reads the same versions after a restart", func(t *testing.T) { + fixture := newFixture(t) + firstPool := newPoolFor(ctx, t, fixture.databaseURL) + firstStore := postgresadapter.NewPolicyStore(firstPool) + written := []domain.PolicyVersion{ + fixture.publish(t, firstStore.Policies(), 1, time.Time{}, integrationPolicy(81)), + fixture.publish(t, firstStore.Policies(), 2, time.Time{}, integrationPolicy(82)), + } + firstPool.Close() + + restarted := postgresadapter.NewPolicyStore(newPoolFor(ctx, t, fixture.databaseURL)) + for _, want := range written { + got, err := restarted.Policies().GetByID(ctx, want.ID()) + if err != nil { + t.Fatalf("GetByID(%s) after restart error = %v", want.ID(), err) + } + assertSamePolicyVersion(t, got, want) + } + latest, err := restarted.Policies().GetLatest(ctx, domain.ProductPolicyKey) + if err != nil || latest.ID() != written[1].ID() { + t.Fatalf("GetLatest() after restart = v%d, %v; want v2", latest.Version(), err) + } + if result, err := policy.NewPublisher(restarted.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil || result.Created { + t.Fatalf("demo seed after restart = %+v, %v; want no insert", result, err) + } + }) +} + +// integrationPolicy returns a valid calibrated policy for integration +// fixtures. Its values differ from the demo policy, and maxPending tells +// versions apart. +func integrationPolicy(maxPending int32) domain.ProductPolicy { + return domain.ProductPolicy{ + Invitations: domain.InvitationPolicy{ + ResponseDeadlineOptions: []domain.CalendarDays{1, 4, 9}, + DefaultResponseDeadline: 4, + MaxPendingPerNeed: maxPending, + RepeatAfterDecline: 8, + InterviewProposalDeadline: 2, + NoDealPause: 6, + }, + OrganizationQuotas: domain.OrganizationQuotaPolicy{ + InvitationWindow: 2, + CardViewWindow: 6, + TierE0: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 1, DistinctCardViewsPerWindow: 2}, + TierE1: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 3, DistinctCardViewsPerWindow: 4}, + TierE2: domain.OrganizationTierQuota{Active: true, InvitationsPerWindow: 5, DistinctCardViewsPerWindow: 6}, + }, + Assessment: domain.AssessmentPolicy{ + Calibration: domain.AssessmentCalibrationCalibrated, + SameGradeRetryAfter: 4, + MaxAttemptsPerWindow: 5, + AttemptWindow: 40, + PromotionMinInterval: 20, + ConfirmationThreshold: 7000, + HighStrengthThreshold: 8500, + PracticeRequired: false, + StopRule: domain.AssessmentStopRule{ + MinScoredItems: 4, + MaxScoredItems: 12, + SeedItems: 1, + UpperProbability: 9200, + LowerProbability: 800, + MaxStandardError: 3500, + }, + }, + Identity: domain.IdentityPolicy{ + VerificationTokenLifetime: 6, + UnverifiedAccountLifetime: 2, + SessionIdleTimeout: 3, + SessionAbsoluteLifetime: 1, + }, + SearchStatus: domain.SearchStatusPolicy{SearchingConfirmationInterval: 10}, + } +} + +// draft builds a numbered calibrated test draft; a zero effectiveAt makes it +// effective at publication. +func (fixture policyFixture) draft(t *testing.T, number int32, effectiveAt time.Time, values domain.ProductPolicy) domain.PolicyVersionDraft { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, + Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, + EffectiveAt: effectiveAt, + Policy: values, + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft(v%d) error = %v", number, err) + } + numbered, err := draft.WithVersion(number) + if err != nil { + t.Fatalf("WithVersion(%d) error = %v", number, err) + } + return numbered +} + +// demoDraft builds the draft the seed stores, for comparison only. +func (fixture policyFixture) demoDraft(t *testing.T) domain.PolicyVersionDraft { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV1(), + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft(demo) error = %v", err) + } + return draft +} + +func (fixture policyFixture) publish( + t *testing.T, + policies outbound.PolicyRepository, + number int32, + effectiveAt time.Time, + values domain.ProductPolicy, +) domain.PolicyVersion { + t.Helper() + stored, err := policies.Create(fixture.ctx, fixture.draft(t, number, effectiveAt, values)) + if err != nil { + t.Fatalf("Create(v%d) error = %v", number, err) + } + return stored +} + +func (fixture policyFixture) assertEffective(t *testing.T, at time.Time, want domain.PolicyVersion) { + t.Helper() + got, err := fixture.store.Policies().GetEffective(fixture.ctx, domain.ProductPolicyKey, at) + if err != nil { + t.Fatalf("GetEffective(%s) error = %v", at, err) + } + if got.ID() != want.ID() { + t.Fatalf("GetEffective(%s) = v%d, want v%d", at, got.Version(), want.Version()) + } +} + +// readMaxPending reads one value from the stored jsonb document directly. +func (fixture policyFixture) readMaxPending(t *testing.T, id domain.PolicyVersionID) int32 { + t.Helper() + var value int32 + err := fixture.pool.QueryRow(fixture.ctx, + `SELECT (document -> 'invitations' ->> 'max_pending_per_need')::integer FROM policy_versions WHERE id = $1`, + id.UUID()).Scan(&value) + if err != nil { + t.Fatalf("read stored max_pending_per_need: %v", err) + } + return value +} + +func (fixture policyFixture) assertVersionCount(t *testing.T, want int) { + t.Helper() + var count int + if err := fixture.pool.QueryRow(fixture.ctx, `SELECT count(*) FROM policy_versions`).Scan(&count); err != nil { + t.Fatalf("count policy versions: %v", err) + } + if count != want { + t.Fatalf("policy_versions has %d rows, want %d", count, want) + } +} + +// newSizedPoolFor opens a pool with maxConns connections to databaseURL, so +// goroutines run at the same time instead of queueing for connections. +func newSizedPoolFor(ctx context.Context, t *testing.T, databaseURL string, maxConns int32) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(databaseURL) + if err != nil { + t.Fatalf("parse database URL: %v", err) + } + poolConfig.MaxConns = maxConns + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create sized PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// assertDatabaseTime checks that a time stamped by PostgreSQL is close to +// the moment the test started the statement. +func assertDatabaseTime(t *testing.T, name string, got, before time.Time) { + t.Helper() + if got.Before(before.Add(-databaseClockTolerance)) || got.After(time.Now().Add(databaseClockTolerance)) { + t.Fatalf("%s = %s, want the database clock near %s", name, got, before) + } +} + +// assertPolicyImmutable checks the raw trigger error and its mapping. +func assertPolicyImmutable(t *testing.T, statement string, err error) { + t.Helper() + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != policyImmutableSQLState || pgError.ConstraintName != policyImmutableConstraint { + t.Fatalf("%s error = %v, want SQLSTATE %s on %s", statement, err, policyImmutableSQLState, policyImmutableConstraint) + } + if mapped := postgresadapter.MapPolicyErrorForIntegrationTest(err); !errors.Is(mapped, outbound.ErrPolicyVersionImmutable) { + t.Fatalf("%s mapped error = %v, want ErrPolicyVersionImmutable", statement, mapped) + } + if strings.Contains(err.Error(), "operator:") { + t.Fatalf("%s error quotes row values: %v", statement, err) + } +} + +func assertSamePolicyVersion(t *testing.T, got, want domain.PolicyVersion) { + t.Helper() + if got.ID() != want.ID() || got.Key() != want.Key() || got.Version() != want.Version() || got.Kind() != want.Kind() || + got.Author() != want.Author() || !got.EffectiveAt().Equal(want.EffectiveAt()) || !got.CreatedAt().Equal(want.CreatedAt()) || + got.DocumentHash() != want.DocumentHash() || string(got.Document()) != string(want.Document()) { + t.Fatalf("policy version = %s %s v%d, want %s %s v%d with the same metadata and document", + got.ID(), got.Key(), got.Version(), want.ID(), want.Key(), want.Version()) + } +} + +// conflictCountingPolicies counts version number conflicts seen by Create. +type conflictCountingPolicies struct { + outbound.PolicyRepository + + conflicts atomic.Int64 +} + +func (policies *conflictCountingPolicies) Create(ctx context.Context, draft domain.PolicyVersionDraft) (domain.PolicyVersion, error) { + stored, err := policies.PolicyRepository.Create(ctx, draft) + if errors.Is(err, outbound.ErrPolicyVersionConflict) { + policies.conflicts.Add(1) + } + return stored, err +} diff --git a/backend/integration_test/postgres_helpers_test.go b/backend/integration_test/postgres_helpers_test.go new file mode 100644 index 0000000..35ce641 --- /dev/null +++ b/backend/integration_test/postgres_helpers_test.go @@ -0,0 +1,158 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/rand" + "io/fs" + "net/url" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/db" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +// applyMigrations brings the database at databaseURL to the latest embedded +// schema with the same runner the backend uses at startup. +func applyMigrations(ctx context.Context, t *testing.T, databaseURL string) { + t.Helper() + migrator := newMigrator(t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations: %v", err) + } +} + +func newMigrator(t *testing.T, databaseURL string) *postgresadapter.Migrator { + t.Helper() + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("load embedded migrations: %v", err) + } + migrator, err := postgresadapter.NewMigrator(databaseURL, migrations) + if err != nil { + t.Fatalf("create migrator: %v", err) + } + t.Cleanup(func() { + if err := migrator.Close(); err != nil { + t.Errorf("close migrator: %v", err) + } + }) + return migrator +} + +// embeddedMigrationCount derives the expected count from the embedded files. +func embeddedMigrationCount(t *testing.T) int { + t.Helper() + migrations, err := db.Migrations() + if err != nil { + t.Fatalf("load embedded migrations: %v", err) + } + files, err := fs.Glob(migrations, "*.sql") + if err != nil { + t.Fatalf("list embedded migrations: %v", err) + } + if len(files) == 0 { + t.Fatal("no embedded migrations") + } + return len(files) +} + +// newPool opens a pool to the bootstrap database and closes it with t. +func (env *testEnvironment) newPool(ctx context.Context, t *testing.T) *pgxpool.Pool { + t.Helper() + return newPoolFor(ctx, t, env.Config.DatabaseURL) +} + +func newPoolFor(ctx context.Context, t *testing.T, databaseURL string) *pgxpool.Pool { + t.Helper() + pool, err := postgresadapter.NewPool(ctx, databaseURL) + if err != nil { + t.Fatalf("create PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// newPoolWithMaxConns opens a pool sized for a concurrency test, so goroutines +// run their transactions at the same time instead of queueing for connections. +func (env *testEnvironment) newPoolWithMaxConns(ctx context.Context, t *testing.T, maxConns int32) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.MaxConns = maxConns + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create sized PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// newPoolWithLockTimeout opens a pool whose sessions fail a lock wait after +// timeout, so a test can prove that a statement never waits for a lock. +func (env *testEnvironment) newPoolWithLockTimeout(ctx context.Context, t *testing.T, timeout time.Duration) *pgxpool.Pool { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.ConnConfig.RuntimeParams["lock_timeout"] = strconv.FormatInt(timeout.Milliseconds(), 10) + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create PostgreSQL pool with a lock timeout: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// createIsolatedDatabase creates an empty database in the bootstrap container +// for tests that must change the whole schema, and drops it with t. +func (env *testEnvironment) createIsolatedDatabase(ctx context.Context, t *testing.T) string { + t.Helper() + if env.Config.DatabaseURL == "" { + t.Fatal("PostgreSQL was not selected in bootstrap") + } + admin := env.newPool(ctx, t) + name := "isolated_" + strings.ToLower(rand.Text()) + identifier := pgx.Identifier{name}.Sanitize() + if _, err := admin.Exec(ctx, "CREATE DATABASE "+identifier); err != nil { + t.Fatalf("create isolated database: %v", err) + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + if _, err := admin.Exec(ctx, "DROP DATABASE IF EXISTS "+identifier+" WITH (FORCE)"); err != nil { + t.Errorf("drop isolated database: %v", err) + } + }) + databaseURL, err := url.Parse(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + databaseURL.Path = "/" + name + return databaseURL.String() +} + +// truncateTables resets shared tables between sequential subtests. Callers +// must not run subtests that use these tables in parallel. PostgreSQL refuses +// to truncate a table that another table references unless both are listed, +// so a test that truncates users names usersDependentTables. +func truncateTables(ctx context.Context, t *testing.T, pool *pgxpool.Pool, tables ...pgx.Identifier) { + t.Helper() + names := make([]string, 0, len(tables)) + for _, table := range tables { + names = append(names, table.Sanitize()) + } + if _, err := pool.Exec(ctx, "TRUNCATE "+strings.Join(names, ", ")); err != nil { + t.Fatalf("truncate test tables: %v", err) + } +} diff --git a/backend/integration_test/postgres_migrations_test.go b/backend/integration_test/postgres_migrations_test.go new file mode 100644 index 0000000..191adf1 --- /dev/null +++ b/backend/integration_test/postgres_migrations_test.go @@ -0,0 +1,302 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +const ( + migrationTestTimeout = 3 * time.Minute + concurrentMigrators = 4 +) + +const ( + // identityMigrationVersion creates identityTableNames. + identityMigrationVersion = 2 + // policyMigrationVersion creates policyTableNames and policyFunctionNames. + policyMigrationVersion = 3 + // consumerMigrationVersion creates consumerTableNames. + consumerMigrationVersion = 5 + // deliveryMigrationVersion creates deliveryTableNames (mail requests, + // deliveries, and their attempts) and deliveryFunctionNames. + deliveryMigrationVersion = 6 + // mailQuotaMigrationVersion creates mailQuotaTableNames. + mailQuotaMigrationVersion = 7 + // scheduledJobMigrationVersion creates scheduledJobTableNames. + scheduledJobMigrationVersion = 8 + // organizationMigrationVersion creates organizationTableNames and + // organizationFunctionNames. + organizationMigrationVersion = 10 + // assessmentBankMigrationVersion creates assessmentBankTableNames and + // assessmentBankFunctionNames. + assessmentBankMigrationVersion = 11 +) + +var ( + // Tables created by 00001, 00002, 00003, 00005, 00006, 00007, 00008, and + // 00010, and 00011. + outboxTables = []string{"outbox_events"} + identityTableNames = []string{"users", "email_tokens", "sessions"} + policyTableNames = []string{"policy_versions"} + consumerTableNames = []string{"consumer_processed_events", "consumer_dead_letters"} + deliveryTableNames = []string{"mail_requests", "deliveries", "delivery_attempts"} + mailQuotaTableNames = []string{"mail_quota_usage", "mail_quota_reservations"} + scheduledJobTableNames = []string{"scheduled_jobs"} + // organizationTableNames lists the tables of migration 00010. + organizationTableNames = []string{"organizations", "organization_representatives", "memberships"} + // assessmentBankTableNames lists the tables of migration 00011. + assessmentBankTableNames = []string{"assessment_families", "assessment_category_openings"} + // Trigger functions created by 00003, 00006, 00010, and 00011. + policyFunctionNames = []string{"policy_versions_refuse_change()", "policy_versions_stamp_creation()"} + deliveryFunctionNames = []string{"deliveries_refuse_content_change()", "delivery_attempts_refuse_update()"} + organizationFunctionNames = []string{"organizations_require_owner()"} + assessmentBankFunctionNames = []string{ + "assessment_families_stamp_creation()", "assessment_families_guard_update()", "assessment_families_refuse_removal()", + "assessment_category_openings_stamp()", "assessment_category_openings_refuse_change()", + } +) + +func TestPostgresMigrations(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + total := embeddedMigrationCount(t) + + t.Run("bootstrap database has every migration applied", func(t *testing.T) { + assertAllApplied(ctx, t, newMigrator(t, env.Config.DatabaseURL), total) + }) + + t.Run("up, down to zero, and up again on an isolated database", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + + applied, err := migrator.Up(ctx) + if err != nil { + t.Fatalf("first Up() error = %v", err) + } + if len(applied) != total { + t.Fatalf("first Up() applied %d migrations, want %d", len(applied), total) + } + assertTablesExist(ctx, t, pool, true, outboxTables...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + assertTablesExist(ctx, t, pool, true, policyTableNames...) + assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...) + assertTablesExist(ctx, t, pool, true, consumerTableNames...) + assertTablesExist(ctx, t, pool, true, deliveryTableNames...) + assertFunctionsExist(ctx, t, pool, true, deliveryFunctionNames...) + assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...) + assertTablesExist(ctx, t, pool, true, scheduledJobTableNames...) + assertTablesExist(ctx, t, pool, true, organizationTableNames...) + assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...) + assertTablesExist(ctx, t, pool, true, assessmentBankTableNames...) + assertFunctionsExist(ctx, t, pool, true, assessmentBankFunctionNames...) + + identityRolledBack, policyRolledBack, consumerRolledBack, deliveryRolledBack, mailQuotaRolledBack := false, false, false, false, false + scheduledJobRolledBack, organizationRolledBack, assessmentBankRolledBack := false, false, false + for rolledBack := 0; ; rolledBack++ { + result, err := migrator.DownOne(ctx) + if errors.Is(err, postgresadapter.ErrNoMigrationToRollBack) { + if rolledBack != total { + t.Fatalf("rolled back %d migrations, want %d", rolledBack, total) + } + break + } + if err != nil { + t.Fatalf("DownOne() after %d rollbacks error = %v", rolledBack, err) + } + if result.Version == assessmentBankMigrationVersion { + // The bank migration removes its tables and functions and + // leaves the policy table its openings referenced. + assertTablesExist(ctx, t, pool, false, assessmentBankTableNames...) + assertFunctionsExist(ctx, t, pool, false, assessmentBankFunctionNames...) + assertTablesExist(ctx, t, pool, true, policyTableNames...) + assessmentBankRolledBack = true + } + if result.Version == organizationMigrationVersion { + // The organization migration removes its tables and its + // function and leaves the identity tables they reference. + assertTablesExist(ctx, t, pool, false, organizationTableNames...) + assertFunctionsExist(ctx, t, pool, false, organizationFunctionNames...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + organizationRolledBack = true + } + if result.Version == scheduledJobMigrationVersion { + // The scheduled job migration removes only its own table. + assertTablesExist(ctx, t, pool, false, scheduledJobTableNames...) + assertTablesExist(ctx, t, pool, true, mailQuotaTableNames...) + scheduledJobRolledBack = true + } + if result.Version == mailQuotaMigrationVersion { + // The quota migration removes only its counter table; the + // deliveries it does not reference stay. + assertTablesExist(ctx, t, pool, false, mailQuotaTableNames...) + assertTablesExist(ctx, t, pool, true, deliveryTableNames...) + mailQuotaRolledBack = true + } + if result.Version == deliveryMigrationVersion { + // The delivery migration removes its tables and functions + // and leaves the identity tables they referenced. + assertTablesExist(ctx, t, pool, false, deliveryTableNames...) + assertFunctionsExist(ctx, t, pool, false, deliveryFunctionNames...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + deliveryRolledBack = true + } + if result.Version == consumerMigrationVersion { + // The consumer migration removes only its own tables. + assertTablesExist(ctx, t, pool, false, consumerTableNames...) + assertTablesExist(ctx, t, pool, true, outboxTables...) + consumerRolledBack = true + } + if result.Version == policyMigrationVersion { + // The policy migration rolls back its table, triggers, and + // function and leaves the identity tables. + assertTablesExist(ctx, t, pool, false, policyTableNames...) + assertFunctionsExist(ctx, t, pool, false, policyFunctionNames...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + policyRolledBack = true + } + if result.Version == identityMigrationVersion { + // The identity migration rolls back on its own and leaves the + // outbox migration before it. + assertTablesExist(ctx, t, pool, false, identityTableNames...) + assertTablesExist(ctx, t, pool, true, outboxTables...) + identityRolledBack = true + } + } + if !identityRolledBack || !policyRolledBack || !consumerRolledBack || !deliveryRolledBack || !mailQuotaRolledBack || + !scheduledJobRolledBack || !organizationRolledBack || !assessmentBankRolledBack { + t.Fatalf("migrations %d, %d, %d, %d, %d, %d, %d, and %d were not all rolled back", + identityMigrationVersion, policyMigrationVersion, consumerMigrationVersion, deliveryMigrationVersion, mailQuotaMigrationVersion, + scheduledJobMigrationVersion, organizationMigrationVersion, assessmentBankMigrationVersion) + } + assertTablesExist(ctx, t, pool, false, outboxTables...) + assertTablesExist(ctx, t, pool, false, identityTableNames...) + assertTablesExist(ctx, t, pool, false, policyTableNames...) + var leftovers int + err = pool.QueryRow(ctx, ` + SELECT count(*) FROM pg_catalog.pg_class AS c + JOIN pg_catalog.pg_namespace AS n ON n.oid = c.relnamespace + WHERE n.nspname = 'public' AND c.relname NOT LIKE 'goose_db_version%'`).Scan(&leftovers) + if err != nil { + t.Fatalf("count leftover relations: %v", err) + } + if leftovers != 0 { + t.Fatalf("%d relations remain after rolling back every migration", leftovers) + } + var leftoverFunctions int + err = pool.QueryRow(ctx, ` + SELECT count(*) FROM pg_catalog.pg_proc AS p + JOIN pg_catalog.pg_namespace AS n ON n.oid = p.pronamespace + WHERE n.nspname = 'public'`).Scan(&leftoverFunctions) + if err != nil { + t.Fatalf("count leftover functions: %v", err) + } + if leftoverFunctions != 0 { + t.Fatalf("%d functions remain after rolling back every migration", leftoverFunctions) + } + + applied, err = migrator.Up(ctx) + if err != nil { + t.Fatalf("second Up() error = %v", err) + } + if len(applied) != total { + t.Fatalf("second Up() applied %d migrations, want %d", len(applied), total) + } + assertTablesExist(ctx, t, pool, true, outboxTables...) + assertTablesExist(ctx, t, pool, true, identityTableNames...) + assertTablesExist(ctx, t, pool, true, policyTableNames...) + assertFunctionsExist(ctx, t, pool, true, policyFunctionNames...) + assertTablesExist(ctx, t, pool, true, consumerTableNames...) + assertTablesExist(ctx, t, pool, true, deliveryTableNames...) + assertTablesExist(ctx, t, pool, true, organizationTableNames...) + assertFunctionsExist(ctx, t, pool, true, organizationFunctionNames...) + assertTablesExist(ctx, t, pool, true, assessmentBankTableNames...) + assertFunctionsExist(ctx, t, pool, true, assessmentBankFunctionNames...) + assertAllApplied(ctx, t, migrator, total) + }) + + t.Run("concurrent runners apply each migration once", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrators := make([]*postgresadapter.Migrator, concurrentMigrators) + for index := range migrators { + migrators[index] = newMigrator(t, databaseURL) + } + applied := make([]int, len(migrators)) + errs := make([]error, len(migrators)) + start := make(chan struct{}) + var group sync.WaitGroup + for index, migrator := range migrators { + group.Go(func() { + <-start + results, err := migrator.Up(ctx) + applied[index], errs[index] = len(results), err + }) + } + close(start) + group.Wait() + + sum := 0 + for index, err := range errs { + if err != nil { + t.Fatalf("runner %d Up() error = %v", index, err) + } + sum += applied[index] + } + if sum != total { + t.Fatalf("runners applied %d migrations in total, want %d", sum, total) + } + assertAllApplied(ctx, t, migrators[0], total) + }) +} + +func assertAllApplied(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator, total int) { + t.Helper() + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("Status() error = %v", err) + } + if len(statuses) != total { + t.Fatalf("Status() lists %d migrations, want %d", len(statuses), total) + } + for _, status := range statuses { + if !status.Applied { + t.Fatalf("migration %s is pending", status.Name) + } + } +} + +func assertTablesExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, tables ...string) { + t.Helper() + for _, table := range tables { + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regclass($1) IS NOT NULL`, "public."+table).Scan(&exists); err != nil { + t.Fatalf("check table %s: %v", table, err) + } + if exists != want { + t.Fatalf("%s exists = %t, want %t", table, exists, want) + } + } +} + +func assertFunctionsExist(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool, signatures ...string) { + t.Helper() + for _, signature := range signatures { + var exists bool + if err := pool.QueryRow(ctx, `SELECT to_regprocedure($1) IS NOT NULL`, "public."+signature).Scan(&exists); err != nil { + t.Fatalf("check function %s: %v", signature, err) + } + if exists != want { + t.Fatalf("function %s exists = %t, want %t", signature, exists, want) + } + } +} diff --git a/backend/integration_test/practice_runner_fixture_test.go b/backend/integration_test/practice_runner_fixture_test.go new file mode 100644 index 0000000..45b3879 --- /dev/null +++ b/backend/integration_test/practice_runner_fixture_test.go @@ -0,0 +1,318 @@ +//go:build integration + +package integration_test + +import ( + "crypto/sha256" + "crypto/tls" + "encoding/pem" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + coderunner "lincodex/backend/internal/adapter/secondary/code_runner" + "lincodex/backend/internal/adapter/secondary/code_runner/api" +) + +const ( + practiceRunnerToken = "fixture-token-0123456789abcdef0123456789abcdef" + practiceRunnerRunKey = "fixture-run-key-0123456789abcdef0123456789abcdef" + // practiceRunnerTimeout is the request timeout of the client under test. + // It is short so that a stalled answer ends a try quickly. + practiceRunnerTimeout = 750 * time.Millisecond + // practiceRunnerStall outlasts practiceRunnerTimeout. + practiceRunnerStall = 10 * time.Second + // practiceRunnerPrefix is the path of a run in the runner protocol. + practiceRunnerPrefix = "/v1/runs/" +) + +// Sources of the two programs that the fixture recognizes. Each reads two +// integers and prints their sum. +const ( + practicePythonSum = "print(sum(map(int, input().split())))\n" + practiceGoSum = "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar a, b int\n\tfmt.Scan(&a, &b)\n\tfmt.Println(a + b)\n}\n" +) + +// runnerCall is what the fixture saw on the wire. +type runnerCall struct { + Method string + Path string + Header http.Header + Body []byte +} + +// fixtureRun is one run that the fixture holds. +type fixtureRun struct { + ID string + Request api.RunRequest + Body []byte + Result api.RunResult + fingerprint [sha256.Size]byte +} + +// practiceRunnerFixture is a local stand-in for the code runner. It speaks +// the protocol of api/runner over TLS 1.3 like the production runner: a +// bearer token, PUT and GET of /v1/runs/{id}, a run held once per run ID, and +// 422 for the same ID with another payload. It does not run code: it +// recognizes the two sum programs of this test file and compares their +// output with the expected output of each test, so the output of a program +// follows its source and its input. +type practiceRunnerFixture struct { + server *httptest.Server + + mu sync.Mutex + runs map[string]*fixtureRun + order []string + calls []runnerCall + // holding keeps every run running until it is turned off. + holding bool + // afterAccept is applied once to the next newly accepted run: "cut" + // drops the connection without an answer, "stall" delays the answer past + // the client timeout. In both cases the run exists on the runner. + afterAccept string +} + +func newPracticeRunnerFixture(t *testing.T) *practiceRunnerFixture { + t.Helper() + fixture := &practiceRunnerFixture{runs: map[string]*fixtureRun{}} + fixture.server = httptest.NewUnstartedServer(http.HandlerFunc(fixture.serve)) + fixture.server.TLS = &tls.Config{MinVersion: tls.VersionTLS13} + fixture.server.StartTLS() + t.Cleanup(fixture.server.Close) + return fixture +} + +// client builds a new client of the runner, as a restarted process would. +func (fixture *practiceRunnerFixture) client(t *testing.T) *coderunner.Client { + t.Helper() + client, err := coderunner.NewClient(coderunner.Settings{ + BaseURL: fixture.server.URL, Token: practiceRunnerToken, RunKey: practiceRunnerRunKey, + CAPEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: fixture.server.Certificate().Raw}), + RequestTimeout: practiceRunnerTimeout, + }) + if err != nil { + t.Fatalf("coderunner.NewClient() error = %v", err) + } + return client +} + +// stop shuts the runner down; later connections are refused. +func (fixture *practiceRunnerFixture) stop() { fixture.server.Close() } + +func (fixture *practiceRunnerFixture) hold(holding bool) { + fixture.mu.Lock() + defer fixture.mu.Unlock() + fixture.holding = holding +} + +func (fixture *practiceRunnerFixture) failNextAccept(how string) { + fixture.mu.Lock() + defer fixture.mu.Unlock() + fixture.afterAccept = how +} + +func (fixture *practiceRunnerFixture) runCount() int { + fixture.mu.Lock() + defer fixture.mu.Unlock() + return len(fixture.order) +} + +// runIDsSince returns the run IDs that the fixture accepted after it held +// the first count runs. +func (fixture *practiceRunnerFixture) runIDsSince(count int) []string { + fixture.mu.Lock() + defer fixture.mu.Unlock() + return append([]string(nil), fixture.order[count:]...) +} + +func (fixture *practiceRunnerFixture) run(id string) (fixtureRun, bool) { + fixture.mu.Lock() + defer fixture.mu.Unlock() + run, found := fixture.runs[id] + if !found { + return fixtureRun{}, false + } + return *run, true +} + +// callsFor returns the requests that named the run. +func (fixture *practiceRunnerFixture) callsFor(id string) []runnerCall { + fixture.mu.Lock() + defer fixture.mu.Unlock() + var calls []runnerCall + for _, call := range fixture.calls { + if call.Path == practiceRunnerPrefix+id { + calls = append(calls, call) + } + } + return calls +} + +func (fixture *practiceRunnerFixture) serve(writer http.ResponseWriter, request *http.Request) { + body, _ := io.ReadAll(request.Body) + fixture.mu.Lock() + fixture.calls = append(fixture.calls, runnerCall{ + Method: request.Method, Path: request.URL.Path, Header: request.Header.Clone(), Body: body, + }) + fixture.mu.Unlock() + + if request.Header.Get("Authorization") != "Bearer "+practiceRunnerToken { + writeRunnerProblem(writer, http.StatusUnauthorized, api.ProblemCodeUnauthenticated) + return + } + id := strings.TrimPrefix(request.URL.Path, practiceRunnerPrefix) + switch request.Method { + case http.MethodPut: + fixture.put(writer, request, id, body) + case http.MethodGet: + fixture.get(writer, id) + default: + writeRunnerProblem(writer, http.StatusMethodNotAllowed, api.ProblemCodeMethodNotAllowed) + } +} + +func (fixture *practiceRunnerFixture) put(writer http.ResponseWriter, request *http.Request, id string, body []byte) { + var payload api.RunRequest + if err := payload.UnmarshalJSON(body); err != nil { + writeRunnerProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed) + return + } + runID, err := uuid.Parse(id) + if err != nil { + writeRunnerProblem(writer, http.StatusBadRequest, api.ProblemCodeValidationFailed) + return + } + fingerprint := sha256.Sum256(body) + + fixture.mu.Lock() + if existing, found := fixture.runs[id]; found { + defer fixture.mu.Unlock() + if existing.fingerprint != fingerprint { + writeRunnerProblem(writer, http.StatusUnprocessableEntity, api.ProblemCodeIdempotencyKeyReused) + return + } + writeRunnerStatus(writer, http.StatusOK, fixture.statusLocked(existing)) + return + } + fixture.runs[id] = &fixtureRun{ + ID: id, Request: payload, Body: body, Result: evaluateFixtureRun(payload), fingerprint: fingerprint, + } + fixture.order = append(fixture.order, id) + action := fixture.afterAccept + fixture.afterAccept = "" + fixture.mu.Unlock() + + switch action { + case "cut": + // The run is accepted and the connection ends without an answer. + panic(http.ErrAbortHandler) + case "stall": + select { + case <-time.After(practiceRunnerStall): + case <-request.Context().Done(): + return + } + } + writeRunnerStatus(writer, http.StatusAccepted, api.RunStatus{RunID: runID, State: api.RunStateRunning}) +} + +func (fixture *practiceRunnerFixture) get(writer http.ResponseWriter, id string) { + fixture.mu.Lock() + defer fixture.mu.Unlock() + run, found := fixture.runs[id] + if !found { + writeRunnerProblem(writer, http.StatusNotFound, api.ProblemCodeNotFound) + return + } + writeRunnerStatus(writer, http.StatusOK, fixture.statusLocked(run)) +} + +func (fixture *practiceRunnerFixture) statusLocked(run *fixtureRun) api.RunStatus { + status := api.RunStatus{RunID: uuid.MustParse(run.ID), State: api.RunStateRunning} + if !fixture.holding { + status.State = api.RunStateFinished + status.Result = api.NewOptRunResult(run.Result) + } + return status +} + +// evaluateFixtureRun produces the result of a run: every test of a group runs +// until the first one that fails, and a failed public test carries the output +// of the program as its diagnostic, which the practice API shows. +func evaluateFixtureRun(request api.RunRequest) api.RunResult { + result := api.RunResult{Outcome: api.RunOutcomeAccepted, DurationMs: 25} + for _, group := range request.Groups { + groupResult := api.GroupResult{ + ID: group.ID, Visibility: group.Visibility, Outcome: api.RunOutcomeAccepted, TotalTests: int32(len(group.Tests)), + } + for _, test := range group.Tests { + output := fixtureProgramOutput(request.Source, test.Input) + testResult := api.TestResult{ID: test.ID, Outcome: api.RunOutcomeAccepted, TimeMs: 3, WallTimeMs: 4, MemoryKB: 1024} + if output != strings.TrimSpace(test.ExpectedOutput) { + testResult.Outcome = api.RunOutcomeWrongAnswer + if group.Visibility == api.TestVisibilityPublic { + testResult.Diagnostic = api.NewOptString("got " + output) + } + groupResult.Outcome = api.RunOutcomeWrongAnswer + groupResult.Tests = append(groupResult.Tests, testResult) + break + } + groupResult.PassedTests++ + groupResult.Tests = append(groupResult.Tests, testResult) + } + if result.Outcome == api.RunOutcomeAccepted { + result.Outcome = groupResult.Outcome + } + result.Groups = append(result.Groups, groupResult) + } + return result +} + +// fixtureProgramOutput is the output of the sum programs for an input: the +// sum of its integer words. Another program prints nothing. +func fixtureProgramOutput(source, input string) string { + if !strings.Contains(source, "sum(map(int, input().split()))") && !strings.Contains(source, "fmt.Println(a + b)") { + return "" + } + total := 0 + for _, word := range strings.Fields(input) { + if value, err := strconv.Atoi(word); err == nil { + total += value + } + } + return strconv.Itoa(total) +} + +func writeRunnerStatus(writer http.ResponseWriter, code int, status api.RunStatus) { + // The generated types encode themselves; json.Marshal cannot encode an + // unset optional field. + body, err := status.MarshalJSON() + if err != nil { + panic(err) + } + writeRunnerJSON(writer, code, "application/json", body) +} + +func writeRunnerProblem(writer http.ResponseWriter, code int, problem api.ProblemCode) { + body, err := (&api.Problem{ + Type: "urn:lincodex:problem:" + string(problem), Title: "Problem", Status: int32(code), Code: problem, + }).MarshalJSON() + if err != nil { + panic(err) + } + writeRunnerJSON(writer, code, "application/problem+json", body) +} + +func writeRunnerJSON(writer http.ResponseWriter, code int, contentType string, body []byte) { + writer.Header().Set("Content-Type", contentType) + writer.Header().Set("Content-Length", strconv.Itoa(len(body))) + writer.WriteHeader(code) + _, _ = writer.Write(body) +} diff --git a/backend/integration_test/privacy_cohort_test.go b/backend/integration_test/privacy_cohort_test.go new file mode 100644 index 0000000..7ee9436 --- /dev/null +++ b/backend/integration_test/privacy_cohort_test.go @@ -0,0 +1,248 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/policy" + + "github.com/google/uuid" +) + +func TestOrganizationAnonymousCandidateProjectionHonorsC2AndHiding(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), candidatePrivacyTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: now} + policies := postgresadapter.NewPolicyStore(pool) + if _, err := policy.NewPublisher(policies.Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + fixture := candidatePrivacyFixture{ + ctx: ctx, pool: pool, queries: sqlc.New(pool), identity: identity, + organizations: organizationFixture{ + ctx: ctx, pool: pool, identity: identity, + transactor: postgresadapter.NewTransactor(pool), now: now, + }, + ledger: postgresadapter.NewConsentStore(pool), now: now, + } + truncateTables(ctx, t, pool, usersDependentTables...) + owner := fixture.organizations.employer(t, "owner@example.test") + organization := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization"), now) + organizationB := fixture.organizations.create(t, owner, fixture.organizations.completeProfile(t, "Projection test organization B"), now) + profiles := candidateProfileFixture{ctx: ctx, pool: pool, queries: fixture.queries, identity: identity, now: now} + + visible := make([]uuid.UUID, 0, 5) + for index := range 5 { + candidate := fixture.candidate(t, fmt.Sprintf("visible-%d@example.test", index)) + verifyPrivacyCohortCandidate(t, fixture, candidate) + consent := fixture.grant(t, candidate.ID, domain.ConsentPurposePublication, privacyC2Version, now.Add(time.Duration(index)*time.Second)) + fixture.publish(t, candidate.ID, consent.ID(), 0, + domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, + domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility, + ) + profiles.save(t, candidate.ID, domain.CandidateProfileInput{ + FullName: confirmedDecision("Private Name Marker"), + Email: confirmedDecision("private-contact-marker@example.test"), + Stack: privacyCohortConfirmedItems( + "go", "UniqueStackMarker", + ), + Roles: privacyCohortConfirmedItems(domain.ProfileRole{Specialization: domain.SpecializationBackend, SelfAssessedGrade: domain.GradeJunior}), + Experience: privacyCohortConfirmedItems(domain.ProfileExperience{ + EmployerName: "Private Employer Marker", Specialization: domain.SpecializationBackend, + StartedOn: "2020-01", EndedOn: "2024-12", Summary: "Private Summary Marker", + }), + SoftSkills: privacyCohortConfirmedItems("Private Soft Skill Marker"), + Location: confirmedDecision("Private Location Marker"), + SalaryMinimum: confirmedDecision(domain.ProfileSalaryMinimum{ + Amount: 180_000, TaxBasis: domain.ProfileTaxNet, + }), + }, 0) + if _, err := fixture.queries.InsertCandidateQuestionnaire(ctx, sqlc.InsertCandidateQuestionnaireParams{ + UserID: uuidParam(candidate.ID), WorkFormats: []string{"remote"}, At: timeParam(now), + }); err != nil { + t.Fatalf("InsertCandidateQuestionnaire() error = %v", err) + } + visible = append(visible, candidate.ID) + } + + hidden := fixture.candidate(t, "hidden@example.test") + verifyPrivacyCohortCandidate(t, fixture, hidden) + hiddenConsent := fixture.grant(t, hidden.ID, domain.ConsentPurposePublication, privacyC2Version, now) + fixture.publish(t, hidden.ID, hiddenConsent.ID(), 0, domain.CardFieldStack) + fixture.hide(t, hidden.ID, organization.ID(), now) + + revoked := fixture.candidate(t, "revoked@example.test") + verifyPrivacyCohortCandidate(t, fixture, revoked) + revokedConsent := fixture.grant(t, revoked.ID, domain.ConsentPurposePublication, privacyC2Version, now) + fixture.publish(t, revoked.ID, revokedConsent.ID(), 0, domain.CardFieldStack) + fixture.revokeC2(t, revoked.ID, now.Add(time.Minute)) + + reader := postgresadapter.NewPrivacyCohortStore(pool) + sources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources() error = %v", err) + } + if len(sources) != len(visible) { + t.Fatalf("visible sources = %d, want %d after excluding hidden and revoked candidates", len(sources), len(visible)) + } + sourcesB, err := reader.ListVisibleCandidateViewSources(ctx, organizationB.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(B) error = %v", err) + } + sourcesAAgain, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(A again) error = %v", err) + } + if len(sourcesB) != len(visible)+1 || len(sourcesAAgain) != len(visible) { + t.Fatalf("visible sources A/B/A = %d/%d/%d, want %d/6/%d with B still seeing the organization-hidden candidate", len(sources), len(sourcesB), len(sourcesAAgain), len(visible), len(visible)) + } + candidateID := sources[0].CandidateID() + if !privacyCohortHasSource(sourcesB, candidateID) || !privacyCohortHasSource(sourcesAAgain, candidateID) { + t.Fatal("the same candidate was not visible in repository reads A/B/A") + } + key, err := domain.NewCandidateViewPseudonymKey(bytes.Repeat([]byte("dedicated-anonymous-view-key"), 2)) + if err != nil { + t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err) + } + aliasA, err := key.ForOrganization(organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization(A) error = %v", err) + } + aliasB, err := key.ForOrganization(organizationB.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization(B) error = %v", err) + } + aliasAAgain, err := key.ForOrganization(organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization(A again) error = %v", err) + } + if aliasA != aliasAAgain || aliasA == aliasB { + t.Fatalf("repository-backed A/B/A aliases = %q/%q/%q, want stable A and distinct B", aliasA, aliasB, aliasAAgain) + } + service := anonymousprofile.NewService(reader, key, func() time.Time { return now.Add(2 * time.Minute) }) + views, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible() error = %v", err) + } + if len(views) != 5 { + t.Fatalf("ListVisible() returned %d views, want the five-member cohort", len(views)) + } + if !privacyCohortHasViewAlias(views, aliasA) { + t.Fatal("organization A projection did not contain its stable candidate alias") + } + viewsB, err := service.ListVisible(ctx, organizationB.ID()) + if err != nil { + t.Fatalf("ListVisible(B) error = %v", err) + } + viewsAAgain, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible(A again) error = %v", err) + } + if len(viewsB) != 5 || !privacyCohortHasViewAlias(viewsB, aliasB) || !privacyCohortHasViewAlias(viewsAAgain, aliasAAgain) { + t.Fatalf("service projection A/B/A = %d/%d/%d aliases present=%t/%t", len(views), len(viewsB), len(viewsAAgain), privacyCohortHasViewAlias(viewsB, aliasB), privacyCohortHasViewAlias(viewsAAgain, aliasAAgain)) + } + for _, view := range views { + if view.ExperienceBand == nil || *view.ExperienceBand != domain.CandidateExperienceBandThreeToSix { + t.Errorf("experience band = %v, want 3_6", view.ExperienceBand) + } + if len(view.Skills) != 1 || view.Skills[0] != domain.CandidateViewSkillGo { + t.Errorf("skills = %v, want only the recognized canonical value", view.Skills) + } + if len(view.WorkFormats) != 1 || view.WorkFormats[0] != domain.QuestionnaireWorkFormatRemote { + t.Errorf("work formats = %v, want explicitly selected remote", view.WorkFormats) + } + if len(view.Categories) != 0 || len(view.SelfAssessment) != 1 || view.SelfAssessment[0].DeclaredGrade == nil { + t.Errorf("confirmed categories and self-assessment were not kept separate: categories=%v self_assessment=%v", view.Categories, view.SelfAssessment) + } + if view.SalaryCompatibility != nil { + t.Errorf("salary compatibility = %v, want unknown without an approved computed result", view.SalaryCompatibility) + } + } + encoded, err := json.Marshal(views) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + for _, marker := range []string{ + "Private Name Marker", "private-contact-marker@example.test", "Private Employer Marker", + "Private Summary Marker", "Private Soft Skill Marker", "Private Location Marker", + "UniqueStackMarker", "180000", hidden.ID.String(), revoked.ID.String(), + } { + if strings.Contains(string(encoded), marker) { + t.Errorf("organization-facing cohort contains private marker %q", marker) + } + } + + fixture.hide(t, visible[0], organization.ID(), now.Add(3*time.Minute)) + fourSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(four) error = %v", err) + } + fourViews, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible(four) error = %v", err) + } + if len(fourSources) != 4 || len(fourViews) != 0 { + t.Fatalf("cohort of four sources/views = %d/%d, want 4/0 after suppression", len(fourSources), len(fourViews)) + } + for index := 1; index < len(visible)-1; index++ { + fixture.hide(t, visible[index], organization.ID(), now.Add(time.Duration(index+3)*time.Minute)) + } + oneSources, err := reader.ListVisibleCandidateViewSources(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources(one) error = %v", err) + } + oneViews, err := service.ListVisible(ctx, organization.ID()) + if err != nil { + t.Fatalf("ListVisible(one) error = %v", err) + } + if len(oneSources) != 1 || len(oneViews) != 0 { + t.Fatalf("cohort of one source/view = %d/%d, want 1/0 after suppression", len(oneSources), len(oneViews)) + } +} + +func privacyCohortHasSource(sources []domain.CandidateViewSource, candidateID uuid.UUID) bool { + for _, source := range sources { + if source.CandidateID() == candidateID { + return true + } + } + return false +} + +func privacyCohortHasViewAlias(views []domain.AnonymousCandidateViewDTO, alias string) bool { + for _, view := range views { + if view.Pseudonym == alias { + return true + } + } + return false +} + +func verifyPrivacyCohortCandidate(t *testing.T, fixture candidatePrivacyFixture, candidate domain.User) { + t.Helper() + if _, err := fixture.identity.store.Users().MarkEmailVerified(fixture.ctx, candidate.ID, candidate.RegistrationVersion, fixture.now); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } +} + +func privacyCohortConfirmedItems[V comparable](values ...V) []domain.ProfileClaimInput[V] { + items := make([]domain.ProfileClaimInput[V], 0, len(values)) + for _, value := range values { + items = append(items, domain.ProfileClaimInput[V]{Value: value, Status: domain.ProfileClaimConfirmed}) + } + return items +} diff --git a/backend/integration_test/product_notification_test.go b/backend/integration_test/product_notification_test.go new file mode 100644 index 0000000..4668fcd --- /dev/null +++ b/backend/integration_test/product_notification_test.go @@ -0,0 +1,625 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/consent" + identityusecase "lincodex/backend/internal/usecase/identity" + invitationusecase "lincodex/backend/internal/usecase/invitation" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/policy" +) + +const ( + productNoticeTimeout = 5 * time.Minute + // productNoticeOrganization names the sending organization. The notice + // must never carry it, so the tests look for it in the mail and the logs. + productNoticeOrganization = "Notice company" + // productNoticeBody is the start of the neutral body of an invitation + // notice; the full text stays in the mail templates. + productNoticeBody = "Работодатель отправил вам приглашение" + // productNoticeConcurrentWorkers drain one queue at once, each with its + // own sender, as separate processes do. + productNoticeConcurrentWorkers = 4 + productNoticeQueued = 6 + // productNoticeBacklog is the number of due rows that the other lane holds + // while the product claim is explained. + productNoticeBacklog = 5000 +) + +// productNoticeFixture drives the invitation send with the real notifier, the +// consumer that stores its notice, and the notification sender, against one +// isolated database and the local Resend fixture. +type productNoticeFixture struct { + ctx context.Context + pool *pgxpool.Pool + transactor *postgresadapter.Transactor + identity identityFixture + organizations organizationFixture + clock *testClock + key domain.CandidateViewPseudonymKey + handles map[string]uuid.UUID + organization domain.Organization + owner domain.User + service *invitationusecase.Service + renderer *mailtemplate.Renderer + account domain.MailProviderAccount + mail *resendfixture.Server + transport outbound.MailSender + logs *syncBuffer + // harness reads the deliveries and runs the service sender, which the + // notice tests share. + harness *senderHarness + publicURL string +} + +func newProductNoticeFixture(ctx context.Context, t *testing.T, env *testEnvironment) *productNoticeFixture { + t.Helper() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond).Add(time.Second)} + transactor := postgresadapter.NewTransactor(pool) + identities := identityFixture{ctx: ctx, pool: pool, store: postgresadapter.NewIdentityStore(pool), now: clock.Now()} + organizations := organizationFixture{ctx: ctx, pool: pool, identity: identities, transactor: transactor, now: clock.Now()} + owner := organizations.employer(t, "notice-owner@example.test") + confirmEmail(ctx, t, pool, owner, clock.Now().Add(-time.Minute)) + organization := organizations.create(t, owner, organizations.completeProfile(t, productNoticeOrganization), clock.Now()) + + keyring, err := identityusecase.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + key, err := keyring.CandidateViewPseudonymKey() + if err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + renderer, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + account, err := domain.NewMailProviderAccount("resend", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + mail := resendfixture.New() + t.Cleanup(mail.Close) + mail.SetClock(clock.Now) + transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, mail.URL(), clock.Now) + if err != nil { + t.Fatalf("NewLoopbackSender() error = %v", err) + } + notifier, err := notification.NewInvitationNotifier(notification.NewMailRequester(notification.NewTemplateRenderer(renderer), clock.Now)) + if err != nil { + t.Fatalf("NewInvitationNotifier() error = %v", err) + } + logs := &syncBuffer{} + fixture := &productNoticeFixture{ + ctx: ctx, pool: pool, transactor: transactor, identity: identities, organizations: organizations, clock: clock, + key: key, handles: map[string]uuid.UUID{}, organization: organization, owner: owner, renderer: renderer, + account: account, mail: mail, transport: transport, logs: logs, publicURL: env.Config.AppPublicURL, + } + quota := companyquota.NewService(clock.Now) + fixture.service, err = invitationusecase.NewService(invitationusecase.Dependencies{ + Transactor: transactor, Keyring: keyring, PseudonymKey: key, + Candidates: func(_ context.Context, _ outbound.UnitOfWork, _, organizationID uuid.UUID, handle string) (uuid.UUID, error) { + candidateID, ok := fixture.handles[handle] + if !ok || organizationID != organization.ID() { + return uuid.Nil, candidateview.ErrCandidateCardNotFound + } + return candidateID, nil + }, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, invitationID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveInvitation(ctx, unit, organization, invitationID) + }, + Notifier: notifier, Consents: consent.NewService(transactor, clock.Now), Clock: clock.Now, + }) + if err != nil { + t.Fatalf("invitation.NewService() error = %v", err) + } + // The organization is E1, so one owner may send more than the E0 quota + // allows; the rights under test do not depend on the quota. + if _, err := pool.Exec(ctx, ` + UPDATE organizations + SET verification_level = 'e1', verification_basis = 'corporate_domain', verification_changed_at = $2 + WHERE id = $1`, organization.ID(), clock.Now()); err != nil { + t.Fatalf("raise the organization to E1: %v", err) + } + fixture.harness = &senderHarness{ + pool: pool, + transactor: transactor, + identity: postgresadapter.NewIdentityStore(pool), + deliveries: postgresadapter.NewDeliveryStore(pool).Deliveries(), + mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, clock.Now), + fixture: mail, + transport: transport, + account: account, + clock: clock, + logs: logs, + publicURL: env.Config.AppPublicURL, + } + return fixture +} + +// candidate makes a verified candidate with a current publication (C2) and +// the card handle of the organization, so that the send accepts it. +func (fixture *productNoticeFixture) candidate(t *testing.T, email string) domain.User { + t.Helper() + user := fixture.identity.createUser(t, email, domain.ScenarioCandidate, fixture.clock.Now().Add(-time.Hour)) + confirmEmail(fixture.ctx, t, fixture.pool, user, fixture.clock.Now().Add(-time.Minute)) + handle, err := fixture.key.ForOrganization(fixture.organization.ID(), user.ID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + fixture.handles[handle] = user.ID + fixture.publish(t, user.ID) + return user +} + +// publish stores a C2 grant and a published card that names it, the state an +// invitation is sent under. +func (fixture *productNoticeFixture) publish(t *testing.T, userID uuid.UUID) { + t.Helper() + ledger := postgresadapter.NewConsentStore(fixture.pool) + text, err := ledger.ConsentTexts().Get(fixture.ctx, domain.ConsentPurposePublication, privacyC2Version) + if err != nil { + t.Fatalf("ConsentTexts().Get(c2) error = %v", err) + } + grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{ + SubjectID: userID, Purpose: domain.ConsentPurposePublication, TextVersion: text.Version(), TextHash: text.Hash(), + Source: domain.ConsentSourceConsentSettings, GrantedAt: fixture.clock.Now().Add(-time.Hour), + }) + if err != nil { + t.Fatalf("NewConsentGrant() error = %v", err) + } + record, created, err := ledger.ConsentLedger().Grant(fixture.ctx, grant) + if err != nil || !created { + t.Fatalf("Grant(c2) = %t, %v; want a new record", created, err) + } + request, err := domain.NewPublicationRequest(domain.PublicationPublished, []domain.CardField{domain.CardFieldStack, domain.CardFieldCategories}) + if err != nil { + t.Fatalf("NewPublicationRequest() error = %v", err) + } + empty, err := domain.NewPublication(userID) + if err != nil { + t.Fatalf("NewPublication() error = %v", err) + } + change, err := empty.Apply(request, 0, record.ID(), fixture.clock.Now()) + if err != nil || !change.Changed { + t.Fatalf("Apply(publish) = %+v, %v; want a change", change, err) + } + if _, err := sqlc.New(fixture.pool).InsertCandidatePublication(fixture.ctx, sqlc.InsertCandidatePublicationParams{ + UserID: uuidParam(userID), State: string(change.Publication.StoredState()), Fields: change.Publication.StoredFields(), + ConsentRecordID: uuidParam(record.ID()), PublishedAt: timeParam(change.Publication.PublishedAt()), + ClosedAt: pgtype.Timestamptz{}, At: timeParam(fixture.clock.Now()), + }); err != nil { + t.Fatalf("InsertCandidatePublication() error = %v", err) + } +} + +func (fixture *productNoticeFixture) handleOf(t *testing.T, candidateID uuid.UUID) string { + t.Helper() + handle, err := fixture.key.ForOrganization(fixture.organization.ID(), candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return handle +} + +// invite drafts an invitation for the candidate and sends it. The send records +// the notice request in the same transaction, as it does in production. +func (fixture *productNoticeFixture) invite(t *testing.T, candidateID uuid.UUID) domain.OrganizationInvitationView { + t.Helper() + key := "create-" + uuid.NewString() + draft, err := fixture.service.Create(fixture.ctx, invitationusecase.CreateCommand{ + ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), IdempotencyKey: key, + CanonicalBody: []byte(fmt.Sprintf(`{"key":%q}`, key)), CandidateHandle: fixture.handleOf(t, candidateID), + Terms: invitationStorageTerms(), + }) + if err != nil { + t.Fatalf("Create() error = %v", err) + } + sent, err := fixture.service.Send(fixture.ctx, invitationusecase.SendCommand{ + ActorID: fixture.owner.ID, OrganizationID: fixture.organization.ID(), InvitationID: draft.ID, + IdempotencyKey: "send-" + uuid.NewString(), ExpectedVersion: draft.Version, + }) + if err != nil { + t.Fatalf("Send() error = %v", err) + } + return sent +} + +// deliverNotice runs the delivery consumer on the notice request that the send +// recorded, as the event consumer does, and returns the delivery ID. +func (fixture *productNoticeFixture) deliverNotice(t *testing.T, candidateID uuid.UUID) uuid.UUID { + t.Helper() + var event outbound.ConsumedEvent + var payload string + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT event_id, event_type, schema_version, aggregate_type, aggregate_id, aggregate_version, payload::text, occurred_at + FROM outbox_events + WHERE event_type = 'notification.mail_requested' + AND aggregate_id IN (SELECT id FROM mail_requests WHERE recipient_user_id = $1)`, candidateID). + Scan(&event.EventID, &event.EventType, &event.SchemaVersion, &event.AggregateType, &event.AggregateID, + &event.AggregateVersion, &payload, &event.OccurredAt); err != nil { + t.Fatalf("read the notice request: %v", err) + } + event.Payload = []byte(payload) + event.OccurredAt = event.OccurredAt.UTC().Truncate(time.Microsecond) + handler := notification.NewDeliveryHandler(notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, slog.New(slog.DiscardHandler)) + if err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return handler.Handle(ctx, unit, event) + }); err != nil { + t.Fatalf("DeliveryHandler.Handle() error = %v", err) + } + var deliveryID uuid.UUID + if err := fixture.pool.QueryRow(fixture.ctx, + `SELECT id FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification'`, candidateID).Scan(&deliveryID); err != nil { + t.Fatalf("read the notice delivery: %v", err) + } + return deliveryID +} + +// sender builds the notification lane with the reserve of its quota gate. The +// lane shares the transport, account, and timing of the service lane. +func (fixture *productNoticeFixture) sender(t *testing.T, daily, monthly, reserveDaily, reserveMonthly int64) *notification.DeliverySender { + t.Helper() + limits, err := domain.NewMailQuotaLimits(daily, monthly) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + logger := slog.New(slog.NewJSONHandler(fixture.logs, nil)) + gate, err := notification.NewQuotaGate(fixture.account, limits, resend.IdempotencyWindow, fixture.clock.Now, logger).WithReserve(reserveDaily, reserveMonthly) + if err != nil { + t.Fatalf("WithReserve() error = %v", err) + } + sender, err := notification.NewNotificationSender(fixture.transactor, fixture.transport, gate, notification.DeliverySenderSettings{ + Account: fixture.account, + Lease: mailSenderLease, + StoreTimeout: 30 * time.Second, + SettleBudget: mailSenderSettleBudget, + ShutdownSettleBudget: time.Second, + MaxFailures: 3, + Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, + }, fixture.clock.Now, logger, []notification.SubjectRights{notification.NewInvitationNoticeRights()}) + if err != nil { + t.Fatalf("NewNotificationSender() error = %v", err) + } + return sender +} + +// deliveryRow reads the stored status, cancel reason, and bodies of a delivery, +// without decoding it, so a test sees what is in the table. +func (fixture *productNoticeFixture) deliveryRow(t *testing.T, id uuid.UUID) (status, reason, text, html string, redacted bool) { + t.Helper() + var cancelReason *string + var redactedAt *time.Time + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT status, cancel_reason, text_body, html_body, body_redacted_at FROM deliveries WHERE id = $1`, id). + Scan(&status, &cancelReason, &text, &html, &redactedAt); err != nil { + t.Fatalf("read delivery %s: %v", id, err) + } + if cancelReason != nil { + reason = *cancelReason + } + return status, reason, text, html, redactedAt != nil +} + +// requestsFor returns the provider requests addressed to the address. +func (fixture *productNoticeFixture) requestsFor(address string) []resendfixture.Request { + var matching []resendfixture.Request + for _, request := range fixture.mail.Requests() { + for _, to := range request.To { + if to == address { + matching = append(matching, request) + break + } + } + } + return matching +} + +func TestProductNoticeIsSentOnceByItsOwnWorker(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + candidate := fixture.candidate(t, "notice-sent@example.test") + fixture.invite(t, candidate.ID) + deliveryID := fixture.deliverNotice(t, candidate.ID) + calls := len(fixture.mail.Requests()) + + serviceSender := fixture.harness.newSender(t, fixture.transactor, 100, 3000) + if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls { + t.Fatalf("service pass = %+v with %d provider calls; want idle and none: the service worker takes only service mail", result, len(fixture.mail.Requests())-calls) + } + if got := fixture.harness.delivery(ctx, t, deliveryID); got.Kind() != domain.MailKindNotification || got.Status() != domain.DeliveryStatusPending || got.Subject().Kind() != domain.MailSubjectInvitation { + t.Fatalf("stored notice = %s %s with subject %v; want a pending notification that names its invitation", got.Kind(), got.Status(), got.Subject()) + } + + productSender := fixture.sender(t, 100, 3000, 0, 0) + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("product pass = %+v, want accepted", result) + } + sent := fixture.requestsFor(candidate.Email.Address()) + if len(sent) != 1 { + t.Fatalf("provider requests to the candidate = %d, want exactly one", len(sent)) + } + if !strings.Contains(sent[0].Text, productNoticeBody) || strings.Contains(sent[0].Text, productNoticeOrganization) || + strings.Contains(sent[0].Text, candidate.ID.String()) || !strings.Contains(sent[0].Text, "/candidate/invitations") { + t.Fatalf("notice body = %q; want the neutral text with the inbox link and no organization or identifier", sent[0].Text) + } + if got := fixture.harness.delivery(ctx, t, deliveryID); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { + t.Fatalf("delivery is %s after %d attempts, want accepted after one", got.Status(), got.AttemptCount()) + } + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle || len(fixture.mail.Requests()) != calls+1 { + t.Fatalf("pass after the send = %+v; want idle with no second request", result) + } + fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID)) +} + +func TestProductNoticeRightsAreCheckedBeforeEverySend(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + productSender := fixture.sender(t, 100, 3000, 0, 0) + + t.Run("a candidate who hides the organization after the send gets no mail and the body is cleared", func(t *testing.T) { + candidate := fixture.candidate(t, "notice-hidden@example.test") + fixture.invite(t, candidate.ID) + deliveryID := fixture.deliverNotice(t, candidate.ID) + fixture.hide(t, candidate.ID) + calls := len(fixture.mail.Requests()) + + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked { + t.Fatalf("pass = %+v, want cancelled as rights_revoked", result) + } + if len(fixture.mail.Requests()) != calls { + t.Fatal("the transport was called for a notice whose organization is hidden") + } + status, reason, text, html, redacted := fixture.deliveryRow(t, deliveryID) + if status != "cancelled" || reason != "rights_revoked" || text != "" || html != "" || !redacted { + t.Fatalf("stored notice is %s (%s) with bodies %q/%q redacted %v; want cancelled as rights_revoked with no body", status, reason, text, html, redacted) + } + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after the cancellation = %+v, want idle", result) + } + fixture.harness.assertLogsHoldNoSecrets(t, candidate.Email.Address(), candidate.ID.String(), fixture.handleOf(t, candidate.ID)) + }) + + t.Run("an address that is no longer verified gets no mail and is cancelled as recipient_ineligible", func(t *testing.T) { + candidate := fixture.candidate(t, "notice-unverified@example.test") + fixture.invite(t, candidate.ID) + deliveryID := fixture.deliverNotice(t, candidate.ID) + if _, err := fixture.pool.Exec(ctx, `UPDATE users SET email_verified_at = NULL, version = version + 1 WHERE id = $1`, candidate.ID); err != nil { + t.Fatalf("unverify the address: %v", err) + } + calls := len(fixture.mail.Requests()) + + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRecipientIneligible { + t.Fatalf("pass = %+v, want cancelled as recipient_ineligible", result) + } + if len(fixture.mail.Requests()) != calls { + t.Fatal("the transport was called for an unverified address") + } + if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "recipient_ineligible" { + t.Fatalf("stored notice is %s (%s), want cancelled as recipient_ineligible", status, reason) + } + }) + + t.Run("a notice that names no subject has no right to check and is cancelled as source_closed", func(t *testing.T) { + candidate := fixture.candidate(t, "notice-no-subject@example.test") + content, err := domain.NewMailContent(domain.MailKindNotification, "notification.v1", "Синтетическое уведомление", "PRIVATE-BODY notification\n", "") + if err != nil { + t.Fatalf("NewMailContent() error = %v", err) + } + delivery, err := domain.NewDelivery(domain.NewDeliveryInput{ + ID: uuid.Must(uuid.NewV7()), RecipientUserID: candidate.ID, Recipient: candidate.Email, + Content: content, ProviderAccount: fixture.account, CreatedAt: fixture.clock.Now(), + }) + if err != nil { + t.Fatalf("NewDelivery() error = %v", err) + } + if created, err := fixture.harness.deliveries.Create(ctx, delivery); err != nil || !created { + t.Fatalf("Create() = %t, %v; want the notice stored", created, err) + } + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelSourceClosed { + t.Fatalf("pass = %+v, want cancelled as source_closed", result) + } + if status, _, text, _, _ := fixture.deliveryRow(t, delivery.ID()); status != "cancelled" || text != "" { + t.Fatalf("stored notice is %s with text %q, want cancelled with no body", status, text) + } + }) + + // The clock moves past the response deadline, so this subtest comes last. + t.Run("an invitation that passed its response deadline gets no mail and is cancelled as rights_revoked", func(t *testing.T) { + candidate := fixture.candidate(t, "notice-expired@example.test") + fixture.invite(t, candidate.ID) + deliveryID := fixture.deliverNotice(t, candidate.ID) + fixture.clock.Advance(400 * 24 * time.Hour) + calls := len(fixture.mail.Requests()) + + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassCancelled || result.CancelReason != domain.DeliveryCancelRightsRevoked { + t.Fatalf("pass = %+v, want cancelled as rights_revoked", result) + } + if len(fixture.mail.Requests()) != calls { + t.Fatal("the transport was called for an expired invitation") + } + if status, reason, _, _, _ := fixture.deliveryRow(t, deliveryID); status != "cancelled" || reason != "rights_revoked" { + t.Fatalf("stored notice is %s (%s), want cancelled as rights_revoked", status, reason) + } + }) +} + +// hide records that the candidate hid the organization, as the privacy +// settings do. +func (fixture *productNoticeFixture) hide(t *testing.T, candidateID uuid.UUID) { + t.Helper() + if _, err := fixture.pool.Exec(fixture.ctx, ` + INSERT INTO candidate_hidden_organizations (user_id, organization_id, hidden_at) VALUES ($1, $2, $3)`, + candidateID, fixture.organization.ID(), fixture.clock.Now()); err != nil { + t.Fatalf("hide the organization: %v", err) + } +} + +func TestProductNoticeReserveLeavesServiceQuotaToServiceMail(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + // The day holds ten recipients. The notification lane keeps eight for other + // mail, so it admits two notices, and the service lane still has the full + // day. + productSender := fixture.sender(t, 10, 3000, 8, 0) + var waiting uuid.UUID + for index := range 3 { + candidate := fixture.candidate(t, fmt.Sprintf("notice-reserve-%d@example.test", index)) + fixture.invite(t, candidate.ID) + id := fixture.deliverNotice(t, candidate.ID) + if index == 2 { + waiting = id + } + } + for range 2 { + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("notice pass = %+v, want accepted within the lane's share", result) + } + } + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassWaitingQuota { + t.Fatalf("third notice pass = %+v, want waiting_quota at the reserve", result) + } + midnight := domain.MailQuotaWindowsAt(fixture.clock.Now()).ResetAt(domain.MailQuotaPeriodDay) + if got := fixture.harness.delivery(ctx, t, waiting); got.Status() != domain.DeliveryStatusWaitingQuota || !got.NextAttemptAt().Equal(midnight) { + t.Fatalf("waiting notice is %s due %s, want waiting_quota until %s", got.Status(), got.NextAttemptAt(), midnight) + } + if result := fixture.harness.pass(ctx, t, productSender); result.Outcome != inbound.MailPassIdle { + t.Fatalf("notice pass while the reserve holds = %+v, want idle without a spin", result) + } + + service := fixture.harness.createUser(ctx, t, false) + _, _, serviceID := fixture.harness.enqueueVerification(ctx, t, service, mailSenderTokenLifetime) + serviceSender := fixture.harness.newSender(t, fixture.transactor, 10, 3000) + if result := fixture.harness.pass(ctx, t, serviceSender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("service pass = %+v, want the verification mail accepted under the reserve", result) + } + if got := fixture.harness.delivery(ctx, t, serviceID); got.Status() != domain.DeliveryStatusAccepted { + t.Fatalf("service mail is %s, want accepted", got.Status()) + } + fixture.harness.assertQuotaUsage(ctx, t, 3) + if got := len(fixture.mail.Requests()); got != 3 { + t.Fatalf("provider calls = %d, want two notices and the service mail", got) + } +} + +func TestProductNoticeQueueIsDrainedOnceByConcurrentWorkers(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + ids := make([]uuid.UUID, 0, productNoticeQueued) + for index := range productNoticeQueued { + candidate := fixture.candidate(t, fmt.Sprintf("notice-queue-%d@example.test", index)) + fixture.invite(t, candidate.ID) + ids = append(ids, fixture.deliverNotice(t, candidate.ID)) + } + + var group sync.WaitGroup + errs := make([]error, productNoticeConcurrentWorkers) + for worker := range productNoticeConcurrentWorkers { + sender := fixture.sender(t, 1000, 3000, 0, 0) + group.Go(func() { + for { + result, err := sender.ProcessNext(ctx, ctx) + if err != nil { + errs[worker] = err + return + } + if result.Outcome == inbound.MailPassIdle { + return + } + } + }) + } + group.Wait() + if err := errors.Join(errs...); err != nil { + t.Fatalf("a worker failed: %v", err) + } + if got := len(fixture.mail.Requests()); got != productNoticeQueued { + t.Fatalf("provider calls = %d, want one per notice (%d)", got, productNoticeQueued) + } + for _, id := range ids { + if got := fixture.harness.delivery(ctx, t, id); got.Status() != domain.DeliveryStatusAccepted || got.AttemptCount() != 1 { + t.Fatalf("notice %s is %s after %d attempts, want accepted after one", id, got.Status(), got.AttemptCount()) + } + } +} + +func TestProductNoticeClaimReadsItsOwnDueIndex(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + // Service mail backlog: the product claim must not scan it. + if _, err := fixture.pool.Exec(ctx, `INSERT INTO deliveries ( + id, recipient_user_id, recipient_email, kind, template_version, subject, text_body, html_body, content_sha256, + provider, provider_account, idempotency_key, status, attempt_count, next_attempt_at, version, created_at, updated_at + ) + SELECT gen_random_uuid(), $1, 'backlog@example.com', 'verification', 'verification.v1', 's', 't', '', decode(repeat('00', 32), 'hex'), + 'resend', $2, 'delivery/service-backlog-' || n, 'pending', 0, $3::timestamptz - interval '1 day', 1, $3, $3 + FROM generate_series(1, $4::int) AS n`, fixture.identity.createUser(t, "backlog-owner@example.test", domain.ScenarioCandidate, fixture.clock.Now()).ID, + fixture.account.Account(), fixture.clock.Now(), productNoticeBacklog); err != nil { + t.Fatalf("insert the service backlog: %v", err) + } + if _, err := fixture.pool.Exec(ctx, "ANALYZE deliveries"); err != nil { + t.Fatalf("ANALYZE deliveries: %v", err) + } + rows, err := fixture.pool.Query(ctx, `EXPLAIN (COSTS OFF) SELECT due.id FROM deliveries AS due + WHERE due.kind = 'notification' + AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL + AND due.next_attempt_at <= $1::timestamptz AND due.provider = 'resend' AND due.provider_account = $2 + AND (due.claim_owner IS NULL OR due.claimed_until <= clock_timestamp()) + ORDER BY due.next_attempt_at, due.id LIMIT 1 FOR UPDATE SKIP LOCKED`, + fixture.clock.Now(), fixture.account.Account()) + if err != nil { + t.Fatalf("explain the product claim: %v", err) + } + defer rows.Close() + var plan strings.Builder + for rows.Next() { + var line string + if err := rows.Scan(&line); err != nil { + t.Fatalf("scan the plan: %v", err) + } + plan.WriteString(line + "\n") + } + if !strings.Contains(plan.String(), "deliveries_product_due_idx") || strings.Contains(plan.String(), "Seq Scan") { + t.Fatalf("the product claim does not use deliveries_product_due_idx over the service backlog:\n%s", plan.String()) + } +} diff --git a/backend/integration_test/questionnaire_http_test.go b/backend/integration_test/questionnaire_http_test.go new file mode 100644 index 0000000..f46e9ac --- /dev/null +++ b/backend/integration_test/questionnaire_http_test.go @@ -0,0 +1,696 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" + profileusecase "lincodex/backend/internal/usecase/profile" + questionnaireusecase "lincodex/backend/internal/usecase/questionnaire" +) + +const candidateQuestionnaireHTTPTimeout = 6 * time.Minute + +func TestCandidateQuestionnaireOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), candidateQuestionnaireHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv) + initialCatalog := questionnaireCatalogHTTP(t, harness) + assertCatalogAvailability(t, initialCatalog, "backend", "in_development", nil, nil) + bankFixture := seedQuestionnaireCatalogBank(ctx, t, harness.pool) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + now := harness.clock.Now() + candidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-owner@example.test", passwordHash, true) + otherCandidate := createSessionHTTPUser(ctx, t, harness, "questionnaire-other@example.test", passwordHash, true) + employer := createQuestionnaireHTTPEmployer(ctx, t, harness, "questionnaire-employer@example.test", passwordHash, now) + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("set candidate questionnaire onboarding step: %v", err) + } + candidateLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.201:1234") + otherLogin := loginCandidateQuestionnaireHTTP(t, harness, otherCandidate.Email.Address(), "192.0.2.202:1234") + employerLogin := loginCandidateQuestionnaireHTTP(t, harness, employer.Email.Address(), "192.0.2.203:1234") + + publicCatalogResponse := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.204:1234") + if publicCatalogResponse.Code != http.StatusOK { + t.Fatalf("public catalog without a session = %d %s, want 200", publicCatalogResponse.Code, publicCatalogResponse.Body.String()) + } + currentCatalog := decodeSpecializationCatalog(t, publicCatalogResponse.Body.Bytes()) + assertCatalogAvailability(t, currentCatalog, "backend", "available", []string{"junior"}, []string{"go"}) + + guestRead := harness.request(t, http.MethodGet, "/api/v1/me/questionnaire", "", sessionHTTPTestOrigin, "", "", "192.0.2.205:1234") + requireSessionProblem(t, guestRead, http.StatusUnauthorized, "unauthenticated") + + initial := questionnaireHTTPRequest(t, harness, http.MethodGet, "", candidateLogin.cookie, "", "192.0.2.206:1234") + if initial.Code != http.StatusOK || initial.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("empty questionnaire = %d Cache-Control=%q: %s", initial.Code, initial.Header().Get("Cache-Control"), initial.Body.String()) + } + var empty questionnaireHTTPResponse + if err := json.Unmarshal(initial.Body.Bytes(), &empty); err != nil { + t.Fatalf("decode empty questionnaire: %v", err) + } + if empty.Version != 0 || len(empty.Specializations) != 0 || string(empty.WorkContext) != "null" || string(empty.UpdatedAt) != "null" { + t.Fatalf("empty questionnaire = %+v, want version zero with null context and time", empty) + } + + firstSave := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6), + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.207:1234") + if firstSave.Code != http.StatusOK || firstSave.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("save questionnaire = %d Cache-Control=%q: %s", firstSave.Code, firstSave.Header().Get("Cache-Control"), firstSave.Body.String()) + } + var saved questionnaireHTTPResponse + if err := json.Unmarshal(firstSave.Body.Bytes(), &saved); err != nil { + t.Fatalf("decode saved questionnaire: %v", err) + } + if saved.Version != 1 || len(saved.Specializations) != 1 || saved.Specializations[0].SelfAssessedGrade != "junior" || + len(saved.Specializations[0].TaskLanguages) != 1 || saved.Specializations[0].TaskLanguages[0] != "go" || + saved.Specializations[0].Experience == nil || saved.Specializations[0].Experience.CommercialMonths != 18 || + saved.Specializations[0].Experience.AcademicMonths != 6 || len(saved.Specializations[0].Stack) != 1 || saved.Specializations[0].Stack[0] != "PostgreSQL" { + t.Fatalf("saved questionnaire = %+v, want backend/junior/go version 1", saved) + } + assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6) + assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "candidate_assessment") + assertQuestionnaireExperienceConstraint(t, ctx, harness, otherCandidate.ID) + + staleWrite := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"gRPC"}, 18, 6), + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.208:1234") + requireSessionProblem(t, staleWrite, http.StatusPreconditionFailed, "version_conflict") + assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6) + + noOp := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 0, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6), + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.209:1234") + if noOp.Code != http.StatusOK { + t.Fatalf("stale identical questionnaire retry = %d %s, want 200", noOp.Code, noOp.Body.String()) + } + var noOpResponse questionnaireHTTPResponse + if err := json.Unmarshal(noOp.Body.Bytes(), &noOpResponse); err != nil || noOpResponse.Version != 1 { + t.Fatalf("stale identical retry response = %+v, decode error %v; want version 1", noOpResponse, err) + } + + badLanguage := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 1, "backend", "junior", []string{"python"}, []string{"PostgreSQL"}, 18, 6), + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.210:1234") + if badLanguage.Code != http.StatusBadRequest || !strings.Contains(badLanguage.Body.String(), "/specializations/0/task_languages/0") { + t.Fatalf("unoffered task language = %d %s, want field validation", badLanguage.Code, badLanguage.Body.String()) + } + assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6) + + forbiddenFieldBody := questionnaireUpdateWithUnknownField(t, + questionnaireUpdateBody(t, 1, "backend", "junior", []string{"go"}, []string{"PostgreSQL"}, 18, 6), + "confirmed_grade", "senior") + forbiddenField := questionnaireHTTPRequest(t, harness, http.MethodPut, forbiddenFieldBody, + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.211:1234") + if forbiddenField.Code != http.StatusBadRequest { + t.Fatalf("questionnaire update with confirmed_grade = %d %s, want 400", forbiddenField.Code, forbiddenField.Body.String()) + } + assertQuestionnaireRows(t, ctx, harness, candidate.ID, 1, "backend", "junior", "go", "PostgreSQL", 18, 6) + + otherRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", otherLogin.cookie, "", "192.0.2.212:1234") + var other questionnaireHTTPResponse + if otherRead.Code != http.StatusOK || json.Unmarshal(otherRead.Body.Bytes(), &other) != nil || other.Version != 0 || len(other.Specializations) != 0 { + t.Fatalf("other candidate questionnaire = %d %s, want private version-0 questionnaire", otherRead.Code, otherRead.Body.String()) + } + otherDevelopmentSave := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 0, "ds_ml", "junior", nil, []string{"Python"}, 0, 0), + otherLogin.cookie, otherLogin.csrf, "192.0.2.213:1234") + if otherDevelopmentSave.Code != http.StatusOK { + t.Fatalf("save a specialization with no available bank and no task language = %d %s, want 200", otherDevelopmentSave.Code, otherDevelopmentSave.Body.String()) + } + + employerRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", employerLogin.cookie, "", "192.0.2.214:1234") + requireSessionProblem(t, employerRead, http.StatusForbidden, "forbidden") + + // A self-assessed Senior grade remains a private claim. It cannot create a + // confirmed category or a profile claim by itself. + seniorSave := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6), + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.215:1234") + if seniorSave.Code != http.StatusOK { + t.Fatalf("save Senior self-assessment = %d %s, want 200", seniorSave.Code, seniorSave.Body.String()) + } + var senior questionnaireHTTPResponse + if err := json.Unmarshal(seniorSave.Body.Bytes(), &senior); err != nil || senior.Version != 2 || senior.Specializations[0].SelfAssessedGrade != "senior" { + t.Fatalf("Senior questionnaire = %+v, decode error %v", senior, err) + } + profileRead := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", sessionHTTPTestOrigin, + candidateLogin.cookie, "", "192.0.2.216:1234") + var profile struct { + Version int64 `json:"version"` + ConfirmedCategories []json.RawMessage `json:"confirmed_categories"` + } + if profileRead.Code != http.StatusOK || json.Unmarshal(profileRead.Body.Bytes(), &profile) != nil || + profile.Version != 0 || len(profile.ConfirmedCategories) != 0 { + t.Fatalf("profile after a Senior self-assessment = %d %s, want no confirmed category", profileRead.Code, profileRead.Body.String()) + } + + // A later onboarding step never moves backwards on an identical retry. + if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'completed' WHERE id = $1", candidate.ID); err != nil { + t.Fatalf("move candidate to completed onboarding: %v", err) + } + if response := questionnaireHTTPRequest(t, harness, http.MethodPut, + questionnaireUpdateBody(t, 1, "backend", "senior", []string{"go"}, []string{"PostgreSQL"}, 18, 6), + candidateLogin.cookie, candidateLogin.csrf, "192.0.2.217:1234"); response.Code != http.StatusOK { + t.Fatalf("questionnaire retry after onboarding completion = %d %s", response.Code, response.Body.String()) + } + assertQuestionnaireOnboarding(t, ctx, harness, candidate.ID, "completed") + + // Two different changes from the same version race; exactly one wins and + // the stale writer leaves the winner's whole body intact. + firstConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"gRPC"}, 18, 6) + secondConcurrent := questionnaireUpdateBody(t, 2, "backend", "senior", []string{"go"}, []string{"Redis"}, 18, 6) + concurrentResponses := make([]*httptest.ResponseRecorder, 2) + start := make(chan struct{}) + var wait sync.WaitGroup + for index, body := range []string{firstConcurrent, secondConcurrent} { + wait.Add(1) + go func(index int, body string) { + defer wait.Done() + <-start + concurrentResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, body, + candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 218+index)) + }(index, body) + } + close(start) + wait.Wait() + accepted, conflicted := 0, 0 + for _, response := range concurrentResponses { + switch response.Code { + case http.StatusOK: + accepted++ + case http.StatusPreconditionFailed: + conflicted++ + default: + t.Fatalf("concurrent questionnaire save = %d %s, want 200 or 412", response.Code, response.Body.String()) + } + } + if accepted != 1 || conflicted != 1 { + t.Fatalf("concurrent questionnaire results = %d accepted, %d conflicted; want one each", accepted, conflicted) + } + var storedVersion int64 + var storedStack string + if err := harness.pool.QueryRow(ctx, ` + SELECT questionnaire.version, specialization.stack[1] + FROM candidate_questionnaires AS questionnaire + JOIN candidate_questionnaire_specializations AS specialization USING (user_id) + WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil { + t.Fatalf("read concurrent questionnaire winner: %v", err) + } + if storedVersion != 3 || (storedStack != "gRPC" && storedStack != "Redis") { + t.Fatalf("concurrent stored questionnaire = version %d stack %q, want version 3 and one complete winner", storedVersion, storedStack) + } + + // Simultaneous identical saves return the one committed winner to both + // callers without creating a second version or replacing its answer rows. + identicalBody := questionnaireUpdateBody(t, 3, "backend", "senior", []string{"go"}, []string{"Fargate"}, 18, 6) + identicalResponses := make([]*httptest.ResponseRecorder, 2) + start = make(chan struct{}) + for index := range identicalResponses { + wait.Add(1) + go func(index int) { + defer wait.Done() + <-start + identicalResponses[index] = questionnaireHTTPRequest(t, harness, http.MethodPut, identicalBody, + candidateLogin.cookie, candidateLogin.csrf, fmt.Sprintf("192.0.2.%d:1234", 223+index)) + }(index) + } + close(start) + wait.Wait() + for _, response := range identicalResponses { + if response.Code != http.StatusOK { + t.Fatalf("concurrent identical questionnaire save = %d %s, want 200", response.Code, response.Body.String()) + } + var result questionnaireHTTPResponse + if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil || result.Version != 4 || + len(result.Specializations) != 1 || result.Specializations[0].Stack[0] != "Fargate" { + t.Fatalf("concurrent identical save response = %+v, decode error %v; want same version-4 winner", result, err) + } + } + if err := harness.pool.QueryRow(ctx, ` + SELECT questionnaire.version, specialization.stack[1] + FROM candidate_questionnaires AS questionnaire + JOIN candidate_questionnaire_specializations AS specialization USING (user_id) + WHERE questionnaire.user_id = $1`, candidate.ID).Scan(&storedVersion, &storedStack); err != nil { + t.Fatalf("read identical questionnaire winner: %v", err) + } + if storedVersion != 4 || storedStack != "Fargate" { + t.Fatalf("identical concurrent stored questionnaire = version %d stack %q, want version 4 and Fargate", storedVersion, storedStack) + } + + secondLogin := loginCandidateQuestionnaireHTTP(t, harness, candidate.Email.Address(), "192.0.2.220:1234") + harness.pool.Close() + harness = newCandidateQuestionnaireHTTPHarness(ctx, t, &isolatedEnv) + bankFixture.bank = assessment.NewBank(postgresadapter.NewTransactor(harness.pool)) + bankFixture.publisher = policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + restartedRead := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.221:1234") + var restarted questionnaireHTTPResponse + if restartedRead.Code != http.StatusOK || json.Unmarshal(restartedRead.Body.Bytes(), &restarted) != nil || + restarted.Version != 4 || len(restarted.Specializations) != 1 || restarted.Specializations[0].SelfAssessedGrade != "senior" || + restarted.Specializations[0].Stack[0] != storedStack { + t.Fatalf("questionnaire after re-login and handler restart = %d %s, want version 4 and persisted winner", restartedRead.Code, restartedRead.Body.String()) + } + assertQuestionnaireRows(t, ctx, harness, candidate.ID, 4, "backend", "senior", "go", storedStack, 18, 6) + + // A new policy version makes the old opening ineligible for the public + // catalog. Reopening under that policy restores availability only while the + // pinned published-family manifest still meets its recorded threshold. + policyVersion, err := bankFixture.publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, Policy: integrationPolicy(11), + }) + if err != nil { + t.Fatalf("Publish(replacement catalog policy) error = %v", err) + } + assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil) + if _, err := bankFixture.bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, + CatalogMetadata: &bankFixture.metadata, + }); err != nil { + t.Fatalf("OpenCategory(replacement catalog policy) error = %v", err) + } + assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "available", []string{"junior"}, []string{"go"}) + if _, err := bankFixture.bank.RetireFamily(ctx, bankFixture.firstFamilyKey, 1, fixturePublisher); err != nil { + t.Fatalf("RetireFamily(under-covered catalog) error = %v", err) + } + assertCatalogAvailability(t, questionnaireCatalogHTTP(t, harness), "backend", "in_development", nil, nil) + questionnaireAfterBankChange := questionnaireHTTPRequest(t, harness, http.MethodGet, "", secondLogin.cookie, "", "192.0.2.222:1234") + var preserved questionnaireHTTPResponse + if questionnaireAfterBankChange.Code != http.StatusOK || json.Unmarshal(questionnaireAfterBankChange.Body.Bytes(), &preserved) != nil || + preserved.Version != 4 || len(preserved.Specializations) != 1 || preserved.Specializations[0].Stack[0] != storedStack { + t.Fatalf("questionnaire after bank coverage change = %d %s, want persisted version 4", questionnaireAfterBankChange.Code, questionnaireAfterBankChange.Body.String()) + } + + for _, privateValue := range []string{ + candidate.Email.Address(), otherCandidate.Email.Address(), employer.Email.Address(), + "PostgreSQL", "gRPC", "Redis", + } { + if strings.Contains(harness.logs.String(), privateValue) { + t.Fatalf("questionnaire HTTP logs contain private value %q", privateValue) + } + } +} + +type questionnaireHTTPResponse struct { + Version int64 `json:"version"` + Specializations []questionnaireHTTPSpecialization `json:"specializations"` + WorkContext json.RawMessage `json:"work_context"` + UpdatedAt json.RawMessage `json:"updated_at"` +} + +type questionnaireHTTPSpecialization struct { + Specialization string `json:"specialization"` + SelfAssessedGrade string `json:"self_assessed_grade"` + TaskLanguages []string `json:"task_languages"` + Stack []string `json:"stack"` + Experience *struct { + CommercialMonths int32 `json:"commercial_months"` + AcademicMonths int32 `json:"academic_months"` + } `json:"experience"` +} + +type questionnaireCatalogResponse struct { + Directions []struct { + Code string `json:"code"` + Specializations []struct { + Code string `json:"code"` + TestAvailability struct { + Status string `json:"status"` + Grades []string `json:"grades"` + TaskLanguages []string `json:"task_languages"` + Note *string `json:"note"` + } `json:"test_availability"` + } `json:"specializations"` + } `json:"directions"` +} + +type questionnaireLogin struct { + cookie string + csrf string +} + +type questionnaireBankFixture struct { + bank *assessment.Bank + publisher *policy.Publisher + metadata domain.AssessmentCategoryCatalogMetadata + firstFamilyKey domain.AssessmentFamilyKey +} + +func seedQuestionnaireCatalogBank(ctx context.Context, t *testing.T, pool *pgxpool.Pool) questionnaireBankFixture { + t.Helper() + transactor := postgresadapter.NewTransactor(pool) + bank := assessment.NewBank(transactor) + store := postgresadapter.NewAssessmentBankStore(pool) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), time.Now) + fixture := assessmentFixture{ + ctx: ctx, pool: pool, store: store, transactor: transactor, bank: bank, + publisher: publisher, demoBundle: loadDemoBundleFile(t), + } + if _, err := bank.ImportBundle(ctx, fixture.demoBundle); err != nil { + t.Fatalf("ImportBundle(unreviewed base bundle) error = %v", err) + } + unreviewedAvailability, err := bank.SpecializationAvailability(ctx) + if err != nil || len(unreviewedAvailability) != 0 { + t.Fatalf("catalog availability after importing an unreviewed draft = %v, %v; want no rows", unreviewedAvailability, err) + } + policyVersion, err := publisher.Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindCalibrated, + Author: policyTestAuthor, Policy: integrationPolicy(11), + }) + if err != nil { + t.Fatalf("Publish(questionnaire grading policy) error = %v", err) + } + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + reviewed := fixture.reviewedBundle(int(required)) + if _, err := bank.ImportBundle(ctx, reviewed); err != nil { + t.Fatalf("ImportBundle(reviewed questionnaire fixture) error = %v", err) + } + for _, family := range reviewed.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } + metadata, err := domain.NewAssessmentCategoryCatalogMetadata( + domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo}, + ) + if err != nil { + t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err) + } + if _, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: assessmentCategory, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, + CatalogMetadata: &metadata, + }); err != nil { + t.Fatalf("OpenCategory(reviewed questionnaire fixture) error = %v", err) + } + return questionnaireBankFixture{ + bank: bank, publisher: publisher, metadata: metadata, + firstFamilyKey: domain.AssessmentFamilyKey(reviewed.Families[0].Key), + } +} + +func newCandidateQuestionnaireHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL)) + profileHandler := v1.NewProfileHandler(profileusecase.NewService(transactor, clock.Now)) + questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now)) + catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor)) + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithProfile(profileHandler), + v1.WithQuestionnaire(questionnaireHandler), v1.WithCatalog(catalogHandler), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func createQuestionnaireHTTPEmployer( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, + registeredAt time.Time, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt, + }) + if err != nil { + t.Fatalf("NewUser(employer) error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(employer) error = %v", err) + } + verified, err := harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(employer) error = %v", err) + } + return verified +} + +func loginCandidateQuestionnaireHTTP(t *testing.T, harness *sessionHTTPHarness, email, remoteAddr string) questionnaireLogin { + t.Helper() + response := loginSessionHTTP(t, harness, email, sessionHTTPTestPass, sessionHTTPTestOrigin, "", remoteAddr) + if response.Code != http.StatusCreated { + t.Fatalf("login questionnaire account = %d %s", response.Code, response.Body.String()) + } + cookie := requireSessionCookie(t, response) + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" { + t.Fatalf("decode questionnaire login response: %v", err) + } + return questionnaireLogin{cookie: cookie.Value, csrf: body.CSRFToken} +} + +func questionnaireHTTPRequest( + t *testing.T, + harness *sessionHTTPHarness, + method, body, cookie, csrf, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + return harness.request(t, method, "/api/v1/me/questionnaire", body, sessionHTTPTestOrigin, cookie, csrf, remoteAddr) +} + +func questionnaireUpdateBody( + t *testing.T, + version int64, + specialization, grade string, + languages, stack []string, + commercialMonths, academicMonths int, +) string { + t.Helper() + if languages == nil { + languages = []string{} + } + if stack == nil { + stack = []string{} + } + var experience any + if commercialMonths != 0 || academicMonths != 0 { + experience = map[string]any{"commercial_months": commercialMonths, "academic_months": academicMonths} + } + encoded, err := json.Marshal(map[string]any{ + "expected_version": version, + "specializations": []any{map[string]any{ + "specialization": specialization, "self_assessed_grade": grade, + "task_languages": languages, "stack": stack, "experience": experience, + }}, + "work_context": map[string]any{"work_formats": []string{"remote"}}, + }) + if err != nil { + t.Fatalf("marshal questionnaire request: %v", err) + } + return string(encoded) +} + +func questionnaireUpdateWithUnknownField(t *testing.T, requestBody, field string, value any) string { + t.Helper() + var body map[string]any + if err := json.Unmarshal([]byte(requestBody), &body); err != nil { + t.Fatalf("decode questionnaire request fixture: %v", err) + } + body[field] = value + encoded, err := json.Marshal(body) + if err != nil { + t.Fatalf("marshal questionnaire request with %s: %v", field, err) + } + return string(encoded) +} + +func questionnaireCatalogHTTP(t *testing.T, harness *sessionHTTPHarness) questionnaireCatalogResponse { + t.Helper() + response := harness.request(t, http.MethodGet, "/api/v1/specializations", "", "", "", "", "192.0.2.200:1234") + if response.Code != http.StatusOK { + t.Fatalf("GetSpecializationCatalog() = %d %s, want 200", response.Code, response.Body.String()) + } + return decodeSpecializationCatalog(t, response.Body.Bytes()) +} + +func decodeSpecializationCatalog(t *testing.T, encoded []byte) questionnaireCatalogResponse { + t.Helper() + var catalog questionnaireCatalogResponse + if err := json.Unmarshal(encoded, &catalog); err != nil { + t.Fatalf("decode specialization catalog: %v", err) + } + return catalog +} + +func assertCatalogAvailability(t *testing.T, catalog questionnaireCatalogResponse, code, status string, grades, languages []string) { + t.Helper() + for _, direction := range catalog.Directions { + for _, specialization := range direction.Specializations { + if specialization.Code != code { + continue + } + actual := specialization.TestAvailability + if actual.Status != status || !slices.Equal(actual.Grades, grades) || !slices.Equal(actual.TaskLanguages, languages) { + t.Fatalf("catalog availability for %s = %+v; want %s grades=%v languages=%v", code, actual, status, grades, languages) + } + if status == "in_development" && (actual.Note == nil || *actual.Note != "Тест в разработке.") { + t.Fatalf("catalog development note for %s = %v, want fixed note", code, actual.Note) + } + if status == "available" && actual.Note != nil { + t.Fatalf("catalog availability note for %s = %q, want null", code, *actual.Note) + } + return + } + } + t.Fatalf("catalog is missing specialization %s", code) +} + +func assertQuestionnaireRows( + t *testing.T, + ctx context.Context, + harness *sessionHTTPHarness, + userID uuid.UUID, + wantVersion int64, + specialization, grade, language, stack string, + commercialMonths, academicMonths int32, +) { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM candidate_questionnaires WHERE user_id = $1", userID).Scan(&count); err != nil { + t.Fatalf("count questionnaire rows: %v", err) + } + wantRows := 1 + if wantVersion == 0 { + wantRows = 0 + } + if count != wantRows { + t.Fatalf("questionnaire rows = %d, want %d", count, wantRows) + } + if wantVersion == 0 { + return + } + var version int64 + var storedSpecialization, storedGrade, storedLanguage, storedStack string + var storedCommercial, storedAcademic int32 + if err := harness.pool.QueryRow(ctx, ` + SELECT questionnaire.version, answer.specialization, answer.self_assessed_grade, + answer.task_languages[1], answer.stack[1], answer.commercial_months, answer.academic_months + FROM candidate_questionnaires AS questionnaire + JOIN candidate_questionnaire_specializations AS answer USING (user_id) + WHERE questionnaire.user_id = $1`, userID).Scan( + &version, &storedSpecialization, &storedGrade, &storedLanguage, &storedStack, &storedCommercial, &storedAcademic, + ); err != nil { + t.Fatalf("read stored questionnaire: %v", err) + } + if version != wantVersion || storedSpecialization != specialization || storedGrade != grade || storedLanguage != language || + storedStack != stack || storedCommercial != commercialMonths || storedAcademic != academicMonths { + t.Fatalf("stored questionnaire = version %d %s/%s/%s/%s/%d/%d; want %d %s/%s/%s/%s/%d/%d", + version, storedSpecialization, storedGrade, storedLanguage, storedStack, storedCommercial, storedAcademic, + wantVersion, specialization, grade, language, stack, commercialMonths, academicMonths) + } +} + +func assertQuestionnaireOnboarding(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID, want string) { + t.Helper() + var step string + if err := harness.pool.QueryRow(ctx, "SELECT onboarding_step FROM users WHERE id = $1", userID).Scan(&step); err != nil { + t.Fatalf("read questionnaire onboarding step: %v", err) + } + if step != want { + t.Fatalf("questionnaire onboarding step = %q, want %q", step, want) + } +} + +func assertQuestionnaireExperienceConstraint(t *testing.T, ctx context.Context, harness *sessionHTTPHarness, userID uuid.UUID) { + t.Helper() + tx, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin questionnaire constraint check: %v", err) + } + defer func() { + if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) { + t.Errorf("rollback questionnaire constraint check: %v", err) + } + }() + if _, err := tx.Exec(ctx, ` + INSERT INTO candidate_questionnaires (user_id, version, work_formats, created_at, updated_at) + VALUES ($1, 1, ARRAY['remote']::text[], statement_timestamp(), statement_timestamp())`, userID); err != nil { + t.Fatalf("insert empty questionnaire row for DB constraint check: %v", err) + } + _, err = tx.Exec(ctx, ` + INSERT INTO candidate_questionnaire_specializations + (user_id, ordinal, specialization, self_assessed_grade, task_languages, stack, commercial_months, academic_months) + VALUES ($1, 0, 'backend', 'junior', ARRAY[]::text[], ARRAY[]::text[], 18, NULL)`, userID) + var pgError *pgconn.PgError + if !errors.As(err, &pgError) || pgError.Code != "23514" || pgError.ConstraintName != "candidate_questionnaire_specializations_experience" { + t.Fatalf("one-sided experience month value error = %v, want experience CHECK", err) + } +} diff --git a/backend/integration_test/redis_ratelimit_test.go b/backend/integration_test/redis_ratelimit_test.go new file mode 100644 index 0000000..d3292c6 --- /dev/null +++ b/backend/integration_test/redis_ratelimit_test.go @@ -0,0 +1,87 @@ +//go:build integration + +package integration_test + +import ( + "errors" + "testing" + "time" + + "lincodex/backend/internal/port/outbound" +) + +func TestRedisRateLimiter(t *testing.T) { + env := bootstrap(t, redisService) + ctx := t.Context() + limiter := env.Redis + + t.Run("admits up to the limit and then reports the wait", func(t *testing.T) { + rule := outbound.RateLimitRule{Window: 10 * time.Second, Limit: 2} + for attempt := 1; attempt <= 2; attempt++ { + decision, err := limiter.Take(ctx, "limit-basic", rule) + if err != nil || !decision.Allowed || decision.RetryAfter != 0 { + t.Fatalf("take %d = %+v, %v, want allowed", attempt, decision, err) + } + } + decision, err := limiter.Take(ctx, "limit-basic", rule) + if err != nil || decision.Allowed || decision.RetryAfter <= 0 || decision.RetryAfter > rule.Window { + t.Fatalf("third take = %+v, %v, want refused with a wait inside the window", decision, err) + } + }) + + t.Run("a refused take counts nothing in any rule", func(t *testing.T) { + interval := outbound.RateLimitRule{Window: 300 * time.Millisecond, Limit: 1} + daily := outbound.RateLimitRule{Window: time.Hour, Limit: 3} + if decision, err := limiter.Take(ctx, "limit-atomic", interval, daily); err != nil || !decision.Allowed { + t.Fatalf("first take = %+v, %v", decision, err) + } + // Refused by the interval: the daily counter must stay at 1. + for range 5 { + if decision, err := limiter.Take(ctx, "limit-atomic", interval, daily); err != nil || decision.Allowed { + t.Fatalf("take inside the interval = %+v, %v, want refused", decision, err) + } + } + time.Sleep(350 * time.Millisecond) + for attempt := 2; attempt <= 3; attempt++ { + decision, err := limiter.Take(ctx, "limit-atomic", interval, daily) + if err != nil || !decision.Allowed { + t.Fatalf("take %d after the interval = %+v, %v, want allowed", attempt, decision, err) + } + time.Sleep(350 * time.Millisecond) + } + decision, err := limiter.Take(ctx, "limit-atomic", interval, daily) + if err != nil || decision.Allowed || decision.RetryAfter < 50*time.Minute { + t.Fatalf("take over the daily limit = %+v, %v, want refused until the daily window ends", decision, err) + } + }) + + t.Run("keys are independent and windows reset", func(t *testing.T) { + rule := outbound.RateLimitRule{Window: 200 * time.Millisecond, Limit: 1} + for _, key := range []string{"limit-a", "limit-b"} { + if decision, err := limiter.Take(ctx, key, rule); err != nil || !decision.Allowed { + t.Fatalf("first take of %s = %+v, %v", key, decision, err) + } + } + time.Sleep(250 * time.Millisecond) + if decision, err := limiter.Take(ctx, "limit-a", rule); err != nil || !decision.Allowed { + t.Fatalf("take after the window = %+v, %v, want allowed", decision, err) + } + }) + + t.Run("rejects an invalid rule", func(t *testing.T) { + for name, rules := range map[string][]outbound.RateLimitRule{ + "no rule": nil, + "zero limit": {{Window: time.Second, Limit: 0}}, + "zero window": {{Window: 0, Limit: 1}}, + "tiny window": {{Window: time.Microsecond, Limit: 1}}, + "second fails": {{Window: time.Second, Limit: 1}, {Window: time.Second, Limit: -1}}, + } { + if _, err := limiter.Take(ctx, "limit-invalid", rules...); !errors.Is(err, outbound.ErrInvalidRateLimitRule) { + t.Fatalf("Take(%s) error = %v, want ErrInvalidRateLimitRule", name, err) + } + } + if _, err := limiter.Take(ctx, "", outbound.RateLimitRule{Window: time.Second, Limit: 1}); !errors.Is(err, outbound.ErrInvalidRateLimitRule) { + t.Fatalf("Take with an empty key error = %v", err) + } + }) +} diff --git a/backend/integration_test/registration_consent_migration_test.go b/backend/integration_test/registration_consent_migration_test.go new file mode 100644 index 0000000..7c30dcd --- /dev/null +++ b/backend/integration_test/registration_consent_migration_test.go @@ -0,0 +1,281 @@ +//go:build integration + +package integration_test + +import ( + "context" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" +) + +const ( + registrationConsentMigrationVersion = 16 + registrationConsentMigrationName = "00016_bind_registration_consent.sql" + mailRetryMigrationName = "00017_retry_unknown_mail.sql" +) + +func TestRegistrationConsentMigration(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + + t.Run("binds legacy C1 rows and survives down and up", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations before preparing legacy data: %v", err) + } + rollbackThroughRegistrationConsent(ctx, t, migrator) + assertRegistrationConsentColumn(ctx, t, pool, false) + + const userID = "018f0000-0000-7000-8000-000000000001" + const registrationConsentID = "018f0000-0000-7000-8000-000000000002" + const settingsConsentID = "018f0000-0000-7000-8000-000000000003" + const otherConsentID = "018f0000-0000-7000-8000-000000000004" + const c1SettingsVersion = "c1-migration-settings" + createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + registrationAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + settingsAt := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC) + seedRegistrationConsentFixture(ctx, t, pool, userID, createdAt, registrationAt, registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion, settingsAt) + + applied, err := migrator.Up(ctx) + if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName { + t.Fatalf("apply registration-consent and later migrations = %+v, %v", applied, err) + } + assertConsentRegistrationVersion(ctx, t, pool, registrationConsentID, 2) + assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID) + + // Model a later registration after its former C1 was discarded. Old + // binaries omit registration_version; the insert trigger must bind the + // new C1 to the account version in effect at insert time. + if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1::uuid`, registrationConsentID); err != nil { + t.Fatalf("remove the previous unverified registration C1: %v", err) + } + nextRegistrationAt := registrationAt.Add(24 * time.Hour) + if _, err := pool.Exec(ctx, `UPDATE users SET registration_version = 3, last_registered_at = $2, version = version + 1, updated_at = $2 WHERE id = $1::uuid`, userID, nextRegistrationAt); err != nil { + t.Fatalf("advance the synthetic registration: %v", err) + } + const compatibilityConsentID = "018f0000-0000-7000-8000-000000000005" + insertLegacyRegistrationC1(ctx, t, pool, compatibilityConsentID, userID, "c1-2026-10-01", nextRegistrationAt) + assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3) + + beforeMismatch := countConsentRecords(ctx, t, pool) + const mismatchedConsentID = "018f0000-0000-7000-8000-000000000006" + _, err = pool.Exec(ctx, ` + INSERT INTO consent_records ( + id, subject_id, purpose, text_version, text_hash, source, granted_at, registration_version + ) + SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256, + 'registration', $3, 2 + FROM consent_texts AS text + WHERE text.purpose = 'c1' AND text.version = 'c1-2026-10-01'`, mismatchedConsentID, userID, nextRegistrationAt) + assertSQLError(t, "registration C1 with an explicitly mismatched version", err, "23514", "consent_records_registration_version_matches_user") + if countConsentRecords(ctx, t, pool) != beforeMismatch { + t.Fatal("a registration C1 with a mismatched account version was inserted") + } + + _, err = pool.Exec(ctx, `UPDATE consent_records + SET registration_version = 4, revoked_at = granted_at, revocation_source = 'support_request' + WHERE id = $1::uuid`, compatibilityConsentID) + assertSQLError(t, "changing a bound registration C1 version during revocation", err, "23000", "consent_records_immutable") + var version int64 + var revokedAt *time.Time + if err := pool.QueryRow(ctx, `SELECT registration_version, revoked_at FROM consent_records WHERE id = $1::uuid`, compatibilityConsentID).Scan(&version, &revokedAt); err != nil { + t.Fatalf("read C1 after refused version change: %v", err) + } + if version != 3 || revokedAt != nil { + t.Fatal("a refused registration C1 version change altered its version or revocation state") + } + + rollbackThroughRegistrationConsent(ctx, t, migrator) + assertRegistrationConsentColumn(ctx, t, pool, false) + if countConsentRecords(ctx, t, pool) != beforeMismatch { + t.Fatal("rolling back the registration-consent migration changed the consent ledger") + } + applied, err = migrator.Up(ctx) + if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName { + t.Fatalf("reapply registration-consent and later migrations = %+v, %v", applied, err) + } + assertRegistrationConsentColumn(ctx, t, pool, true) + assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3) + assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID) + }) + + t.Run("refuses stale legacy registration C1 without a partial migration", func(t *testing.T) { + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("apply migrations before preparing stale legacy data: %v", err) + } + rollbackThroughRegistrationConsent(ctx, t, migrator) + assertRegistrationConsentColumn(ctx, t, pool, false) + + const userID = "018f0000-0000-7000-8000-000000000101" + const consentID = "018f0000-0000-7000-8000-000000000102" + createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC) + grantAt := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + lastRegisteredAt := grantAt.Add(24 * time.Hour) + seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, lastRegisteredAt, 1) + insertLegacyRegistrationC1(ctx, t, pool, consentID, userID, "c1-2026-10-01", grantAt) + + if _, err := migrator.Up(ctx); err == nil { + t.Fatal("migration accepted a registration C1 older than the account's latest registration") + } + assertRegistrationConsentColumn(ctx, t, pool, false) + if countConsentRecords(ctx, t, pool) != 1 { + t.Fatal("a failed migration partially changed the legacy consent record") + } + statuses, err := migrator.Status(ctx) + if err != nil { + t.Fatalf("read migration status after failed migration: %v", err) + } + for _, status := range statuses { + if status.Name == registrationConsentMigrationName && status.Applied { + t.Fatal("failed migration was recorded as applied") + } + } + + if _, err := pool.Exec(ctx, `UPDATE users SET last_registered_at = $2, updated_at = $2 WHERE id = $1::uuid`, userID, grantAt); err != nil { + t.Fatalf("correct the synthetic legacy registration timestamp: %v", err) + } + applied, err := migrator.Up(ctx) + if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName { + t.Fatalf("migrations did not succeed after the legacy data was corrected: %+v, %v", applied, err) + } + assertRegistrationConsentColumn(ctx, t, pool, true) + assertConsentRegistrationVersion(ctx, t, pool, consentID, 1) + }) +} + +// rollbackThroughRegistrationConsent removes later migrations as well, so +// each fixture is truly at the schema immediately before migration 00016. +func rollbackThroughRegistrationConsent(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) { + t.Helper() + for { + rolledBack, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("roll back through registration-consent migration: %v", err) + } + if rolledBack.Version < registrationConsentMigrationVersion { + t.Fatalf("rolled back migration %d before reaching migration %d", rolledBack.Version, registrationConsentMigrationVersion) + } + if rolledBack.Version == registrationConsentMigrationVersion { + if rolledBack.Name != registrationConsentMigrationName { + t.Fatalf("rolled back migration %d named %q, want %q", rolledBack.Version, rolledBack.Name, registrationConsentMigrationName) + } + return + } + } +} + +func seedRegistrationConsentFixture( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + userID string, + createdAt, registrationAt time.Time, + registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion string, + settingsAt time.Time, +) { + t.Helper() + seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, registrationAt, 2) + if _, err := pool.Exec(ctx, ` + INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at) + SELECT purpose, $1, body, sha256(convert_to(body, 'UTF8')), kind, $2 + FROM consent_texts WHERE purpose = 'c1' AND version = 'c1-2026-10-01'`, c1SettingsVersion, createdAt.Add(24*time.Hour)); err != nil { + t.Fatalf("insert synthetic C1 text for a settings consent: %v", err) + } + insertLegacyRegistrationC1(ctx, t, pool, registrationConsentID, userID, "c1-2026-10-01", registrationAt) + insertLegacyConsent(ctx, t, pool, settingsConsentID, userID, "c1", c1SettingsVersion, "consent_settings", settingsAt) + insertLegacyConsent(ctx, t, pool, otherConsentID, userID, "c2", "c2-2026-10-01", "consent_settings", settingsAt) +} + +func seedRegistrationMigrationUser( + ctx context.Context, + t *testing.T, + pool *pgxpool.Pool, + userID string, + createdAt, lastRegisteredAt time.Time, + registrationVersion int64, +) { + t.Helper() + const passwordHash = "$argon2id$v=19$m=1,t=1,p=1$c2FsdA$cGFzcw" + if _, err := pool.Exec(ctx, ` + INSERT INTO users ( + id, email, email_normalized, password_hash, scenario, onboarding_step, + registration_version, last_registered_at, version, created_at, updated_at + ) VALUES ($1::uuid, 'migration.owner@example.test', 'migration.owner@example.test', $2, + 'candidate', 'candidate_consents', $3, $4, 1, $5, $4)`, + userID, passwordHash, registrationVersion, lastRegisteredAt, createdAt); err != nil { + t.Fatalf("insert synthetic account before migration: %v", err) + } +} + +func insertLegacyRegistrationC1(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, version string, grantedAt time.Time) { + t.Helper() + insertLegacyConsent(ctx, t, pool, consentID, userID, "c1", version, "registration", grantedAt) +} + +func insertLegacyConsent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, purpose, version, source string, grantedAt time.Time) { + t.Helper() + if _, err := pool.Exec(ctx, ` + INSERT INTO consent_records (id, subject_id, purpose, text_version, text_hash, source, granted_at) + SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256, $5, $6 + FROM consent_texts AS text WHERE text.purpose = $3 AND text.version = $4`, + consentID, userID, purpose, version, source, grantedAt); err != nil { + t.Fatalf("insert synthetic legacy consent: %v", err) + } +} + +func assertRegistrationConsentColumn(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) { + t.Helper() + var exists bool + if err := pool.QueryRow(ctx, `SELECT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = 'consent_records' AND column_name = 'registration_version' + )`).Scan(&exists); err != nil { + t.Fatalf("check registration-version column: %v", err) + } + if exists != want { + t.Fatalf("registration-version column exists = %t, want %t", exists, want) + } +} + +func assertConsentRegistrationVersion(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID string, want int64) { + t.Helper() + var got int64 + if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&got); err != nil { + t.Fatalf("read bound consent version: %v", err) + } + if got != want { + t.Fatalf("consent registration version = %d, want %d", got, want) + } +} + +func assertConsentRegistrationVersionNull(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentIDs ...string) { + t.Helper() + for _, consentID := range consentIDs { + var version *int64 + if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&version); err != nil { + t.Fatalf("read unbound consent version: %v", err) + } + if version != nil { + t.Fatalf("non-registration consent has registration version %d", *version) + } + } +} + +func countConsentRecords(ctx context.Context, t *testing.T, pool *pgxpool.Pool) int { + t.Helper() + var count int + if err := pool.QueryRow(ctx, `SELECT count(*)::integer FROM consent_records`).Scan(&count); err != nil { + t.Fatalf("count consent records: %v", err) + } + return count +} diff --git a/backend/integration_test/registration_test.go b/backend/integration_test/registration_test.go new file mode 100644 index 0000000..a7fdf08 --- /dev/null +++ b/backend/integration_test/registration_test.go @@ -0,0 +1,808 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/policy" +) + +const ( + registrationTestTimeout = 5 * time.Minute + registrationPath = "/api/v1/identity/registrations" + resendPath = "/api/v1/identity/email-verification-requests" + emailVerificationPath = "/api/v1/identity/email-verifications" + registrationPassword = "correct horse battery staple" + registrationC1 = `{"text_version":"c1-2026-10-01","accepted":true}` + // registrationMinInterval is long enough that one request, including the + // password hash, finishes well inside it, and short enough to wait out. + // The production default is a minute. + registrationMinInterval = 3 * time.Second + registrationDailyLimit = 3 + // registrationEmailHourlyLimit is the production default of the login + // limit per address, which code confirmation shares. + registrationEmailHourlyLimit = 10 + registrationSecret = "integration-test-identity-key-secret-0123456789" + registrationApplication = "registration_http" +) + +var ( + registrationTables = slices.Concat( + mailSenderTables, + usersDependentTables, + []pgx.Identifier{{"idempotency_records"}, {"outbox_events"}}, + ) + // verificationLinkToken finds the token in the fragment of the link of + // the sent message. + verificationLinkToken = regexp.MustCompile(`#token=([A-Za-z0-9_-]{32,128})`) +) + +type registrationHarness struct { + pool *pgxpool.Pool + router http.Handler + sender *notification.ServiceMailSender + fixture *resendfixture.Server + clock *testClock + logs *syncBuffer + identity *postgresadapter.IdentityStore + origin string + // registration is the usecase behind the router. + registration *identity.Registration + // nextKey makes every request carry a new Idempotency-Key. + nextKey int + // start is the application time at the beginning of every subtest. + start time.Time +} + +func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironment, clientHourlyLimit int64) *registrationHarness { + t.Helper() + poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) + if err != nil { + t.Fatalf("parse bootstrap database URL: %v", err) + } + poolConfig.MaxConns = 16 + poolConfig.ConnConfig.RuntimeParams["application_name"] = registrationApplication + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + t.Fatalf("create registration PostgreSQL pool: %v", err) + } + t.Cleanup(pool.Close) + // The demo policy is effective from its publication by the database clock, + // so the application clock must not be earlier than now. + clock := &testClock{now: time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond)} + start := clock.Now() + logs := &syncBuffer{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + fixture := resendfixture.New() + t.Cleanup(fixture.Close) + transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now) + if err != nil { + t.Fatalf("NewLoopbackSender() error = %v", err) + } + account, err := domain.NewMailProviderAccount("resend", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + // The product policy carries the verification token lifetime. + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + + hasher, err := argon2id.NewHasher(2) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + keyring, err := identity.NewKeyring([]byte(registrationSecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + identityStore := postgresadapter.NewIdentityStore(pool) + credentials := identity.NewCredentials(hasher) + metrics := prometheus.New() + registration, err := identity.NewRegistration(identity.RegistrationDependencies{ + Transactor: transactor, + ConsentTexts: postgresadapter.NewConsentStore(pool), + Idempotency: identityStore.IdempotencyRecords(), + Consents: consent.NewService(transactor, clock.Now), + Credentials: credentials, + Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now), + Limiter: env.Redis, + Keyring: keyring, + Clock: clock.Now, + Metrics: metrics, + }, identity.RegistrationSettings{ + MailMinInterval: registrationMinInterval, + MailDailyLimit: registrationDailyLimit, + ClientHourlyLimit: clientHourlyLimit, + }) + if err != nil { + t.Fatalf("NewRegistration() error = %v", err) + } + confirmation, err := identity.NewEmailConfirmation(identity.ConfirmationDependencies{ + Transactor: transactor, + Tokens: identityStore.EmailTokens(), + Credentials: credentials, + Limiter: env.Redis, + Keyring: keyring, + Clock: clock.Now, + Metrics: metrics, + }, identity.ConfirmationSettings{ + TokenHourlyLimit: 2, + ClientHourlyLimit: clientHourlyLimit, + EmailHourlyLimit: registrationEmailHourlyLimit, + }) + if err != nil { + t.Fatalf("NewEmailConfirmation() error = %v", err) + } + + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler( + registration, + v1.WithEmailConfirmation(confirmation), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ))) + router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + + limits, err := domain.NewMailQuotaLimits(1000, 10000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + gate := notification.NewQuotaGate(account, limits, resend.IdempotencyWindow, clock.Now, logger) + sender, err := notification.NewServiceMailSender(transactor, transport, gate, notification.ServiceMailSenderSettings{ + Account: account, + Lease: time.Minute, + StoreTimeout: 30 * time.Second, + SettleBudget: mailSenderSettleBudget, + ShutdownSettleBudget: time.Second, + MaxFailures: 3, + Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, + }, clock.Now, logger) + if err != nil { + t.Fatalf("NewServiceMailSender() error = %v", err) + } + return ®istrationHarness{ + start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore, + origin: env.Config.AppPublicURL, + registration: registration, + } +} + +type registrationResponse struct { + status int + body string + retryAfter string + // contentType is part of the shape that must not depend on the branch. + contentType string + setCookie string +} + +func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse { + return harness.postWithOriginDefault(t, path, body, headers, true) +} + +func (harness *registrationHarness) postWithoutDefaultOrigin(t *testing.T, path, body string, headers map[string]string) registrationResponse { + return harness.postWithOriginDefault(t, path, body, headers, false) +} + +func (harness *registrationHarness) postWithOriginDefault(t *testing.T, path, body string, headers map[string]string, setDefaultOrigin bool) registrationResponse { + t.Helper() + request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + if setDefaultOrigin { + request.Header.Set("Origin", harness.origin) + } + for name, value := range headers { + request.Header.Set(name, value) + } + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return registrationResponse{ + status: recorder.Code, + body: recorder.Body.String(), + retryAfter: recorder.Header().Get("Retry-After"), + contentType: recorder.Header().Get("Content-Type"), + setCookie: recorder.Header().Get("Set-Cookie"), + } +} + +func registrationBody(email, scenario, password, consent string) string { + return `{"email":"` + email + `","password":"` + password + `","scenario":"` + scenario + `","consent_c1":` + consent + `}` +} + +// register posts a registration under a fresh Idempotency-Key unless key is +// given. +func (harness *registrationHarness) register(t *testing.T, email, scenario, key string) registrationResponse { + t.Helper() + return harness.registerBody(t, registrationBody(email, scenario, registrationPassword, registrationC1), key) +} + +func (harness *registrationHarness) registerBody(t *testing.T, body, key string) registrationResponse { + t.Helper() + if key == "" { + harness.nextKey++ + key = "integration-key-" + strconv.Itoa(harness.nextKey) + } + return harness.post(t, registrationPath, body, map[string]string{"Idempotency-Key": key}) +} + +func (harness *registrationHarness) resend(t *testing.T, email string) registrationResponse { + t.Helper() + return harness.post(t, resendPath, `{"email":"`+email+`"}`, nil) +} + +func (harness *registrationHarness) count(ctx context.Context, t *testing.T, query string, args ...any) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return count +} + +// drain runs the sending worker until it finds nothing due and returns how +// many deliveries it settled. +func (harness *registrationHarness) drain(ctx context.Context, t *testing.T) int { + t.Helper() + settled := 0 + for range 20 { + result, err := harness.sender.ProcessNext(ctx, ctx) + if err != nil { + t.Fatalf("ProcessNext() error = %v", err) + } + if result.Outcome == inbound.MailPassIdle { + return settled + } + settled++ + } + t.Fatal("the sending worker did not go idle") + return settled +} + +// registerAndSendVerification follows the real registration message through +// the local Resend receiver and returns the token from the received link. +func (harness *registrationHarness) registerAndSendVerification( + ctx context.Context, + t *testing.T, + email, scenario, password string, +) string { + t.Helper() + link := verificationLinkToken.FindStringSubmatch(harness.registerAndReceiveVerification(ctx, t, email, scenario, password)) + if link == nil { + t.Fatal("the received verification message has no token in its link fragment") + } + return link[1] +} + +// registerAndReceiveVerification registers the address, delivers the queued +// message through the fixture, and returns the text of the message. +func (harness *registrationHarness) registerAndReceiveVerification( + ctx context.Context, + t *testing.T, + email, scenario, password string, +) string { + t.Helper() + requestCount := len(harness.fixture.Requests()) + response := harness.registerBody(t, registrationBody(email, scenario, password, registrationC1), "") + requireAccepted(t, response) + return harness.receiveVerificationText(ctx, t, email, requestCount) +} + +// receiveVerificationText drains the sending worker and returns the text of the +// one message the fixture received after requestCount requests. +func (harness *registrationHarness) receiveVerificationText(ctx context.Context, t *testing.T, email string, requestCount int) string { + t.Helper() + if settled := harness.drain(ctx, t); settled != 1 { + t.Fatalf("settled %d deliveries, want 1", settled) + } + received := harness.fixture.Requests()[requestCount:] + if len(received) != 1 || !slices.Equal(received[0].To, []string{email}) { + t.Fatalf("fixture received %d messages, want one to the registered address", len(received)) + } + return received[0].Text +} + +// truncate empties the tables of the flow. CASCADE also empties tables that +// later migrations add with a reference to users, so this suite does not +// depend on usersDependentTables being kept up to date by other tasks. +func (harness *registrationHarness) truncate(ctx context.Context, t *testing.T) { + t.Helper() + names := make([]string, 0, len(registrationTables)) + for _, table := range registrationTables { + names = append(names, table.Sanitize()) + } + harness.exec(ctx, t, "TRUNCATE "+strings.Join(names, ", ")+" CASCADE") +} + +func (harness *registrationHarness) exec(ctx context.Context, t *testing.T, statement string, args ...any) { + t.Helper() + if _, err := harness.pool.Exec(ctx, statement, args...); err != nil { + t.Fatalf("exec %q: %v", statement, err) + } +} + +func (harness *registrationHarness) assertLogsHoldNoSecrets(t *testing.T, forbidden ...string) { + t.Helper() + logs := harness.logs.String() + for _, marker := range forbidden { + if marker != "" && strings.Contains(logs, marker) { + t.Fatalf("a secret or an address reached the logs:\n%s", logs) + } + } +} + +// requireProblemStatus checks the status and the problem code of a response +// and returns its body. +func requireProblemStatus(t *testing.T, response registrationResponse, status int, code string) string { + t.Helper() + if response.status != status || !strings.Contains(response.body, `"code":"`+code+`"`) { + t.Fatalf("response = %d %s, want %d with code %s", response.status, response.body, status, code) + } + return response.body +} + +// requireRetryWithinInterval checks the wait of a refusal by the minimum +// interval: at least one second and at most the interval. +func requireRetryWithinInterval(t *testing.T, response registrationResponse) { + t.Helper() + wait, err := strconv.Atoi(response.retryAfter) + if err != nil || wait < 1 || wait > int(registrationMinInterval/time.Second) { + t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(registrationMinInterval/time.Second)) + } +} + +func requireAccepted(t *testing.T, response registrationResponse) { + t.Helper() + if response.status != http.StatusAccepted || response.body != `{"status":"accepted"}` { + t.Fatalf("response = %d %s, want the neutral 202", response.status, response.body) + } +} + +func TestRegistrationOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + reset := func(t *testing.T) { + t.Helper() + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + } + + t.Run("a candidate registers in one transaction with C1 and a queued message", func(t *testing.T) { + reset(t) + requests := len(harness.fixture.Requests()) + response := harness.register(t, "Candidate.One@Example.com", "candidate", "") + requireAccepted(t, response) + + var scenario, step string + var verified *time.Time + var version int64 + err := harness.pool.QueryRow(ctx, + `SELECT scenario, onboarding_step, email_verified_at, registration_version FROM users WHERE email_normalized = 'candidate.one@example.com'`, + ).Scan(&scenario, &step, &verified, &version) + if err != nil { + t.Fatalf("read the account: %v", err) + } + if scenario != "candidate" || step != "candidate_consents" || verified != nil || version != 1 { + t.Fatalf("account = %s %s verified=%v version=%d", scenario, step, verified, version) + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + + // C1 with the current text version and its hash; nothing else, in + // particular no C4. + c1Text, err := postgresadapter.NewConsentStore(harness.pool).ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, harness.clock.Now()) + if err != nil { + t.Fatalf("read the current C1 text: %v", err) + } + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 1) + var purpose, textVersion, source string + var textHash []byte + var revoked *time.Time + err = harness.pool.QueryRow(ctx, `SELECT purpose, text_version, text_hash, source, revoked_at FROM consent_records`). + Scan(&purpose, &textVersion, &textHash, &source, &revoked) + wantHash := c1Text.Hash() + if err != nil || purpose != "c1" || textVersion != string(c1Text.Version()) || !bytes.Equal(textHash, wantHash[:]) || + source != "registration" || revoked != nil { + t.Fatalf("consent record = %s %s %x %s revoked=%v, err=%v", purpose, textVersion, textHash, source, revoked, err) + } + if harness.count(ctx, t, `SELECT count(*) FROM consent_records WHERE purpose = 'c4'`) != 0 { + t.Fatal("C4 was recorded by the registration") + } + + // One token hash (never the raw token) and one queued delivery bound + // to it, in the same commit. + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + var tokenHash []byte + var tokenID, deliveryTokenID string + var tokenVersion int64 + if err := harness.pool.QueryRow(ctx, `SELECT id::text, token_hash, registration_version FROM email_tokens`).Scan(&tokenID, &tokenHash, &tokenVersion); err != nil { + t.Fatalf("read the token: %v", err) + } + if len(tokenHash) != sha256.Size || tokenVersion != 1 { + t.Fatalf("token hash length = %d, version = %d", len(tokenHash), tokenVersion) + } + var status string + if err := harness.pool.QueryRow(ctx, `SELECT status, email_token_id::text FROM deliveries`).Scan(&status, &deliveryTokenID); err != nil { + t.Fatalf("read the delivery: %v", err) + } + if status != string(domain.DeliveryStatusPending) || deliveryTokenID != tokenID { + t.Fatalf("delivery = %s bound to %s, want pending bound to token %s", status, deliveryTokenID, tokenID) + } + + // The sending worker sends it through the local Resend fixture. + if settled := harness.drain(ctx, t); settled != 1 { + t.Fatalf("settled %d deliveries, want 1", settled) + } + sent := harness.fixture.Requests()[requests:] + if len(sent) != 1 || !slices.Equal(sent[0].To, []string{"Candidate.One@Example.com"}) { + t.Fatalf("fixture received %d messages to %v", len(sent), sent) + } + link := verificationLinkToken.FindStringSubmatch(sent[0].Text) + if link == nil { + t.Fatal("the message holds no verification link with the token in the fragment") + } + sum := sha256.Sum256([]byte(link[1])) + if !bytes.Equal(sum[:], tokenHash) { + t.Fatal("the token of the link does not match the stored hash") + } + harness.assertLogsHoldNoSecrets(t, "Candidate.One", registrationPassword, link[1]) + }) + + t.Run("an employer registers once and a repeat creates no second account and reveals nothing", func(t *testing.T) { + reset(t) + first := harness.register(t, "employer@example.com", "employer", "employer-key-1") + requireAccepted(t, first) + var step string + if err := harness.pool.QueryRow(ctx, `SELECT onboarding_step FROM users`).Scan(&step); err != nil || step != "employer_company" { + t.Fatalf("onboarding step = %q, err = %v, want employer_company", step, err) + } + + // The same request replays: one account, one token, one message. + replay := harness.register(t, "employer@example.com", "employer", "employer-key-1") + if replay != first { + t.Fatalf("replay = %+v, want exactly %+v", replay, first) + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + assertRowCount(ctx, t, harness.pool, pgx.Identifier{"deliveries"}, 1) + + // The same key with another body is a reused key. + reused := harness.registerBody(t, registrationBody("employer@example.com", "employer", "another correct horse battery", registrationC1), "employer-key-1") + requireProblemStatus(t, reused, http.StatusUnprocessableEntity, "idempotency_key_reused") + + // A new registration of the pending address, with another password and + // scenario, never changes the credentials of the account row. + var firstHash string + if err := harness.pool.QueryRow(ctx, `SELECT password_hash FROM users`).Scan(&firstHash); err != nil { + t.Fatalf("read the password hash: %v", err) + } + time.Sleep(registrationMinInterval + 100*time.Millisecond) + again := harness.registerBody(t, registrationBody("employer@example.com", "candidate", "an attacker chosen long password", registrationC1), "") + if again != first { + t.Fatalf("repeat = %+v, want the same answer as the first registration %+v", again, first) + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + var scenario string + var version int64 + if err := harness.pool.QueryRow(ctx, `SELECT scenario, registration_version FROM users`).Scan(&scenario, &version); err != nil { + t.Fatalf("read the account: %v", err) + } + var hashAfter, stepAfter string + if err := harness.pool.QueryRow(ctx, `SELECT password_hash, onboarding_step FROM users`).Scan(&hashAfter, &stepAfter); err != nil { + t.Fatalf("read the account: %v", err) + } + if scenario != "employer" || stepAfter != "employer_company" || hashAfter != firstHash || version != 2 { + t.Fatalf("after the repeat: scenario = %s, step = %s, registration version = %d, hash unchanged = %t; want the first registration's credentials and version 2", + scenario, stepAfter, version, hashAfter == firstHash) + } + // Each token carries the pending credentials of its own registration; + // the invalidated first token keeps none. + rows, err := harness.pool.Query(ctx, `SELECT pending_password_hash, pending_scenario, pending_onboarding_step, registration_version, invalidated_at IS NOT NULL + FROM email_tokens ORDER BY created_at, id`) + if err != nil { + t.Fatalf("read the tokens: %v", err) + } + type pendingRow struct { + hash, scenario, step *string + version int64 + invalidated bool + } + var pendings []pendingRow + for rows.Next() { + var row pendingRow + if err := rows.Scan(&row.hash, &row.scenario, &row.step, &row.version, &row.invalidated); err != nil { + t.Fatalf("scan a token: %v", err) + } + pendings = append(pendings, row) + } + rows.Close() + if len(pendings) != 2 || + !pendings[0].invalidated || pendings[0].hash != nil || pendings[0].scenario != nil || pendings[0].step != nil || pendings[0].version != 1 || + pendings[1].invalidated || pendings[1].hash == nil || *pendings[1].hash == firstHash || + pendings[1].scenario == nil || *pendings[1].scenario != "candidate" || + pendings[1].step == nil || *pendings[1].step != "candidate_consents" || pendings[1].version != 2 { + t.Fatalf("tokens do not carry their own pending credentials: %+v", pendings) + } + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 1) + if active := harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NULL AND consumed_at IS NULL`); active != 1 { + t.Fatalf("%d unused tokens, want exactly the new one", active) + } + if all := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`); all != 2 { + t.Fatalf("%d tokens, want the replaced one and the new one", all) + } + + // A verified address is left alone and answers the same way. + var userID string + if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users`).Scan(&userID); err != nil { + t.Fatalf("read the account ID: %v", err) + } + harness.exec(ctx, t, `UPDATE users SET email_verified_at = $1 WHERE id = $2`, harness.clock.Now(), userID) + tokens := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) + deliveries := harness.count(ctx, t, `SELECT count(*) FROM deliveries`) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + verified := harness.register(t, "employer@example.com", "employer", "") + if verified != first { + t.Fatalf("verified address answered %+v, want %+v", verified, first) + } + if harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != tokens || + harness.count(ctx, t, `SELECT count(*) FROM deliveries`) != deliveries || + harness.count(ctx, t, `SELECT count(*) FROM users WHERE scenario = 'employer' AND registration_version = 2`) != 1 { + t.Fatal("a registration of a verified address changed the account or queued a message") + } + // The replaced token never reaches the user: the sending worker + // cancels its message because the token is no longer current. + harness.drain(ctx, t) + harness.assertLogsHoldNoSecrets(t, "employer@example.com", registrationPassword) + }) + + t.Run("a stale consent text version is refused the same way and consumes nothing", func(t *testing.T) { + reset(t) + stale := `{"text_version":"c1-2000-01-01","accepted":true}` + for _, email := range []string{"new.address@example.com", "known.address@example.com"} { + if email == "known.address@example.com" { + requireAccepted(t, harness.register(t, email, "candidate", "")) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + } + response := harness.registerBody(t, registrationBody(email, "candidate", registrationPassword, stale), "") + body := requireProblemStatus(t, response, http.StatusBadRequest, "validation_failed") + if !strings.Contains(body, `"/consent_c1/text_version"`) { + t.Fatalf("problem %s does not point at /consent_c1/text_version", body) + } + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + }) + + t.Run("resend replaces the unused token and is rate limited without a new token", func(t *testing.T) { + reset(t) + requests := len(harness.fixture.Requests()) + const email = "resend.candidate@example.com" + requireAccepted(t, harness.register(t, email, "candidate", "")) + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + + // Inside the minimum interval: 429 with the wait, and no new token. + limited := harness.resend(t, email) + requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited") + requireRetryWithinInterval(t, limited) + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + + // Within the daily limit: every resend replaces the previous token. + for sent := 2; sent <= registrationDailyLimit; sent++ { + time.Sleep(registrationMinInterval + 100*time.Millisecond) + requireAccepted(t, harness.resend(t, email)) + assertRowCount(ctx, t, harness.pool, emailTokensTable, sent) + if active := harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NULL AND consumed_at IS NULL`); active != 1 { + t.Fatalf("after resend %d: %d unused tokens, want 1", sent, active) + } + } + + // A resend keeps the credentials of the registration it resends for on + // its new token; every invalidated token keeps none. + if harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE pending_password_hash IS NOT NULL`) != 1 || + harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NOT NULL AND pending_password_hash IS NOT NULL`) != 0 || + harness.count(ctx, t, `SELECT count(*) FROM email_tokens AS token JOIN users ON users.id = token.user_id + WHERE token.invalidated_at IS NULL AND token.pending_password_hash = users.password_hash`) != 1 { + t.Fatal("resent tokens do not carry the pending credentials of the registration") + } + + // Over the daily limit: 429 with a long wait and no new token. + time.Sleep(registrationMinInterval + 100*time.Millisecond) + capped := harness.resend(t, email) + requireProblemStatus(t, capped, http.StatusTooManyRequests, "rate_limited") + if wait, err := strconv.Atoi(capped.retryAfter); err != nil || wait <= int(registrationMinInterval/time.Second) { + t.Fatalf("Retry-After over the daily limit = %q, want the wait until the window ends", capped.retryAfter) + } + assertRowCount(ctx, t, harness.pool, emailTokensTable, registrationDailyLimit) + + // Only the message of the last token is current; the others are + // cancelled by the worker, and the message goes through the fixture. + harness.drain(ctx, t) + sent := harness.fixture.Requests()[requests:] + if len(sent) != 1 || !slices.Equal(sent[0].To, []string{email}) { + t.Fatalf("fixture received %d messages, want exactly the one of the current token: %v", len(sent), sent) + } + var lastHash []byte + if err := harness.pool.QueryRow(ctx, `SELECT token_hash FROM email_tokens WHERE invalidated_at IS NULL`).Scan(&lastHash); err != nil { + t.Fatalf("read the current token: %v", err) + } + link := verificationLinkToken.FindStringSubmatch(sent[0].Text) + sum := sha256.Sum256([]byte(link[1])) + if link == nil || !bytes.Equal(sum[:], lastHash) { + t.Fatal("the delivered link is not the one of the current token") + } + if cancelled := harness.count(ctx, t, `SELECT count(*) FROM deliveries WHERE status = 'cancelled'`); cancelled != registrationDailyLimit-1 { + t.Fatalf("%d cancelled deliveries, want %d", cancelled, registrationDailyLimit-1) + } + harness.assertLogsHoldNoSecrets(t, "resend.candidate", link[1]) + }) + + t.Run("resend answers an unknown and a verified address like an unverified one", func(t *testing.T) { + reset(t) + requireAccepted(t, harness.register(t, "pending@example.com", "candidate", "")) + requireAccepted(t, harness.register(t, "done@example.com", "candidate", "")) + harness.exec(ctx, t, `UPDATE users SET email_verified_at = $1 WHERE email_normalized = 'done@example.com'`, harness.clock.Now()) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + tokens := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) + + pending := harness.resend(t, "pending@example.com") + unknown := harness.resend(t, "nobody@example.com") + verified := harness.resend(t, "done@example.com") + requireAccepted(t, pending) + if unknown != pending || verified != pending { + t.Fatalf("answers differ: pending %+v, unknown %+v, verified %+v", pending, unknown, verified) + } + if got := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`); got != tokens+1 { + t.Fatalf("%d tokens, want %d: only the unverified account gets one", got, tokens+1) + } + assertRowCount(ctx, t, harness.pool, usersTable, 2) + + // The limit does not depend on the account either: a never + // registered address is refused on the same schedule. + for _, email := range []string{"pending@example.com", "nobody@example.com", "done@example.com"} { + response := harness.resend(t, email) + requireProblemStatus(t, response, http.StatusTooManyRequests, "rate_limited") + requireRetryWithinInterval(t, response) + } + }) + + t.Run("a validation error does not consume the limit", func(t *testing.T) { + reset(t) + bad := harness.registerBody(t, registrationBody("not-an-email", "candidate", registrationPassword, registrationC1), "") + requireProblemStatus(t, bad, http.StatusBadRequest, "validation_failed") + short := harness.registerBody(t, registrationBody("short.password@example.com", "candidate", "too short", registrationC1), "") + requireProblemStatus(t, short, http.StatusBadRequest, "validation_failed") + requireAccepted(t, harness.register(t, "short.password@example.com", "candidate", "")) + }) +} + +func TestPublicIdentityOriginRefusalDoesNotMutateAccountsOrMailState(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + + const verifiedFlowEmail = "origin-check@example.test" + token := harness.registerAndSendVerification(ctx, t, verifiedFlowEmail, "candidate", registrationPassword) + stateCounts := func() map[string]int { + t.Helper() + counts := make(map[string]int) + for _, table := range []string{"users", "consent_records", "email_tokens", "idempotency_records", "outbox_events", "deliveries"} { + counts[table] = harness.count(ctx, t, "SELECT count(*) FROM "+table) + } + return counts + } + assertCountsUnchanged := func(want map[string]int) { + t.Helper() + for table, expected := range want { + if got := harness.count(ctx, t, "SELECT count(*) FROM "+table); got != expected { + t.Errorf("%s count = %d after Origin refusal, want unchanged at %d", table, got, expected) + } + } + } + before := stateCounts() + register := harness.post(t, registrationPath, + registrationBody("rejected@example.test", "candidate", registrationPassword, registrationC1), + map[string]string{"Idempotency-Key": "origin-refused-registration", "Origin": "https://attacker.example"}, + ) + requireProblemStatus(t, register, http.StatusForbidden, "csrf_check_failed") + assertCountsUnchanged(before) + + resend := harness.post(t, resendPath, `{"email":"`+verifiedFlowEmail+`"}`, map[string]string{"Origin": "https://attacker.example"}) + requireProblemStatus(t, resend, http.StatusForbidden, "csrf_check_failed") + assertCountsUnchanged(before) + + confirmation := harness.post(t, emailVerificationPath, + `{"token":"`+token+`","password":"`+registrationPassword+`"}`, + map[string]string{"Origin": "https://attacker.example"}, + ) + requireProblemStatus(t, confirmation, http.StatusForbidden, "csrf_check_failed") + assertCountsUnchanged(before) + + var verifiedAt *time.Time + var registrationVersion int64 + if err := harness.pool.QueryRow(ctx, + `SELECT email_verified_at, registration_version FROM users WHERE email_normalized = $1`, verifiedFlowEmail, + ).Scan(&verifiedAt, ®istrationVersion); err != nil { + t.Fatalf("read account after Origin refusals: %v", err) + } + if verifiedAt != nil || registrationVersion != 1 { + t.Fatalf("account state after refused operations: verified=%v registration version=%d", verifiedAt, registrationVersion) + } + var consumedAt, invalidatedAt *time.Time + if err := harness.pool.QueryRow(ctx, + `SELECT consumed_at, invalidated_at FROM email_tokens WHERE user_id = (SELECT id FROM users WHERE email_normalized = $1)`, verifiedFlowEmail, + ).Scan(&consumedAt, &invalidatedAt); err != nil { + t.Fatalf("read verification token state after Origin refusals: %v", err) + } + if consumedAt != nil || invalidatedAt != nil { + t.Fatalf("verification token changed after Origin refusals: consumed=%v invalidated=%v", consumedAt, invalidatedAt) + } +} + +func TestRegistrationClientLimit(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 2) + harness.truncate(ctx, t) + + // The usecase counts a request with a client key against the per-client + // rule; the handler supplies the key from the resolved network address. + registration := harness.registration + for index, email := range []string{"client.one@example.com", "client.two@example.com", "client.three@example.com"} { + err := registration.Register(ctx, identity.RegisterCommand{ + IdempotencyKey: "client-key-" + email, Email: email, Password: registrationPassword, + Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "203.0.113.9", + }) + var limited *identity.RateLimitedError + switch { + case index < 2 && err != nil: + t.Fatalf("registration %d error = %v, want accepted", index+1, err) + case index == 2 && !errors.As(err, &limited): + t.Fatalf("registration 3 error = %v, want *RateLimitedError", err) + } + } + assertRowCount(ctx, t, harness.pool, usersTable, 2) +} diff --git a/backend/integration_test/scheduled_jobs_test.go b/backend/integration_test/scheduled_jobs_test.go new file mode 100644 index 0000000..91a3fe9 --- /dev/null +++ b/backend/integration_test/scheduled_jobs_test.go @@ -0,0 +1,758 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/worker/jobrunner" + "lincodex/backend/internal/worker/retry" + "lincodex/backend/pkg/testutil" +) + +const ( + jobTestTimeout = 3 * time.Minute + // jobTestKind is registered only by the test handler. + jobTestKind = "test.effect" + // jobTestLease is long in real time: the fake clock alone decides when + // a lease expired, and a handler never runs out of it by accident. + jobTestLease = time.Minute + jobTestBackoff = time.Second + jobTestGrace = 2 * time.Second + jobTestShortGrace = 200 * time.Millisecond + jobTestMaxAttempts = 3 + // jobTestConcurrentJobs is enough jobs for two workers to overlap. + jobTestConcurrentJobs = 40 + jobEffectsSchema = "job_test" + jobEffectsTable = "effects" + jobCancelApplication = "job_cancel" +) + +var ( + jobTestStart = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC) + jobEffects = pgx.Identifier{jobEffectsSchema, jobEffectsTable} + createJobEffectsTable = fmt.Sprintf(` + CREATE SCHEMA %[1]s; + -- No unique key: a second effect of a job must stay visible. seq + -- records the commit order of the effects. + CREATE TABLE %[2]s ( + seq bigint GENERATED ALWAYS AS IDENTITY, + job_id bigint NOT NULL, + job_key text NOT NULL, + worker text NOT NULL + )`, pgx.Identifier{jobEffectsSchema}.Sanitize(), jobEffects.Sanitize()) + errJobEffectFailed = errors.New("job effect failed") +) + +// jobEffectHandler is the test-only handler: it writes one effect row in +// the transaction that completes the job, then runs hook in it. +type jobEffectHandler struct { + worker string + hook func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error +} + +func (*jobEffectHandler) JobKind() string { return jobTestKind } + +func (handler *jobEffectHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return errors.New("unit of work is not a PostgreSQL transaction") + } + if _, err := tx.Exec(ctx, "INSERT INTO "+jobEffects.Sanitize()+" (job_id, job_key, worker) VALUES ($1, $2, $3)", job.ID, job.Key, handler.worker); err != nil { + return err + } + if handler.hook == nil { + return nil + } + return handler.hook(ctx, unit, job) +} + +// jobHarness schedules jobs through the scheduler port and builds workers +// the way the application does, each with its own pool, against one +// database and one fake clock. +type jobHarness struct { + env *testEnvironment + pool *pgxpool.Pool + clock *testutil.FakeClock +} + +// jobInstance is one simulated backend process: its own pool, store, and +// worker. Dropping it and building another one is a restart. +type jobInstance struct { + pool *pgxpool.Pool + store *postgresadapter.ScheduledJobStore + worker *jobrunner.Worker + metrics *prometheus.Metrics +} + +func jobTestSettings(grace time.Duration) jobrunner.Settings { + return jobrunner.Settings{ + BatchSize: 5, + PollInterval: 10 * time.Millisecond, + Lease: jobTestLease, + MaxAttempts: jobTestMaxAttempts, + Backoff: retry.Backoff{Initial: jobTestBackoff, Max: jobTestBackoff}, + ShutdownGrace: grace, + StoreTimeout: 5 * time.Second, + BacklogInterval: time.Second, + } +} + +func (harness *jobHarness) start(ctx context.Context, t *testing.T, handler *jobEffectHandler, settings jobrunner.Settings) *jobInstance { + t.Helper() + pool := harness.env.newPool(ctx, t) + store := postgresadapter.NewScheduledJobStore(pool, settings.Lease) + metrics := prometheus.New() + worker, err := jobrunner.New([]inbound.JobHandler{handler}, store, metrics, slog.New(slog.DiscardHandler), settings, harness.clock.Now) + if err != nil { + t.Fatalf("jobrunner.New() error = %v", err) + } + return &jobInstance{pool: pool, store: store, worker: worker, metrics: metrics} +} + +// schedule schedules a job of the test kind in its own transaction and +// reports whether it was new. +func (harness *jobHarness) schedule(ctx context.Context, t *testing.T, key string, dueAt time.Time, maxAttempts int) bool { + t.Helper() + job, err := domain.NewScheduledJob(domain.ScheduledJobInput{ + Kind: jobTestKind, Key: key, DueAt: dueAt, MaxAttempts: maxAttempts, + Payload: []byte(`{"subject_id":"` + key + `"}`), + }) + if err != nil { + t.Fatalf("NewScheduledJob() error = %v", err) + } + var scheduled bool + err = postgresadapter.NewTransactor(harness.pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + scheduled, err = unit.ScheduledJobs().Schedule(ctx, job) + return err + }) + if err != nil { + t.Fatalf("Schedule() error = %v", err) + } + return scheduled +} + +func (harness *jobHarness) cancel(ctx context.Context, t *testing.T, key string) bool { + t.Helper() + cancelled, err := cancelJob(ctx, harness.pool, key) + if err != nil { + t.Fatalf("Cancel() error = %v", err) + } + return cancelled +} + +// cancelJob cancels a job of the test kind in its own transaction on pool. +func cancelJob(ctx context.Context, pool *pgxpool.Pool, key string) (bool, error) { + var cancelled bool + err := postgresadapter.NewTransactor(pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + cancelled, err = unit.ScheduledJobs().Cancel(ctx, jobTestKind, key) + return err + }) + return cancelled, err +} + +// stall claims the one due job with a lease owner of its own, as a worker +// that then stops would, and with started also records that its handler +// began. It returns the stale claim. +func (harness *jobHarness) stall(ctx context.Context, t *testing.T, instance *jobInstance, started bool) outbound.ClaimedJob { + t.Helper() + claimed, err := instance.store.Claim(ctx, outbound.JobClaim{ + Owner: uuid.New(), Kinds: []string{jobTestKind}, Now: harness.clock.Now(), + Lease: jobTestLease, Limit: 1, DefaultMaxAttempts: jobTestMaxAttempts, + }) + if err != nil || len(claimed) != 1 { + t.Fatalf("Claim() = %v, %v; want one job", claimed, err) + } + if !started { + return claimed[0] + } + job, ok, err := instance.store.Start(ctx, claimed[0], harness.clock.Now(), jobTestLease) + if err != nil || !ok { + t.Fatalf("Start() = %t, %v; want started", ok, err) + } + return job +} + +type jobRow struct { + id int64 + status string + attempts int + dueAt time.Time + availableAt time.Time + errorClass *string + leaseOwner *uuid.UUID +} + +func (harness *jobHarness) job(ctx context.Context, t *testing.T, key string) jobRow { + t.Helper() + var row jobRow + err := harness.pool.QueryRow(ctx, ` + SELECT id, status, attempts, due_at, available_at, last_error_class, lease_owner + FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`, jobTestKind, key). + Scan(&row.id, &row.status, &row.attempts, &row.dueAt, &row.availableAt, &row.errorClass, &row.leaseOwner) + if err != nil { + t.Fatalf("read job %s: %v", key, err) + } + return row +} + +// effectKeys returns the job keys of the committed effects in commit order. +func (harness *jobHarness) effectKeys(ctx context.Context, t *testing.T) []string { + t.Helper() + rows, err := harness.pool.Query(ctx, "SELECT job_key FROM "+jobEffects.Sanitize()+" ORDER BY seq") + if err != nil { + t.Fatalf("read effects: %v", err) + } + keys, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("scan effects: %v", err) + } + return keys +} + +func runDueJobs(ctx context.Context, t *testing.T, instance *jobInstance) jobrunner.PassResult { + t.Helper() + result, err := instance.worker.RunDue(ctx) + if err != nil { + t.Fatalf("RunDue() error = %v", err) + } + return result +} + +// runWorker runs the worker loop until the returned stop is called, which +// waits for Run to return. +func runWorker(ctx context.Context, t *testing.T, instance *jobInstance) (stop func()) { + t.Helper() + ctx, cancel := context.WithCancel(ctx) + stopped := make(chan struct{}) + go func() { + defer close(stopped) + instance.worker.Run(ctx) + }() + var once sync.Once + stop = func() { + once.Do(func() { + cancel() + select { + case <-stopped: + case <-time.After(consumerStopTimeout): + t.Fatal("the job worker did not stop") + } + }) + } + t.Cleanup(stop) + return stop +} + +func TestScheduledJobs(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), jobTestTimeout) + defer cancel() + pool := env.newPool(ctx, t) + if _, err := pool.Exec(ctx, createJobEffectsTable); err != nil { + t.Fatalf("create test-only tables: %v", err) + } + // Subtests share the tables and run sequentially; each starts empty + // with a fresh clock. + reset := func(t *testing.T) *jobHarness { + t.Helper() + truncateTables(ctx, t, pool, jobEffects, pgx.Identifier{"scheduled_jobs"}) + return &jobHarness{env: env, pool: pool, clock: testutil.NewFakeClock(jobTestStart)} + } + + t.Run("jobs on different dates survive restarts and each runs once in due order", func(t *testing.T) { + harness := reset(t) + inThreeDays, tomorrow := jobTestStart.AddDate(0, 0, 3), jobTestStart.AddDate(0, 0, 1) + if !harness.schedule(ctx, t, "later", inThreeDays, 0) || !harness.schedule(ctx, t, "sooner", tomorrow, 0) { + t.Fatal("Schedule() did not create the jobs") + } + // A repeated schedule keeps the first due time. + if harness.schedule(ctx, t, "sooner", jobTestStart, 0) { + t.Fatal("a repeated Schedule() created a second job") + } + + first := harness.start(ctx, t, &jobEffectHandler{worker: "first"}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, first); result.Claimed != 0 { + t.Fatalf("a job ran before it was due: %+v", result) + } + // Restart: the first process is gone with its pool; a new one + // finds the jobs in the database. + first.pool.Close() + second := harness.start(ctx, t, &jobEffectHandler{worker: "second"}, jobTestSettings(jobTestGrace)) + harness.clock.Advance(24 * time.Hour) + if result := runDueJobs(ctx, t, second); result.Done != 1 { + t.Fatalf("pass after one day = %+v, want one done job", result) + } + if result := runDueJobs(ctx, t, second); result.Claimed != 0 { + t.Fatalf("a done job ran again: %+v", result) + } + + second.pool.Close() + third := harness.start(ctx, t, &jobEffectHandler{worker: "third"}, jobTestSettings(jobTestGrace)) + harness.clock.Advance(48*time.Hour - time.Microsecond) + if result := runDueJobs(ctx, t, third); result.Claimed != 0 { + t.Fatalf("the later job ran a microsecond early: %+v", result) + } + harness.clock.Advance(time.Microsecond) + if result := runDueJobs(ctx, t, third); result.Done != 1 { + t.Fatalf("pass after three days = %+v, want one done job", result) + } + harness.clock.Advance(30 * 24 * time.Hour) + if result := runDueJobs(ctx, t, third); result.Claimed != 0 { + t.Fatalf("a done job ran again a month later: %+v", result) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "sooner" || keys[1] != "later" { + t.Fatalf("effects = %v, want sooner then later, once each", keys) + } + for _, key := range []string{"sooner", "later"} { + if row := harness.job(ctx, t, key); row.status != "done" || row.attempts != 1 || row.leaseOwner != nil { + t.Fatalf("job %s = %+v, want done after one attempt", key, row) + } + } + if !harness.job(ctx, t, "sooner").dueAt.Equal(tomorrow) { + t.Fatal("the repeated Schedule() moved the due time") + } + }) + + t.Run("two concurrent workers produce exactly one effect per job", func(t *testing.T) { + harness := reset(t) + for index := range jobTestConcurrentJobs { + harness.schedule(ctx, t, "job-"+strconv.Itoa(index), jobTestStart.Add(-time.Duration(index)*time.Second), 0) + } + slow := func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error { + // Keeps the two workers' transactions overlapping. + select { + case <-time.After(5 * time.Millisecond): + return nil + case <-ctx.Done(): + return ctx.Err() + } + } + left := harness.start(ctx, t, &jobEffectHandler{worker: "left", hook: slow}, jobTestSettings(jobTestGrace)) + right := harness.start(ctx, t, &jobEffectHandler{worker: "right", hook: slow}, jobTestSettings(jobTestGrace)) + stopLeft, stopRight := runWorker(ctx, t, left), runWorker(ctx, t, right) + waitFor(ctx, t, "every job to be done", func() bool { + var done int + err := pool.QueryRow(ctx, "SELECT count(*) FROM scheduled_jobs WHERE status = 'done'").Scan(&done) + return err == nil && done == jobTestConcurrentJobs + }) + stopLeft() + stopRight() + + var total, distinct int + var workers []string + err := pool.QueryRow(ctx, "SELECT count(*), count(DISTINCT job_id), array_agg(DISTINCT worker) FROM "+jobEffects.Sanitize()). + Scan(&total, &distinct, &workers) + if err != nil { + t.Fatalf("count effects: %v", err) + } + if total != jobTestConcurrentJobs || distinct != jobTestConcurrentJobs { + t.Fatalf("%d effects for %d distinct jobs, want exactly one for each of %d jobs", total, distinct, jobTestConcurrentJobs) + } + t.Logf("effects were written by workers %v", workers) + }) + + t.Run("a handler that outlives its lease keeps the job locked and another worker skips it", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "slow", jobTestStart, 0) + inEffect, release := make(chan struct{}), make(chan struct{}) + holder := harness.start(ctx, t, &jobEffectHandler{worker: "holder", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error { + close(inEffect) + return awaitOrCancel(ctx, release, nil) + }}, jobTestSettings(jobTestGrace)) + other := harness.start(ctx, t, &jobEffectHandler{worker: "other"}, jobTestSettings(jobTestGrace)) + + finished := make(chan jobrunner.PassResult, 1) + go func() { + result, _ := holder.worker.RunDue(ctx) + finished <- result + }() + awaitSignal(ctx, t, inEffect, "the first handler to start") + // By the clock the lease expired, but the row is locked by the + // running handler, so the claim skips it instead of running the + // job a second time. + harness.clock.Advance(2 * jobTestLease) + if result := runDueJobs(ctx, t, other); result.Claimed != 0 { + t.Fatalf("another worker claimed a job whose handler is running: %+v", result) + } + close(release) + if result := <-finished; result.Done != 1 { + t.Fatalf("holder pass = %+v, want one done job", result) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 1 { + t.Fatalf("effects = %v, want one", keys) + } + }) + + t.Run("an expired lease is reclaimed by another worker and the late completion is refused", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "abandoned", jobTestStart, 0) + stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace)) + // Worker A starts the job and stops inside it, like a process that + // froze or crashed while its handler ran. + claimed := harness.stall(ctx, t, stalled, true) + reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer"}, jobTestSettings(jobTestGrace)) + harness.clock.Advance(jobTestLease - time.Microsecond) + if result := runDueJobs(ctx, t, reclaimer); result.Claimed != 0 { + t.Fatalf("a job was reclaimed before its lease expired: %+v", result) + } + harness.clock.Advance(time.Microsecond) + if result := runDueJobs(ctx, t, reclaimer); result.Done != 1 { + t.Fatalf("pass after the lease expired = %+v, want one done job", result) + } + row := harness.job(ctx, t, "abandoned") + if row.status != "done" || row.attempts != 2 || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorLeaseExpired) { + t.Fatalf("job = %+v, want done on the second attempt after lease_expired", row) + } + + // Worker A wakes up: its start, completion, failure record, and + // release are all refused, and its handler never runs. + if _, ok, err := stalled.store.Start(ctx, claimed, harness.clock.Now(), jobTestLease); err != nil || ok { + t.Fatalf("late Start() = %t, %v; want refused", ok, err) + } + ran := false + err := stalled.store.Run(ctx, claimed, func(context.Context, outbound.UnitOfWork) error { + ran = true + return nil + }) + if !errors.Is(err, outbound.ErrJobLeaseLost) || ran { + t.Fatalf("late Run() = %v, ran %t; want ErrJobLeaseLost without running", err, ran) + } + if recorded, err := stalled.store.Fail(ctx, claimed, outbound.JobFailure{Class: outbound.JobErrorHandlerFailed, RetryAt: harness.clock.Now()}); err != nil || recorded { + t.Fatalf("late Fail() = %t, %v; want refused", recorded, err) + } + if released, err := stalled.store.Release(ctx, []outbound.ClaimedJob{claimed}); err != nil || len(released) != 0 { + t.Fatalf("late Release() = %v, %v; want refused", released, err) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 1 || harness.job(ctx, t, "abandoned").status != "done" { + t.Fatalf("effects = %v, want one and the job still done", keys) + } + }) + + t.Run("a started last attempt whose lease expired makes the job dead without running it", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "crashing", jobTestStart, 1) + stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace)) + harness.stall(ctx, t, stalled, true) + calls := 0 + reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer", hook: func(context.Context, outbound.UnitOfWork, outbound.ClaimedJob) error { + calls++ + return nil + }}, jobTestSettings(jobTestGrace)) + harness.clock.Advance(jobTestLease) + if result := runDueJobs(ctx, t, reclaimer); result.Dead != 1 || calls != 0 { + t.Fatalf("pass = %+v, handler calls %d; want a dead job without a call", result, calls) + } + row := harness.job(ctx, t, "crashing") + if row.status != "dead" || row.attempts != 1 || row.leaseOwner != nil || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorLeaseExpired) { + t.Fatalf("job = %+v, want dead after one attempt with lease_expired", row) + } + assertJobMetric(t, reclaimer.metrics, "dead", 1) + }) + + t.Run("a claim that never started is reused, so a single allowed attempt is not lost", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "unstarted", jobTestStart, 1) + stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace)) + // Worker A claims the job and stops before it started the handler. + harness.stall(ctx, t, stalled, false) + reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer"}, jobTestSettings(jobTestGrace)) + harness.clock.Advance(jobTestLease) + if result := runDueJobs(ctx, t, reclaimer); result.Done != 1 { + t.Fatalf("pass = %+v, want the job done", result) + } + if row := harness.job(ctx, t, "unstarted"); row.status != "done" || row.attempts != 1 || row.errorClass != nil { + t.Fatalf("job = %+v, want done on its first counted attempt without an error class", row) + } + }) + + t.Run("a slow job neither starves nor kills the next job of its batch", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "slow", jobTestStart.Add(-time.Minute), 0) + harness.schedule(ctx, t, "next", jobTestStart, 1) + worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(_ context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error { + if job.Key == "slow" { + // The first job runs past the lease the batch was claimed with. + harness.clock.Advance(2 * jobTestLease) + } + return nil + }}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, worker); result.Claimed != 2 || result.Done != 1 || result.Released != 1 { + t.Fatalf("first pass = %+v, want the slow job done and the next one released", result) + } + if row := harness.job(ctx, t, "next"); row.status != "pending" || row.attempts != 0 || row.leaseOwner != nil { + t.Fatalf("next job = %+v, want pending with its attempt intact", row) + } + if result := runDueJobs(ctx, t, worker); result.Done != 1 { + t.Fatalf("second pass = %+v, want the next job done", result) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "slow" || keys[1] != "next" { + t.Fatalf("effects = %v, want slow then next", keys) + } + }) + + t.Run("another worker runs a job that a busy worker claimed but did not start", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "slow", jobTestStart.Add(-time.Minute), 0) + harness.schedule(ctx, t, "waiting", jobTestStart, 1) + inSlow, finishSlow := make(chan struct{}), make(chan struct{}) + busy := harness.start(ctx, t, &jobEffectHandler{worker: "busy", hook: func(ctx context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error { + if job.Key != "slow" { + return nil + } + close(inSlow) + return awaitOrCancel(ctx, finishSlow, nil) + }}, jobTestSettings(jobTestGrace)) + other := harness.start(ctx, t, &jobEffectHandler{worker: "other"}, jobTestSettings(jobTestGrace)) + finished := make(chan jobrunner.PassResult, 1) + go func() { + result, _ := busy.worker.RunDue(ctx) + finished <- result + }() + awaitSignal(ctx, t, inSlow, "the slow job to start") + harness.clock.Advance(2 * jobTestLease) + // The slow job is locked by its handler; the waiting job's attempt + // never started, so the other worker runs it on that same attempt. + if result := runDueJobs(ctx, t, other); result.Claimed != 1 || result.Done != 1 { + t.Fatalf("other worker pass = %+v, want only the waiting job, done", result) + } + close(finishSlow) + if result := <-finished; result.Done != 1 || result.LeaseLost != 1 { + t.Fatalf("busy worker pass = %+v, want its slow job done and the waiting one lost", result) + } + if row := harness.job(ctx, t, "waiting"); row.status != "done" || row.attempts != 1 { + t.Fatalf("waiting job = %+v, want done on its single attempt", row) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 2 { + t.Fatalf("effects = %v, want one per job", keys) + } + }) + + t.Run("a job that cancels itself is finished and the queue moves on", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "self", jobTestStart.Add(-time.Minute), 0) + harness.schedule(ctx, t, "after", jobTestStart, 0) + worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error { + if job.Key != "self" { + return nil + } + // An expiry that also cancels the deadline job it stands for. + cancelled, err := unit.ScheduledJobs().Cancel(ctx, jobTestKind, job.Key) + if err == nil && !cancelled { + err = errors.New("the running job was not canceled") + } + return err + }}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, worker); result.Done != 2 { + t.Fatalf("pass = %+v, want both jobs done", result) + } + if row := harness.job(ctx, t, "self"); row.status != "cancelled" || row.leaseOwner != nil || row.attempts != 1 { + t.Fatalf("self-canceled job = %+v, want cancelled after one attempt", row) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "self" { + t.Fatalf("effects = %v, want the self-canceled job's effect committed and the next job run", keys) + } + if result := runDueJobs(ctx, t, worker); result.Claimed != 0 { + t.Fatalf("a self-canceled job was claimed again: %+v", result) + } + }) + + t.Run("a handler that changes its own job otherwise makes it dead", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "meddling", jobTestStart, 0) + worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error { + tx, ok := postgresadapter.TransactionForIntegrationTest(unit) + if !ok { + return errors.New("unit of work is not a PostgreSQL transaction") + } + _, err := tx.Exec(ctx, `UPDATE scheduled_jobs + SET status = 'done', lease_owner = NULL, lease_expires_at = NULL, started_at = NULL + WHERE id = $1`, job.ID) + return err + }}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, worker); result.Dead != 1 { + t.Fatalf("pass = %+v, want a dead job", result) + } + row := harness.job(ctx, t, "meddling") + if row.status != "dead" || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorCompletionConflict) { + t.Fatalf("job = %+v, want dead with completion_conflict", row) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 0 { + t.Fatalf("effects = %v, want the rolled back attempt to leave none", keys) + } + }) + + t.Run("graceful shutdown leaves the job not done and reclaimable", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "interrupted", jobTestStart, 0) + inEffect := make(chan struct{}) + stopping := harness.start(ctx, t, &jobEffectHandler{worker: "stopping", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error { + close(inEffect) + // Outlasts the shutdown grace. + <-ctx.Done() + return ctx.Err() + }}, jobTestSettings(jobTestShortGrace)) + stop := runWorker(ctx, t, stopping) + awaitSignal(ctx, t, inEffect, "the handler to start") + stop() + + // The effect rolled back, the job is not done, and the release + // returned it without counting the attempt. + row := harness.job(ctx, t, "interrupted") + if row.status != "pending" || row.attempts != 0 || row.leaseOwner != nil || row.errorClass != nil { + t.Fatalf("job after shutdown = %+v, want pending without an attempt", row) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 0 { + t.Fatalf("effects after shutdown = %v, want none", keys) + } + next := harness.start(ctx, t, &jobEffectHandler{worker: "next"}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, next); result.Done != 1 { + t.Fatalf("pass after the restart = %+v, want the job done without waiting for a lease", result) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 1 { + t.Fatalf("effects = %v, want one", keys) + } + }) + + t.Run("a failing job is retried after the backoff and then dead", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "failing", jobTestStart, 2) + var seenDueAt []time.Time + failing := harness.start(ctx, t, &jobEffectHandler{worker: "failing", hook: func(_ context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error { + seenDueAt = append(seenDueAt, job.DueAt) + return errJobEffectFailed + }}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, failing); result.Retried != 1 { + t.Fatalf("first attempt = %+v, want a retry", result) + } + row := harness.job(ctx, t, "failing") + // The retry moves only the claim time; the deadline stays. + wait := row.availableAt.Sub(harness.clock.Now()) + if row.status != "failed" || row.attempts != 1 || wait < jobTestBackoff/2 || wait > jobTestBackoff || + *row.errorClass != string(outbound.JobErrorHandlerFailed) || !row.dueAt.Equal(jobTestStart) { + t.Fatalf("job after the first attempt = %+v, retry in %s", row, wait) + } + if result := runDueJobs(ctx, t, failing); result.Claimed != 0 { + t.Fatal("the job was retried before its backoff passed") + } + harness.clock.Advance(jobTestBackoff) + // The per-job limit of two attempts overrides the default of three. + if result := runDueJobs(ctx, t, failing); result.Dead != 1 { + t.Fatalf("second attempt = %+v, want a dead job", result) + } + if row := harness.job(ctx, t, "failing"); row.status != "dead" || row.attempts != 2 { + t.Fatalf("job = %+v, want dead after two attempts", row) + } + // The handler saw the deadline on the retry too, not the retry time. + if len(seenDueAt) != 2 || !seenDueAt[0].Equal(jobTestStart) || !seenDueAt[1].Equal(jobTestStart) { + t.Fatalf("handler saw due times %v, want %s twice", seenDueAt, jobTestStart) + } + if keys := harness.effectKeys(ctx, t); len(keys) != 0 { + t.Fatalf("failed attempts left effects %v", keys) + } + backlog, err := failing.store.Backlog(ctx, harness.clock.Now()) + if err != nil || backlog.Dead != 1 || backlog.Due != 0 { + t.Fatalf("Backlog() = %+v, %v; want one dead job", backlog, err) + } + assertJobMetric(t, failing.metrics, "dead", 1) + assertJobMetric(t, failing.metrics, "retry", 1) + }) + + t.Run("a canceled job never runs and its key stays reserved", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "withdrawn", jobTestStart, 0) + if !harness.cancel(ctx, t, "withdrawn") { + t.Fatal("Cancel() did not cancel a pending job") + } + if harness.cancel(ctx, t, "withdrawn") || harness.schedule(ctx, t, "withdrawn", jobTestStart, 0) { + t.Fatal("a canceled job was canceled or scheduled again") + } + worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker"}, jobTestSettings(jobTestGrace)) + if result := runDueJobs(ctx, t, worker); result.Claimed != 0 { + t.Fatalf("a canceled job was claimed: %+v", result) + } + backlog, err := worker.store.Backlog(ctx, harness.clock.Now()) + if err != nil || backlog.Due != 0 { + t.Fatalf("Backlog() = %+v, %v; want nothing due", backlog, err) + } + }) + + t.Run("a cancel waits for a running handler and then finds the job done", func(t *testing.T) { + harness := reset(t) + harness.schedule(ctx, t, "racing", jobTestStart, 0) + inEffect, release := make(chan struct{}), make(chan struct{}) + worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error { + close(inEffect) + return awaitOrCancel(ctx, release, nil) + }}, jobTestSettings(jobTestGrace)) + finished := make(chan jobrunner.PassResult, 1) + go func() { + result, _ := worker.worker.RunDue(ctx) + finished <- result + }() + awaitSignal(ctx, t, inEffect, "the handler to start") + + cancelPool := env.newPoolWithApplicationName(ctx, t, jobCancelApplication) + type cancelResult struct { + cancelled bool + err error + } + cancelled := make(chan cancelResult, 1) + go func() { + result, err := cancelJob(ctx, cancelPool, "racing") + cancelled <- cancelResult{cancelled: result, err: err} + }() + if waitEvent, waiting := waitForLockWait(ctx, pool, jobCancelApplication); !waiting { + t.Fatalf("the cancel did not wait for the running handler; last wait event %q", waitEvent) + } + close(release) + if result := <-finished; result.Done != 1 { + t.Fatalf("pass = %+v, want the job done", result) + } + if result := <-cancelled; result.err != nil || result.cancelled { + t.Fatalf("Cancel() = %t, %v; want false for a job its handler completed", result.cancelled, result.err) + } + if row := harness.job(ctx, t, "racing"); row.status != "done" { + t.Fatalf("job = %+v, want done", row) + } + }) +} + +// assertJobMetric reads lincodex_scheduled_jobs_total for the test kind and +// one outcome from the scrape output. +func assertJobMetric(t *testing.T, metrics *prometheus.Metrics, outcome string, want int) { + t.Helper() + prefix := fmt.Sprintf(`lincodex_scheduled_jobs_total{kind=%q,outcome=%q} `, jobTestKind, outcome) + response := httptest.NewRecorder() + metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil)) + for line := range strings.SplitSeq(response.Body.String(), "\n") { + if value, found := strings.CutPrefix(line, prefix); found { + if value != strconv.Itoa(want) { + t.Fatalf("%s%s, want %d", prefix, value, want) + } + return + } + } + t.Fatalf("metrics output has no series %s", prefix) +} diff --git a/backend/integration_test/semantic_matching_http_test.go b/backend/integration_test/semantic_matching_http_test.go new file mode 100644 index 0000000..5edf5a3 --- /dev/null +++ b/backend/integration_test/semantic_matching_http_test.go @@ -0,0 +1,566 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "math" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + mladapter "lincodex/backend/internal/adapter/secondary/ml" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" + "lincodex/backend/internal/usecase/semantic" + "lincodex/backend/internal/worker/jobrunner" + "lincodex/backend/internal/worker/retry" +) + +const ( + semanticHTTPTimeout = 10 * time.Minute + semanticCheckInterval = 10 * time.Minute + // semanticRepository is the address a project links; its owner must + // never reach an organization. + semanticRepository = "https://github.com/Private-Owner-Marker/payments-ledger" + semanticRepositoryOwner = "Private-Owner-Marker" + // semanticMLToken is the bearer token the fake ML service expects. + semanticMLToken = "integration-ml-service-token-0123456789" +) + +// fakeMLService answers the ML embedding contract with a bag-of-topics +// encoder: each topic word lights one dimension, so texts about the same +// topic are close and others are not. Like the real service it requires the +// bearer token and serves the two ensemble models, reports the requested +// model, so the vectors pass the model check, and counts the texts it +// encoded per model. +type fakeMLService struct { + mutex sync.Mutex + texts int + byModel map[string]int + down bool +} + +var fakeMLModels = map[string]map[string]any{ + domain.GigaEmbeddingsModelID: { + "id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision, + "prompt_version": domain.GigaEmbeddingsPromptVersion, + }, + domain.Qwen3EmbeddingModelID: { + "id": domain.Qwen3EmbeddingModelID, "revision": domain.Qwen3EmbeddingModelRevision, + "prompt_version": domain.Qwen3EmbeddingPromptVersion, + }, +} + +var fakeTopics = [][]string{ + {"payment", "idempot", "webhook", "callback", "ledger"}, + {"kafka", "stream", "event"}, + {"react", "frontend", "css"}, + {"kubernetes", "terraform", "infra"}, +} + +func fakeTopicVector(text string) []float32 { + lower := strings.ToLower(text) + vector := make([]float32, len(fakeTopics)+1) + vector[len(fakeTopics)] = 0.2 + for index, words := range fakeTopics { + for _, word := range words { + if strings.Contains(lower, word) { + vector[index]++ + } + } + } + var norm float64 + for _, value := range vector { + norm += float64(value) * float64(value) + } + for index := range vector { + vector[index] = float32(float64(vector[index]) / math.Sqrt(norm)) + } + return vector +} + +func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *http.Request) { + service.mutex.Lock() + down := service.down + service.mutex.Unlock() + if request.Header.Get("Authorization") != "Bearer "+semanticMLToken { + writer.Header().Set("Content-Type", "application/problem+json") + writer.WriteHeader(http.StatusUnauthorized) + _, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:unauthenticated","title":"Authentication required","status":401,"code":"unauthenticated"}`)) + return + } + if down { + writer.Header().Set("Content-Type", "application/problem+json") + writer.WriteHeader(http.StatusServiceUnavailable) + _, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"Service unavailable","status":503,"code":"service_unavailable"}`)) + return + } + var body struct { + Model string `json:"model"` + Kind string `json:"kind"` + Texts []string `json:"texts"` + } + // A model the service does not serve is refused as the real service + // refuses it. + if request.URL.Path != "/v1/embeddings" || json.NewDecoder(request.Body).Decode(&body) != nil || + fakeMLModels[body.Model] == nil { + writer.WriteHeader(http.StatusBadRequest) + return + } + service.mutex.Lock() + service.texts += len(body.Texts) + if service.byModel == nil { + service.byModel = map[string]int{} + } + service.byModel[body.Model] += len(body.Texts) + service.mutex.Unlock() + vectors := make([][]float32, 0, len(body.Texts)) + for _, text := range body.Texts { + vectors = append(vectors, fakeTopicVector(text)) + } + writer.Header().Set("Content-Type", "application/json") + model := map[string]any{"dimension": len(fakeTopics) + 1, "max_tokens": 1024} + for key, value := range fakeMLModels[body.Model] { + model[key] = value + } + _ = json.NewEncoder(writer).Encode(map[string]any{"model": model, "kind": body.Kind, "vectors": vectors}) +} + +func (service *fakeMLService) encodedTextsOf(model string) int { + service.mutex.Lock() + defer service.mutex.Unlock() + return service.byModel[model] +} + +func (service *fakeMLService) encodedTexts() int { + service.mutex.Lock() + defer service.mutex.Unlock() + return service.texts +} + +func (service *fakeMLService) setDown(down bool) { + service.mutex.Lock() + defer service.mutex.Unlock() + service.down = down +} + +// fakeRepositoryFetcher stands in for the public GitHub API; tests never +// call GitHub. +type fakeRepositoryFetcher struct { + mutex sync.Mutex + calls int +} + +func (fetcher *fakeRepositoryFetcher) Fetch(_ context.Context, repository domain.GitHubRepository, _ outbound.RepositoryCheck) (outbound.RepositoryFetch, error) { + fetcher.mutex.Lock() + defer fetcher.mutex.Unlock() + fetcher.calls++ + if repository.Owner() != semanticRepositoryOwner { + return outbound.RepositoryFetch{Found: false}, nil + } + return outbound.RepositoryFetch{ + Found: true, GitHubID: 42, RepositoryETag: `"etag-1"`, + Evidence: domain.RepositoryEvidence{ + Description: "Ledger with idempotent payment webhooks", Topics: []string{"payments"}, + Languages: []string{"Go"}, ReadmeExcerpt: "Deduplicates acquirer callbacks by operation key.", + }, + }, nil +} + +type semanticEntryBody struct { + matchEntryBody + SemanticEvidence []struct { + RequirementKind string `json:"requirement_kind"` + RequirementText string `json:"requirement_text"` + ItemKind string `json:"item_kind"` + ProjectTitle *string `json:"project_title"` + RepositoryVerified bool `json:"repository_verified"` + Similarity string `json:"similarity"` + } `json:"semantic_evidence"` +} + +type semanticSearchBody struct { + Groups struct { + Unconfirmed []semanticEntryBody `json:"unconfirmed"` + } `json:"groups"` +} + +func TestSemanticMatchingOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), semanticHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + trigger := semantic.NewTrigger(true, true) + harness := newMatchSearchHarnessWithSemantic(ctx, t, &isolatedEnv, trigger) + client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} + transactor := postgresadapter.NewTransactor(harness.pool) + + product := domain.DemoProductPolicyV5() + product.Matching.MaxResultsPerGroup = 100 + // The questionnaire of a candidate needs the assessment bank; the bank + // seed publishes the semantic policy V5 with it. + seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, product, true) + + ml := &fakeMLService{} + mlServer := httptest.NewServer(ml) + defer mlServer.Close() + embedder, err := mladapter.NewEmbedder(mladapter.Settings{ + BaseURL: mlServer.URL, Token: semanticMLToken, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second, + }, time.Now) + if err != nil { + t.Fatalf("NewEmbedder() error = %v", err) + } + vectorJobs, err := semantic.NewVectorJobs(embedder, time.Now, nil) + if err != nil { + t.Fatalf("NewVectorJobs() error = %v", err) + } + fetcher := &fakeRepositoryFetcher{} + repositoryJob, err := semantic.NewRepositoryCheckJob(fetcher, trigger, time.Now, nil) + if err != nil { + t.Fatalf("NewRepositoryCheckJob() error = %v", err) + } + jobPool := isolatedEnv.newPool(ctx, t) + worker, err := jobrunner.New( + []inbound.JobHandler{vectorJobs.CandidateHandler(), vectorJobs.NeedHandler(), repositoryJob}, + postgresadapter.NewScheduledJobStore(jobPool, time.Minute), prometheus.New(), slog.New(slog.DiscardHandler), + jobrunner.Settings{ + BatchSize: 50, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3, + Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, + ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second, + }, func() time.Time { return time.Now().Add(time.Hour) }) + if err != nil { + t.Fatalf("jobrunner.New() error = %v", err) + } + // drain runs passes until no job is due; follow-up jobs that a job + // schedules run in the next pass. + drain := func() { + t.Helper() + for range 10 { + result, err := worker.RunDue(ctx) + if err != nil { + t.Fatalf("RunDue() error = %v", err) + } + if result.Claimed == 0 { + return + } + } + t.Fatal("jobs kept falling due") + } + countRows := func(query string, args ...any) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count rows: %v", err) + } + return count + } + + mustCall := func(who categoryHTTPCandidate, method, path, body string, want int) []byte { + t.Helper() + status, response := client.call(t, who, method, path, body, "") + if status != want { + t.Fatalf("%s %s = %d %s, want %d", method, path, status, response, want) + } + return response + } + profileBody := func(version int, projects string) string { + return fmt.Sprintf(`{"expected_version":%d,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null}, + "stack":[{"tag":"go","status":"confirmed"}],"roles":[{"specialization":"backend","self_assessed_grade":"junior","status":"confirmed"}], + "experience":[],"confirmed_parallel_periods":[],"soft_skills":[],"projects":%s, + "terms":{"location":null,"relocation":null,"salary_minimum":null}}`, version, projects) + } + publishFields := func(who categoryHTTPCandidate, version int, fields string) { + t.Helper() + mustCall(who, http.MethodPut, "/api/v1/me/privacy/publication", + fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":%s}`, version, fields), http.StatusOK) + } + + payments := `[{"title":"Payment webhook deduplication","description":"Idempotent callback receiver","stack":["Go","PostgreSQL"],"repository_url":"` + semanticRepository + `/","status":"confirmed"}]` + frontendProject := `[{"title":"Landing page","description":"React and CSS components","stack":["React"],"repository_url":null,"status":"confirmed"}]` + candidates := make([]categoryHTTPCandidate, 0, 6) + for index := range 6 { + member := client.candidate(t, fmt.Sprintf("semantic-%d@example.test", index)) + projects := frontendProject + if index == 0 { + projects = payments + } + mustCall(member, http.MethodPut, "/api/v1/me/profile", profileBody(0, projects), http.StatusOK) + mustCall(member, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK) + publishFields(member, 0, `["projects","self_assessment","stack"]`) + candidates = append(candidates, member) + } + paymentsCandidate := candidates[0] + + t.Run("a profile save schedules jobs whose keys and payloads name no repository", func(t *testing.T) { + if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1`, semantic.CandidateJobKind); got < 6 { + t.Fatalf("candidate jobs = %d, want one per save and publication", got) + } + if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1`, semantic.RepositoryCheckJobKind); got != 1 { + t.Fatalf("repository jobs = %d, want 1", got) + } + if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE dedup_key ILIKE '%owner-marker%' OR payload::text ILIKE '%owner-marker%'`); got != 0 { + t.Fatalf("%d jobs name the repository owner", got) + } + profile := mustCall(paymentsCandidate, http.MethodGet, "/api/v1/me/profile", "", http.StatusOK) + if !strings.Contains(string(profile), `"repository_url":"`+semanticRepository+`"`) || !strings.Contains(string(profile), `"state":"pending"`) { + t.Fatalf("profile = %s, want the canonical address and a pending check", profile) + } + }) + + t.Run("the jobs verify the repository and store the card vectors", func(t *testing.T) { + drain() + if fetcher.calls != 1 { + t.Fatalf("repository fetches = %d, want 1", fetcher.calls) + } + profile := mustCall(paymentsCandidate, http.MethodGet, "/api/v1/me/profile", "", http.StatusOK) + if !strings.Contains(string(profile), `"state":"verified"`) { + t.Fatalf("profile = %s, want a verified check", profile) + } + if got := countRows(`SELECT count(DISTINCT candidate_id) FROM semantic_vectors WHERE subject_kind = 'candidate' AND item_key = 'whole'`); got != 6 { + t.Fatalf("candidates with a whole vector = %d, want 6", got) + } + if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE candidate_id = $1`, paymentsCandidate.id); got != 4 { + t.Fatalf("vectors of the payments candidate = %d, want whole, roles, stack, and one project", got) + } + }) + + employer := client.employer(t, "semantic-employer@example.test") + organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: time.Now().UTC()}, transactor: transactor, now: time.Now().UTC()} + org := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Semantic organization"), time.Now().UTC()) + harness.clock.Set(time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond)) + status, created := client.call(t, employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", org.ID()), + `{"title":"Payments backend","specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Kafka","status":"confirmed"}],"tasks":[{"text":"Make payment callbacks idempotent","status":"confirmed"}]}`, + "semantic-need-1") + var need struct { + ID uuid.UUID `json:"id"` + RequirementsVersion int64 `json:"requirements_version"` + } + if status != http.StatusCreated || json.Unmarshal(created, &need) != nil { + t.Fatalf("create need = %d %s", status, created) + } + searchBody := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d}`, need.ID, need.RequirementsVersion) + search := func() (semanticSearchBody, []byte) { + t.Helper() + response := mustCall(employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/matches", org.ID()), searchBody, http.StatusOK) + var decoded semanticSearchBody + if err := json.Unmarshal(response, &decoded); err != nil { + t.Fatalf("decode search: %v", err) + } + return decoded, response + } + paymentsHandle, err := harness.key.ForOrganization(org.ID(), paymentsCandidate.id) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + + t.Run("before the need vectors exist every entry keeps the neutral Sem and the ML flag", func(t *testing.T) { + result, _ := search() + if len(result.Groups.Unconfirmed) != 6 { + t.Fatalf("unconfirmed entries = %d, want 6", len(result.Groups.Unconfirmed)) + } + for _, entry := range result.Groups.Unconfirmed { + if !slices.Contains(entry.flags(), "semantics:ml_unavailable") || len(entry.SemanticEvidence) != 0 { + t.Fatalf("entry flags %v evidence %v, want the ML flag and no evidence", entry.flags(), entry.SemanticEvidence) + } + } + }) + + t.Run("with vectors the related project ranks first and explains the match without the repository", func(t *testing.T) { + drain() + first, raw := search() + second, rawAgain := search() + if string(raw) != string(rawAgain) || len(first.Groups.Unconfirmed) != len(second.Groups.Unconfirmed) { + t.Fatal("two searches over the same vectors differ") + } + top := first.Groups.Unconfirmed[0] + if top.CandidateHandle != paymentsHandle { + t.Fatalf("first entry = %s, want the payments candidate", top.CandidateHandle) + } + if slices.Contains(top.flags(), "semantics:ml_unavailable") { + t.Fatalf("flags = %v, want Sem known", top.flags()) + } + if top.component("fit") <= first.Groups.Unconfirmed[1].component("fit") { + t.Fatalf("fit %v is not above the next entry %v", top.component("fit"), first.Groups.Unconfirmed[1].component("fit")) + } + var project bool + for _, item := range top.SemanticEvidence { + if item.ItemKind == "project" && item.ProjectTitle != nil && *item.ProjectTitle == "Payment webhook deduplication" && item.RepositoryVerified && + item.RequirementKind == "task" && item.RequirementText == "Make payment callbacks idempotent" { + project = true + } + } + if !project { + t.Fatalf("evidence = %+v, want the task matched to the verified project", top.SemanticEvidence) + } + for _, forbidden := range []string{"github.com", semanticRepositoryOwner, "owner-marker", "payments-ledger", "acquirer"} { + if strings.Contains(strings.ToLower(string(raw)), strings.ToLower(forbidden)) { + t.Fatalf("the search result contains %q", forbidden) + } + } + var fields []string + if err := harness.pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events + WHERE candidate_id = $1 AND organization_id = $2 ORDER BY occurred_at DESC, id DESC LIMIT 1`, + paymentsCandidate.id, org.ID()).Scan(&fields); err != nil { + t.Fatalf("read access history: %v", err) + } + if !slices.Contains(fields, "projects") { + t.Fatalf("access history fields = %v, want projects", fields) + } + }) + + t.Run("the card shows the published project but never the repository address", func(t *testing.T) { + card := mustCall(employer, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", org.ID(), paymentsHandle), "", http.StatusOK) + if !strings.Contains(string(card), `"title":"Payment webhook deduplication"`) || !strings.Contains(string(card), `"repository_verified":true`) { + t.Fatalf("card = %s, want the published project", card) + } + if strings.Contains(string(card), "github.com") || strings.Contains(string(card), semanticRepositoryOwner) { + t.Fatalf("card = %s, leaks the repository", card) + } + }) + + t.Run("an unchanged card costs no ML call and a repeated backfill schedules nothing twice", func(t *testing.T) { + backfill, err := semantic.NewBackfill(transactor, time.Now) + if err != nil { + t.Fatalf("NewBackfill() error = %v", err) + } + for range 2 { + if err := backfill.Run(ctx, semantic.BackfillCandidates, "it-1", uuid.Nil, nil); err != nil { + t.Fatalf("Backfill.Run() error = %v", err) + } + if err := backfill.Run(ctx, semantic.BackfillNeeds, "it-1", uuid.Nil, nil); err != nil { + t.Fatalf("Backfill.Run(needs) error = %v", err) + } + } + if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE dedup_key LIKE '%:backfill-it-1'`); got != 6+1 { + t.Fatalf("backfill jobs = %d, want one per published candidate and need", got) + } + before := ml.encodedTexts() + drain() + if after := ml.encodedTexts(); after != before { + t.Fatalf("the backfill encoded %d texts, want none for unchanged cards", after-before) + } + }) + + t.Run("unpublishing projects removes them from the vectors and the explanation", func(t *testing.T) { + publishFields(paymentsCandidate, 1, `["self_assessment","stack"]`) + drain() + if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE candidate_id = $1 AND item_key LIKE 'project:%'`, paymentsCandidate.id); got != 0 { + t.Fatalf("project vectors = %d, want 0 after unpublishing", got) + } + result, _ := search() + for _, entry := range result.Groups.Unconfirmed { + for _, item := range entry.SemanticEvidence { + if item.ProjectTitle != nil && entry.CandidateHandle == paymentsHandle { + t.Fatalf("evidence still names a project: %+v", item) + } + } + } + }) + + t.Run("an ML outage keeps the job pending and the search answering", func(t *testing.T) { + ml.setDown(true) + defer ml.setDown(false) + mustCall(candidates[1], http.MethodPut, "/api/v1/me/profile", profileBody(1, `[{"title":"Kafka event pipeline","description":null,"stack":["Kafka"],"repository_url":null,"status":"confirmed"}]`), http.StatusOK) + if _, err := worker.RunDue(ctx); err != nil { + t.Fatalf("RunDue() error = %v", err) + } + if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1 AND status = 'failed'`, semantic.CandidateJobKind); got == 0 { + t.Fatal("the vector job did not record a failed attempt while ML was down") + } + search() + }) + + t.Run("the refresh of repository checks is limited per candidate", func(t *testing.T) { + harness.clock.Set(time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond)) + for _, member := range []categoryHTTPCandidate{candidates[2]} { + mustCall(member, http.MethodPut, "/api/v1/me/profile", profileBody(1, `[{"title":"Infra","description":null,"stack":[],"repository_url":"https://github.com/someone/infra","status":"confirmed"}]`), http.StatusOK) + status, body := client.call(t, member, http.MethodPost, "/api/v1/me/profile/repository-checks", "", "") + if status != http.StatusTooManyRequests { + t.Fatalf("refresh right after the save = %d %s, want 429", status, body) + } + harness.clock.Set(time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond)) + status, body = client.call(t, member, http.MethodPost, "/api/v1/me/profile/repository-checks", "", "") + if status != http.StatusAccepted || !strings.Contains(string(body), `"scheduled":1`) { + t.Fatalf("refresh after the interval = %d %s, want 202 with one check", status, body) + } + } + status, body := client.call(t, candidates[3], http.MethodPost, "/api/v1/me/profile/repository-checks", "", "") + if status != http.StatusAccepted || !strings.Contains(string(body), `"scheduled":0`) { + t.Fatalf("refresh without repositories = %d %s, want 202 with nothing", status, body) + } + }) + + t.Run("the ensemble policy and a backfill add the Qwen3 views and the search fuses both models", func(t *testing.T) { + // The payments candidate publishes the project again, so one card is + // close to the need under both models. The publication job falls due + // on the stand clock, ahead of the worker, so a backfill under the + // single-model policy brings the Giga vectors up to date first. + publishFields(paymentsCandidate, 2, `["projects","self_assessment","stack"]`) + backfill, err := semantic.NewBackfill(transactor, time.Now) + if err != nil { + t.Fatalf("NewBackfill() error = %v", err) + } + if err := backfill.Run(ctx, semantic.BackfillCandidates, "it-republish", uuid.Nil, nil); err != nil { + t.Fatalf("Backfill.Run(republish) error = %v", err) + } + drain() + gigaBefore := ml.encodedTextsOf(domain.GigaEmbeddingsModelID) + publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now) + published, err := publisher.EnsureDemoSemanticEnsembleSection(ctx, "operator:integration") + if err != nil || !published.Created { + t.Fatalf("EnsureDemoSemanticEnsembleSection() = %+v, %v", published, err) + } + // Until the need has a Qwen3 view, Sem is unknown for every entry. + before, _ := search() + for _, entry := range before.Groups.Unconfirmed { + if !slices.Contains(entry.flags(), "semantics:ml_unavailable") { + t.Fatalf("flags = %v before the backfill, want the ML flag", entry.flags()) + } + } + for _, scope := range []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds} { + if err := backfill.Run(ctx, scope, "it-ensemble", uuid.Nil, nil); err != nil { + t.Fatalf("Backfill.Run(%s) error = %v", scope, err) + } + } + drain() + if after := ml.encodedTextsOf(domain.GigaEmbeddingsModelID); after != gigaBefore { + t.Fatalf("the backfill encoded %d Giga texts, want none: the Giga views did not change", after-gigaBefore) + } + if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE model_id = $1 AND item_key = 'whole'`, domain.Qwen3EmbeddingModelID); got != 6+1 { + t.Fatalf("Qwen3 whole views = %d, want one per published candidate and the need", got) + } + if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE model_id = $1 AND item_key <> 'whole'`, domain.Qwen3EmbeddingModelID); got != 0 { + t.Fatalf("Qwen3 item vectors = %d, want none: only Giga explains entries", got) + } + // Every candidate now has both whole views, so every entry has a + // known Sem, and the fused score puts the related card first. + result, _ := search() + entries := result.Groups.Unconfirmed + for _, entry := range entries { + if slices.Contains(entry.flags(), "semantics:ml_unavailable") { + t.Fatalf("flags = %v after the backfill, want a known Sem", entry.flags()) + } + } + if entries[0].CandidateHandle != paymentsHandle || entries[0].component("fit") <= entries[len(entries)-1].component("fit") { + t.Fatalf("first entry %s with fit %v, last fit %v: the fused Sem did not put the related card first", + entries[0].CandidateHandle, entries[0].component("fit"), entries[len(entries)-1].component("fit")) + } + }) +} diff --git a/backend/integration_test/session_http_test.go b/backend/integration_test/session_http_test.go new file mode 100644 index 0000000..258ba81 --- /dev/null +++ b/backend/integration_test/session_http_test.go @@ -0,0 +1,541 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" +) + +const ( + sessionHTTPTestTimeout = 5 * time.Minute + sessionHTTPTestOrigin = "http://localhost:8080" + sessionHTTPTestPass = "correct horse battery staple" +) + +type sessionHTTPHarness struct { + pool *pgxpool.Pool + store *postgresadapter.IdentityStore + router http.Handler + credentials *identity.Credentials + clock *testClock + logs *strings.Builder +} + +func newSessionHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + return newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) +} + +func newSessionHTTPHarnessWithSettings( + ctx context.Context, + t *testing.T, + env *testEnvironment, + settings identity.SessionSettings, +) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + service, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), + Users: store.Users(), + Sessions: store.Sessions(), + Credentials: credentials, + Limiter: env.Redis, + Keyring: keyring, + Clock: clock.Now, + }, settings) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(service), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler)) + router, err := httpadapter.NewRouter( + healthHandler, + handler, + identityHandler.SessionSecurity(), + responder, + prometheus.New(), + logger, + nil, + ) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func createSessionHTTPUser( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, + verified bool, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + now := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, + PasswordHash: passwordHash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", email, err) + } + if !verified { + return user + } + user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + return user +} + +func (harness *sessionHTTPHarness) request( + t *testing.T, + method string, + path string, + body string, + origin string, + cookie string, + csrf string, + remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if origin != "" { + request.Header.Set("Origin", origin) + } + if cookie != "" { + request.Header.Set("Cookie", "__Host-lincodex_session="+cookie) + } + if csrf != "" { + request.Header.Set("X-CSRF-Token", csrf) + } + request.RemoteAddr = remoteAddr + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return recorder +} + +func loginSessionHTTP(t *testing.T, harness *sessionHTTPHarness, email, password string, origin, cookie, remoteAddr string) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(struct { + Email string `json:"email"` + Password string `json:"password"` + }{Email: email, Password: password}) + if err != nil { + t.Fatalf("marshal login request: %v", err) + } + return harness.request(t, http.MethodPost, "/api/v1/identity/sessions", string(body), origin, cookie, "", remoteAddr) +} + +func requireSessionProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) { + t.Helper() + var body struct { + Code string `json:"code"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode problem response %d %s: %v", response.Code, response.Body.String(), err) + } + if response.Code != status || body.Code != code { + t.Fatalf("response = %d code=%q body=%s, want %d code=%q", response.Code, body.Code, response.Body.String(), status, code) + } +} + +func requireSessionCookie(t *testing.T, response *httptest.ResponseRecorder) *http.Cookie { + t.Helper() + cookies := response.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("Set-Cookie values = %v, want exactly one session cookie", response.Header().Values("Set-Cookie")) + } + cookie := cookies[0] + if cookie.Name != "__Host-lincodex_session" || cookie.Value == "" || cookie.Path != "/" || cookie.Domain != "" || + !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge <= 0 || cookie.Expires.IsZero() { + t.Fatalf("session cookie attributes = %+v", cookie) + } + return cookie +} + +func requireExpiredSessionCookie(t *testing.T, response *httptest.ResponseRecorder) { + t.Helper() + cookies := response.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("Set-Cookie values = %v, want one cleared session cookie", response.Header().Values("Set-Cookie")) + } + cookie := cookies[0] + if cookie.Name != "__Host-lincodex_session" || cookie.Value != "" || cookie.Path != "/" || cookie.Domain != "" || + !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge >= 0 { + t.Fatalf("cleared session cookie attributes = %+v", cookie) + } +} + +func TestIdentitySessionsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout) + defer cancel() + harness := newSessionHTTPHarness(ctx, t, env) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + verifiedEmail := "verified@example.test" + unverifiedEmail := "unverified@example.test" + verifiedUser := createSessionHTTPUser(ctx, t, harness, verifiedEmail, passwordHash, true) + createSessionHTTPUser(ctx, t, harness, unverifiedEmail, passwordHash, false) + + unknown := loginSessionHTTP(t, harness, "unknown@example.test", sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.1:1234") + wrongPassword := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, "", "192.0.2.2:1234") + requireSessionProblem(t, unknown, http.StatusUnauthorized, "invalid_credentials") + requireSessionProblem(t, wrongPassword, http.StatusUnauthorized, "invalid_credentials") + if unknown.Header().Get("Content-Type") != wrongPassword.Header().Get("Content-Type") || + !strings.Contains(unknown.Header().Get("Content-Type"), "application/problem+json") { + t.Fatalf("unknown and wrong-password response media types differ: %q and %q", unknown.Header().Get("Content-Type"), wrongPassword.Header().Get("Content-Type")) + } + if len(unknown.Header().Values("Set-Cookie")) != 0 || len(wrongPassword.Header().Values("Set-Cookie")) != 0 { + t.Fatal("a rejected login set a session cookie") + } + unverified := loginSessionHTTP(t, harness, unverifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.3:1234") + requireSessionProblem(t, unverified, http.StatusForbidden, "email_not_verified") + if len(unverified.Header().Values("Set-Cookie")) != 0 { + t.Fatal("unverified login set a session cookie") + } + + badOriginBody, err := json.Marshal(struct { + Email string `json:"email"` + Password string `json:"password"` + }{Email: verifiedEmail, Password: sessionHTTPTestPass}) + if err != nil { + t.Fatalf("marshal bad-origin login request: %v", err) + } + badOriginRequest := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", strings.NewReader(string(badOriginBody))) + badOriginRequest.Header.Set("Content-Type", "application/json") + badOriginRequest.Header.Set("Origin", "http://attacker.example") + badOriginRequest.Header.Set("X-Forwarded-Host", "localhost:8080") + badOriginRequest.RemoteAddr = "192.0.2.4:1234" + badOrigin := httptest.NewRecorder() + harness.router.ServeHTTP(badOrigin, badOriginRequest) + requireSessionProblem(t, badOrigin, http.StatusForbidden, "csrf_check_failed") + if len(badOrigin.Header().Values("Set-Cookie")) != 0 { + t.Fatal("a login with a disallowed Origin set a session cookie") + } + + limitedEmail := "limit@example.test" + for attempt := 1; attempt <= 10; attempt++ { + response := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", fmt.Sprintf("198.51.100.%d:1234", attempt)) + requireSessionProblem(t, response, http.StatusUnauthorized, "invalid_credentials") + } + limited := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "198.51.100.11:1234") + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("email login limit response has no Retry-After") + } + + malformedCookieLogin := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "not-a-session-token", "192.0.2.5:1234") + if malformedCookieLogin.Code != http.StatusCreated { + t.Fatalf("login with a malformed incoming cookie status = %d, body=%s", malformedCookieLogin.Code, malformedCookieLogin.Body.String()) + } + firstCookie := requireSessionCookie(t, malformedCookieLogin) + if malformedCookieLogin.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("login Cache-Control = %q, want no-store", malformedCookieLogin.Header().Get("Cache-Control")) + } + var firstBody struct { + Account struct { + ID string `json:"id"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + } `json:"account"` + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(malformedCookieLogin.Body.Bytes(), &firstBody); err != nil { + t.Fatalf("decode login response: %v", err) + } + if firstBody.Account.ID != verifiedUser.ID.String() || firstBody.Account.Email != verifiedEmail || !firstBody.Account.EmailVerified || firstBody.CSRFToken == "" { + t.Fatalf("login account or CSRF token = %+v", firstBody) + } + + currentSession := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.6:1234") + if currentSession.Code != http.StatusOK || currentSession.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("current session response = %d %s, Cache-Control=%q", currentSession.Code, currentSession.Body.String(), currentSession.Header().Get("Cache-Control")) + } + var sessionBody struct { + Account struct { + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + } `json:"account"` + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(currentSession.Body.Bytes(), &sessionBody); err != nil { + t.Fatalf("decode current session response: %v", err) + } + if sessionBody.Account.Email != verifiedEmail || !sessionBody.Account.EmailVerified || sessionBody.CSRFToken != firstBody.CSRFToken { + t.Fatalf("current session response = %+v, want the authenticated account and CSRF token", sessionBody) + } + var userVersionBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionBefore); err != nil { + t.Fatalf("read current account version before protected reads: %v", err) + } + var outboxBefore, idempotencyBefore int64 + if err := harness.pool.QueryRow(ctx, + `SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`, + ).Scan(&outboxBefore, &idempotencyBefore); err != nil { + t.Fatalf("read business side-effect counts before protected reads: %v", err) + } + currentAccount := harness.request(t, http.MethodGet, "/api/v1/identity/me", "", "", firstCookie.Value, "", "192.0.2.7:1234") + if currentAccount.Code != http.StatusOK || currentAccount.Header().Get("Cache-Control") != "no-store" || !strings.Contains(currentAccount.Body.String(), verifiedEmail) { + t.Fatalf("current account response = %d %s, Cache-Control=%q", currentAccount.Code, currentAccount.Body.String(), currentAccount.Header().Get("Cache-Control")) + } + var accountBody struct { + ID string `json:"id"` + EmailVerified bool `json:"email_verified"` + } + if err := json.Unmarshal(currentAccount.Body.Bytes(), &accountBody); err != nil { + t.Fatalf("decode current account response: %v", err) + } + if accountBody.ID != verifiedUser.ID.String() || !accountBody.EmailVerified { + t.Fatalf("current account = %+v, want verified account resolved from PostgreSQL session", accountBody) + } + guestProfile := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", "", "", "192.0.2.8:1234") + requireSessionProblem(t, guestProfile, http.StatusUnauthorized, "unauthenticated") + guestWrite := harness.request(t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`, "", "", "", "192.0.2.9:1234") + requireSessionProblem(t, guestWrite, http.StatusUnauthorized, "unauthenticated") + unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.18:1234") + requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented") + unsupportedWrite := harness.request( + t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`, + sessionHTTPTestOrigin, firstCookie.Value, firstBody.CSRFToken, "192.0.2.19:1234", + ) + requireSessionProblem(t, unsupportedWrite, http.StatusNotImplemented, "not_implemented") + var userVersionAfter int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionAfter); err != nil { + t.Fatalf("read current account version after protected reads: %v", err) + } + var outboxAfter, idempotencyAfter int64 + if err := harness.pool.QueryRow(ctx, + `SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`, + ).Scan(&outboxAfter, &idempotencyAfter); err != nil { + t.Fatalf("read business side-effect counts after protected reads: %v", err) + } + if userVersionAfter != userVersionBefore || outboxAfter != outboxBefore || idempotencyAfter != idempotencyBefore { + t.Fatalf("protected reads changed account or business side effects: user version %d -> %d, outbox %d -> %d, idempotency %d -> %d", + userVersionBefore, userVersionAfter, outboxBefore, outboxAfter, idempotencyBefore, idempotencyAfter) + } + + wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234") + requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials") + stillActive := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.10:1234") + if stillActive.Code != http.StatusOK { + t.Fatalf("failed login revoked its incoming session: status=%d body=%s", stillActive.Code, stillActive.Body.String()) + } + + rotated := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.11:1234") + if rotated.Code != http.StatusCreated { + t.Fatalf("rotating login status = %d, body=%s", rotated.Code, rotated.Body.String()) + } + secondCookie := requireSessionCookie(t, rotated) + if secondCookie.Value == firstCookie.Value { + t.Fatal("rotating login reused the session token") + } + var secondBody struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(rotated.Body.Bytes(), &secondBody); err != nil { + t.Fatalf("decode rotated login response: %v", err) + } + if secondBody.CSRFToken == "" || secondBody.CSRFToken == firstBody.CSRFToken { + t.Fatal("rotated login did not issue a new session-bound CSRF token") + } + replayed := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.12:1234") + requireSessionProblem(t, replayed, http.StatusUnauthorized, "unauthenticated") + + for _, test := range []struct { + name string + origin string + csrf string + }{ + {name: "wrong origin", origin: "http://attacker.example", csrf: secondBody.CSRFToken}, + {name: "wrong CSRF token", origin: sessionHTTPTestOrigin, csrf: firstBody.CSRFToken}, + {name: "missing CSRF token", origin: sessionHTTPTestOrigin}, + } { + t.Run(test.name, func(t *testing.T) { + response := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", test.origin, secondCookie.Value, test.csrf, "192.0.2.13:1234") + requireSessionProblem(t, response, http.StatusForbidden, "csrf_check_failed") + if len(response.Header().Values("Set-Cookie")) != 0 { + t.Fatalf("rejected logout cleared the session cookie: %v", response.Header().Values("Set-Cookie")) + } + active := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.14:1234") + if active.Code != http.StatusOK { + t.Fatalf("rejected logout revoked the session: %d %s", active.Code, active.Body.String()) + } + }) + } + + logout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.15:1234") + if logout.Code != http.StatusNoContent || logout.Body.Len() != 0 { + t.Fatalf("logout response = %d %q, want 204 with no body", logout.Code, logout.Body.String()) + } + requireExpiredSessionCookie(t, logout) + replayAfterLogout := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.16:1234") + requireSessionProblem(t, replayAfterLogout, http.StatusUnauthorized, "unauthenticated") + staleLogout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.17:1234") + requireSessionProblem(t, staleLogout, http.StatusUnauthorized, "unauthenticated") + requireExpiredSessionCookie(t, staleLogout) + + for _, secret := range []string{firstCookie.Value, secondCookie.Value, sessionHTTPTestPass, "incorrect horse battery staple"} { + if secret != "" && strings.Contains(harness.logs.String(), secret) { + t.Fatalf("a session token or password reached request logs") + } + } +} + +func TestSessionExpiryAcrossAPIRestart(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout) + defer cancel() + first := newSessionHTTPHarness(ctx, t, env) + + passwordHash, err := first.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + absoluteEmail := "absolute@example.test" + idleEmail := "idle@example.test" + createSessionHTTPUser(ctx, t, first, absoluteEmail, passwordHash, true) + createSessionHTTPUser(ctx, t, first, idleEmail, passwordHash, true) + + absoluteLogin := loginSessionHTTP(t, first, absoluteEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.20:1234") + if absoluteLogin.Code != http.StatusCreated { + t.Fatalf("absolute-expiry login status = %d, body=%s", absoluteLogin.Code, absoluteLogin.Body.String()) + } + absoluteCookie := requireSessionCookie(t, absoluteLogin) + idleLogin := loginSessionHTTP(t, first, idleEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.21:1234") + if idleLogin.Code != http.StatusCreated { + t.Fatalf("idle-expiry login status = %d, body=%s", idleLogin.Code, idleLogin.Body.String()) + } + idleCookie := requireSessionCookie(t, idleLogin) + + second := newSessionHTTPHarness(ctx, t, env) + for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} { + response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.22:1234") + if response.Code != http.StatusOK { + t.Fatalf("session did not survive an API handler restart: %d %s", response.Code, response.Body.String()) + } + } + + absoluteToken, err := domain.ParseSecretToken(absoluteCookie.Value) + if err != nil { + t.Fatalf("ParseSecretToken(absolute cookie) error = %v", err) + } + idleToken, err := domain.ParseSecretToken(idleCookie.Value) + if err != nil { + t.Fatalf("ParseSecretToken(idle cookie) error = %v", err) + } + now := second.clock.Now() + absoluteHash := absoluteToken.Hash() + idleHash := idleToken.Hash() + if _, err := second.pool.Exec(ctx, + `UPDATE sessions SET created_at = $1, last_seen_at = $1, expires_at = $2 WHERE token_hash = $3`, + now.Add(-2*time.Second), now.Add(-time.Second), absoluteHash[:], + ); err != nil { + t.Fatalf("expire absolute session: %v", err) + } + idleCreatedAt := now.Add(-env.Config.IdentitySessionIdleTimeout - 2*time.Second) + if _, err := second.pool.Exec(ctx, + `UPDATE sessions SET created_at = $1, last_seen_at = $2 WHERE token_hash = $3`, + idleCreatedAt, now.Add(-env.Config.IdentitySessionIdleTimeout-time.Second), idleHash[:], + ); err != nil { + t.Fatalf("age idle session: %v", err) + } + for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} { + response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.23:1234") + requireSessionProblem(t, response, http.StatusUnauthorized, "unauthenticated") + } +} + +func TestShortIdleSessionRefreshesWhileActive(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout) + defer cancel() + harness := newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: time.Minute, + AbsoluteLifetime: 2 * time.Minute, + }) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + user := createSessionHTTPUser(ctx, t, harness, "short-idle@example.test", passwordHash, true) + login := loginSessionHTTP(t, harness, user.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.30:1234") + if login.Code != http.StatusCreated { + t.Fatalf("login status = %d, body=%s", login.Code, login.Body.String()) + } + cookie := requireSessionCookie(t, login) + + harness.clock.Advance(40 * time.Second) + firstActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.31:1234") + if firstActivity.Code != http.StatusOK { + t.Fatalf("session expired before first activity: %d %s", firstActivity.Code, firstActivity.Body.String()) + } + harness.clock.Advance(40 * time.Second) + secondActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.32:1234") + if secondActivity.Code != http.StatusOK { + t.Fatalf("session was not refreshed by activity: %d %s", secondActivity.Code, secondActivity.Body.String()) + } +} diff --git a/backend/integration_test/skill_evidence_http_test.go b/backend/integration_test/skill_evidence_http_test.go new file mode 100644 index 0000000..4cfaccf --- /dev/null +++ b/backend/integration_test/skill_evidence_http_test.go @@ -0,0 +1,901 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + v1 "lincodex/backend/internal/adapter/primary/http/v1" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/anonymousprofile" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/candidateview" + "lincodex/backend/internal/usecase/companyquota" + "lincodex/backend/internal/usecase/evidence" +) + +const ( + skillEvidenceHTTPTimeout = 10 * time.Minute + // skillEvidenceMigrationVersion creates the skill evidence tables. + skillEvidenceMigrationVersion = 35 + // evidenceCohortSize is the smallest visible group of identical cards, so + // the cohort rules of the card leave the category in place. + evidenceCohortSize = 5 +) + +type skillEvidenceHarness struct { + *assessmentAttemptHTTPHarness + key domain.CandidateViewPseudonymKey +} + +func newSkillEvidenceHarness(ctx context.Context, t *testing.T, env *testEnvironment) *skillEvidenceHarness { + t.Helper() + var key domain.CandidateViewPseudonymKey + harness := newAssessmentAttemptHTTPHarnessWithOptions(ctx, t, env, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}, + func(parts assessmentHarnessParts) []v1.HandlerOption { + var err error + if key, err = parts.keyring.CandidateViewPseudonymKey(); err != nil { + t.Fatalf("CandidateViewPseudonymKey() error = %v", err) + } + projector := anonymousprofile.NewService(postgresadapter.NewPrivacyCohortStore(parts.pool), key, parts.clock.Now) + quota := companyquota.NewService(parts.clock.Now) + views, err := candidateview.NewService(candidateview.Dependencies{ + Transactor: parts.transactor, Projector: projector, PseudonymKey: key, Clock: parts.clock.Now, + Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) { + return quota.ReserveCardView(ctx, unit, organization, candidateID) + }, + }) + if err != nil { + t.Fatalf("candidateview.NewService() error = %v", err) + } + settings, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: parts.transactor, Clock: parts.clock.Now}) + if err != nil { + t.Fatalf("candidateprivacy.NewService() error = %v", err) + } + evidenceService, err := evidence.NewService(evidence.Dependencies{ + Transactor: parts.transactor, AuthorizeCategories: views.AuthorizeCategoriesSection, + }) + if err != nil { + t.Fatalf("evidence.NewService() error = %v", err) + } + return []v1.HandlerOption{ + v1.WithPrivacy(v1.NewPrivacyHandler(views, settings, env.Config.AppPublicURL)), + v1.WithEvidence(v1.NewEvidenceHandler(evidenceService)), + } + }) + return &skillEvidenceHarness{assessmentAttemptHTTPHarness: harness, key: key} +} + +// evidenceFactBody is the owner's fact as the contract declares it. +type evidenceFactBody struct { + ID uuid.UUID `json:"id"` + Kind string `json:"kind"` + Source struct { + Type string `json:"type"` + EventID uuid.UUID `json:"event_id"` + ResultID uuid.UUID `json:"result_id"` + } `json:"source"` + Skills []string `json:"skills"` + Result struct { + Grade string `json:"grade"` + Basis string `json:"basis"` + CalibrationStatus string `json:"calibration_status"` + } `json:"result"` + Attribution string `json:"attribution"` + Trust int `json:"trust"` + OccurredAt time.Time `json:"occurred_at"` + Visibility string `json:"visibility"` +} + +type evidencePageBody struct { + Items []evidenceFactBody `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` +} + +func TestSkillEvidenceOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), skillEvidenceHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSkillEvidenceHarness(ctx, t, &isolatedEnv) + bank := seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, domain.DemoProductPolicyV2(), true) + threshold := passPoints(int(bank.policy.Policy().Assessment.StopRule.MaxScoredItems), int(bank.policy.Policy().Assessment.Attempt.BasicPassMark)) + client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} + transactor := postgresadapter.NewTransactor(harness.pool) + + now := time.Now().UTC().Truncate(time.Microsecond) + identity := identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: now} + organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identity, transactor: transactor, now: now} + privacy := candidatePrivacyFixture{ + ctx: ctx, pool: harness.pool, queries: sqlc.New(harness.pool), identity: identity, + organizations: organizations, ledger: postgresadapter.NewConsentStore(harness.pool), now: now, + } + + get := func(who categoryHTTPCandidate, path string) *httptest.ResponseRecorder { + t.Helper() + return harness.request(t, http.MethodGet, path, "", "", who.cookie, "", client.remote()) + } + readOwn := func(who categoryHTTPCandidate, query string) (evidencePageBody, *httptest.ResponseRecorder) { + t.Helper() + response := get(who, "/api/v1/me/evidence"+query) + var page evidencePageBody + if response.Code == http.StatusOK { + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("decode own evidence: %v\n%s", err, response.Body.String()) + } + } + return page, response + } + countRows := func(query string, args ...any) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count rows: %v", err) + } + return count + } + passingIntern := func(who categoryHTTPCandidate) attemptRun { + t.Helper() + run := client.run(t, who, "backend", "intern", func(int) int { return threshold }) + if run.result["outcome"] != "confirmed" || decisionOf(t, run.result)["status"] != "assigned" { + t.Fatalf("passing run of %s = %v, want a confirmed assigned category", who.email, run.result) + } + return run + } + + // The cohort: five candidates with the same published category. A card is + // shown only inside a group of five identical cards. + cohort := make([]categoryHTTPCandidate, 0, evidenceCohortSize) + runs := make(map[uuid.UUID]attemptRun, evidenceCohortSize) + for index := range evidenceCohortSize { + member := client.candidate(t, fmt.Sprintf("evidence-cohort-%d@example.test", index)) + runs[member.id] = passingIntern(member) + cohort = append(cohort, member) + } + target := cohort[0] + targetRun := runs[target.id] + consents := make(map[uuid.UUID]uuid.UUID, len(cohort)) + for _, member := range cohort { + c2 := privacy.grant(t, member.id, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, member.id, c2.ID(), 0, domain.CardFieldCategories) + consents[member.id] = c2.ID() + } + failed := client.candidate(t, "evidence-failed@example.test") + failedRun := client.run(t, failed, "backend", "intern", func(int) int { return threshold - 1 }) + if failedRun.result["outcome"] != "not_confirmed" { + t.Fatalf("failing run = %v, want not_confirmed", failedRun.result["outcome"]) + } + employerAccount := client.employer(t, "evidence-employer@example.test") + foreignAccount := client.employer(t, "evidence-foreign@example.test") + organizationA := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization A"), now) + organizationB := organizations.create(t, domain.User{ID: employerAccount.id}, organizations.completeProfile(t, "Evidence organization B"), now) + foreignOrganization := organizations.create(t, domain.User{ID: foreignAccount.id}, organizations.completeProfile(t, "Evidence foreign organization"), now) + // The policy and the organizations take effect when they are stored, which + // is after the clock of the harness was read, and the card-view quota reads + // both at the application time. + harness.clock.Set(time.Now().UTC().Truncate(time.Microsecond)) + organizationPath := func(organizationID uuid.UUID, handle string) string { + return fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s/evidence", organizationID, handle) + } + aliasIn := func(organizationID, candidateID uuid.UUID) string { + t.Helper() + alias, err := harness.key.ForOrganization(organizationID, candidateID) + if err != nil { + t.Fatalf("ForOrganization() error = %v", err) + } + return alias + } + organizationFacts := func(organizationID, candidateID uuid.UUID, categories ...domain.CandidateViewCategory) []domain.EvidenceOrganizationFact { + t.Helper() + var facts []domain.EvidenceOrganizationFact + err := transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + facts, err = unit.Evidence().ListOrganizationFacts(ctx, organizationID, candidateID, categories) + return err + }) + if err != nil { + t.Fatalf("ListOrganizationFacts() error = %v", err) + } + return facts + } + category := func(specialization domain.SpecializationCode, grade domain.GradeCode) domain.CandidateViewCategory { + return domain.CandidateViewCategory{Specialization: specialization, Grade: grade, Strength: domain.CandidateViewStrengthStandard} + } + // A source records a fact together with its tags in one transaction, the + // only time tags can join a fact. The helper rebuilds the projection from + // the stored results and adds the tags to the fact of one event, as such a + // source would. + rebuildWithTags := func(eventID uuid.UUID, skills ...string) { + t.Helper() + tx, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin the rebuild: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil { + t.Fatalf("empty the projection: %v", err) + } + if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil { + t.Fatalf("project the stored results: %v", err) + } + for _, skill := range skills { + if _, err := tx.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code) + SELECT id, $2 FROM skill_evidence_facts WHERE event_id = $1`, eventID, skill); err != nil { + t.Fatalf("tag the event with %s: %v", skill, err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit the rebuild: %v", err) + } + } + + t.Run("a confirmed assessment gives one fact tied to its result with trust 1", func(t *testing.T) { + if domain.EvidenceTrustOnlineUnconfirmed != 1 { + t.Fatalf("the trust of an online result without identity confirmation = %d, want 1", domain.EvidenceTrustOnlineUnconfirmed) + } + page, response := readOwn(target, "") + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || len(page.Items) != 1 || + page.Page.HasMore || page.Page.NextCursor != nil { + t.Fatalf("own evidence = %d %q %s, want one no-store fact", response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + fact := page.Items[0] + decidedAt, err := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string)) + if err != nil { + t.Fatalf("parse decided_at: %v", err) + } + if fact.ID == uuid.Nil || fact.Kind != "measurement" || fact.Source.Type != "assessment_result" || + fact.Source.EventID != targetRun.id || fact.Source.ResultID != targetRun.id || + !slices.Equal(fact.Skills, []string{"backend"}) || fact.Attribution != "personal" || + fact.Trust != int(domain.EvidenceTrustOnlineUnconfirmed) || fact.Visibility != "visible" || + fact.Result.Grade != "intern" || fact.Result.Basis != "synthetic_demo" || fact.Result.CalibrationStatus != "uncalibrated" || + !fact.OccurredAt.Equal(decidedAt) { + t.Fatalf("fact = %+v, want a visible online measurement of the intern result %s decided at %s", fact, targetRun.id, decidedAt) + } + // The same result is readable by its identifier. + if status, _ := client.call(t, target, http.MethodGet, "/api/v1/me/assessment-attempts/"+fact.Source.ResultID.String()+"/result", "", ""); status != http.StatusOK { + t.Fatalf("result named by the fact = %d, want 200", status) + } + for _, leak := range []string{"answer", "score", "points", "reference", "seed", "item_", "signal", "review", "not_confirmed"} { + if strings.Contains(strings.ToLower(response.Body.String()), leak) { + t.Fatalf("own evidence exposes %q: %s", leak, response.Body.String()) + } + } + stored := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1 AND trust = 1 AND kind = 'measurement' AND result_id = $2`, target.id, targetRun.id) + if stored != 1 { + t.Fatalf("stored facts of the result = %d, want 1", stored) + } + + // Every owner reads only their own facts; a failed attempt gives none. + for _, member := range cohort[1:] { + memberPage, _ := readOwn(member, "") + if len(memberPage.Items) != 1 || memberPage.Items[0].ID == fact.ID || memberPage.Items[0].Source.ResultID != runs[member.id].id { + t.Fatalf("evidence of %s = %+v, want only their own fact", member.email, memberPage.Items) + } + } + if failedPage, response := readOwn(failed, ""); response.Code != http.StatusOK || len(failedPage.Items) != 0 || failedPage.Page.HasMore { + t.Fatalf("evidence after a failed attempt = %d %s, want no fact", response.Code, response.Body.String()) + } + if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, failed.id) != 0 { + t.Fatal("a failed attempt stored a fact") + } + + // Access: a guest, an employer, and a malformed request are refused. + if response := get(categoryHTTPCandidate{}, "/api/v1/me/evidence"); response.Code != http.StatusUnauthorized { + t.Fatalf("evidence without a session = %d, want 401", response.Code) + } + if response := get(employerAccount, "/api/v1/me/evidence"); response.Code != http.StatusForbidden { + t.Fatalf("evidence of an employer account = %d, want 403", response.Code) + } + }) + + t.Run("several tags of one event stay one independent fact", func(t *testing.T) { + rebuildWithTags(targetRun.id, "go", "postgresql") + page, response := readOwn(target, "") + if len(page.Items) != 1 || !slices.Equal(page.Items[0].Skills, []string{"backend", "go", "postgresql"}) { + t.Fatalf("evidence after two more tags = %s, want a single fact with three tags", response.Body.String()) + } + fact := page.Items[0] + if facts, events := countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id), + countRows(`SELECT count(DISTINCT event_id) FROM skill_evidence_facts WHERE candidate_id = $1`, target.id); facts != 1 || events != 1 { + t.Fatalf("independent facts = %d over %d events, want 1 over 1", facts, events) + } + + // One event is one fact whatever its tags, and the tags are a closed set. + _, err := harness.pool.Exec(ctx, ` + INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) + SELECT candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at + FROM skill_evidence_facts WHERE id = $1`, fact.ID) + assertPgError(t, "second fact for one event", err, "23505", "skill_evidence_facts_event_key") + // A stored fact is sealed: a later transaction cannot add a tag to it. + _, err = harness.pool.Exec(ctx, `INSERT INTO skill_evidence_skills (fact_id, skill_code) VALUES ($1, 'qa')`, fact.ID) + assertPgError(t, "tag added to a stored fact", err, "23000", "skill_evidence_skills_fact_sealed") + _, err = harness.pool.Exec(ctx, `UPDATE skill_evidence_skills SET skill_code = 'qa' WHERE fact_id = $1 AND skill_code = 'go'`, fact.ID) + assertPgError(t, "rewrite of a tag", err, "23000", "skill_evidence_skills_immutable") + _, err = harness.pool.Exec(ctx, `DELETE FROM skill_evidence_skills WHERE fact_id = $1`, fact.ID) + assertPgError(t, "removal of tags", err, "23000", "skill_evidence_skills_immutable") + // Inside the creating transaction the tags are still a set from the closed list. + tx, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin the tag check: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + if _, err := tx.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil { + t.Fatalf("empty the projection: %v", err) + } + if _, err := tx.Exec(ctx, `SELECT skill_evidence_project_assessment_result($1)`, targetRun.id); err != nil { + t.Fatalf("project the result: %v", err) + } + if _, err := tx.Exec(ctx, `SAVEPOINT repeated`); err != nil { + t.Fatalf("savepoint: %v", err) + } + _, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'backend' FROM skill_evidence_facts`) + assertPgError(t, "repeated tag", err, "23505", "skill_evidence_skills_pkey") + if _, err := tx.Exec(ctx, `ROLLBACK TO SAVEPOINT repeated`); err != nil { + t.Fatalf("roll back to the savepoint: %v", err) + } + _, err = tx.Exec(ctx, `INSERT INTO skill_evidence_skills SELECT id, 'rate-limiting' FROM skill_evidence_facts`) + assertPgError(t, "tag outside the closed set", err, "23514", "skill_evidence_skills_code") + }) + + t.Run("a stored fact keeps its result and trust and only its visibility changes", func(t *testing.T) { + page, _ := readOwn(target, "") + factID := page.Items[0].ID + for name, test := range map[string]struct { + sql, constraint string + code string + }{ + "trust": {`UPDATE skill_evidence_facts SET trust = 2 WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, + "grade": {`UPDATE skill_evidence_facts SET grade = 'senior' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, + "attribution": {`UPDATE skill_evidence_facts SET attribution = 'team_role' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, + "kind": {`UPDATE skill_evidence_facts SET kind = 'claim' WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, + "removal": {`DELETE FROM skill_evidence_facts WHERE id = $1`, "skill_evidence_facts_immutable", "23000"}, + "bad hiding": {`UPDATE skill_evidence_facts SET visibility = 'public' WHERE id = $1`, "skill_evidence_facts_visibility", "23514"}, + } { + _, err := harness.pool.Exec(ctx, test.sql, factID) + assertPgError(t, name, err, test.code, test.constraint) + } + // A fact is a measurement of level 1 to 3 or a claim of level 0, never both. + for name, statement := range map[string]string{ + "claim above level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, 'claim', source_type, event_id, result_id, attribution, 1, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, + "measurement at level 0": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 0, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, + "online result in person": `INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) SELECT candidate_id, kind, source_type, event_id, result_id, attribution, 3, grade, basis, calibration_status, occurred_at FROM skill_evidence_facts WHERE id = $1`, + } { + if _, err := harness.pool.Exec(ctx, statement, factID); err == nil { + t.Errorf("%s was stored", name) + } + } + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE id = $1`, factID); err != nil { + t.Fatalf("hide the fact: %v", err) + } + hiddenPage, _ := readOwn(target, "") + if len(hiddenPage.Items) != 1 || hiddenPage.Items[0].Visibility != "hidden" || hiddenPage.Items[0].Trust != 1 { + t.Fatalf("own evidence after hiding = %+v, want the same fact with visibility hidden", hiddenPage.Items) + } + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE id = $1`, factID); err != nil { + t.Fatalf("show the fact again: %v", err) + } + }) + + t.Run("an express run creates no qualifying evidence, category, or cohort entry", func(t *testing.T) { + expressOnly := client.candidate(t, "evidence-express@example.test") + beforeBody := readOwnBody(t, get, target) + beforeFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`) + beforeCategories := countStoredCategories(t, ctx, harness.pool, target.id) + expressIDs := make([]uuid.UUID, 0, 2) + for _, who := range []categoryHTTPCandidate{target, expressOnly} { + expressIDs = append(expressIDs, runPerfectExpress(t, ctx, client, harness.assessmentAttemptHTTPHarness, who)) + } + if afterBody := readOwnBody(t, get, target); afterBody != beforeBody { + t.Fatalf("evidence changed after an express run:\n%s\n%s", beforeBody, afterBody) + } + if page, _ := readOwn(expressOnly, ""); len(page.Items) != 0 { + t.Fatalf("evidence after express only = %+v, want none", page.Items) + } + if afterFacts := countRows(`SELECT count(*) FROM skill_evidence_facts`); afterFacts != beforeFacts { + t.Fatalf("facts after express = %d, want the %d before", afterFacts, beforeFacts) + } + if countStoredCategories(t, ctx, harness.pool, target.id) != beforeCategories || countStoredCategories(t, ctx, harness.pool, expressOnly.id) != 0 { + t.Fatal("an express run changed a category") + } + // The database also refuses a fact whose source is an express result or + // a failed attempt, even through a direct write. + for name, source := range map[string]struct{ owner, attempt uuid.UUID }{ + "express result of the owner": {target.id, expressIDs[0]}, + "express result of an outsider": {expressOnly.id, expressIDs[1]}, + "failed attempt": {failed.id, failedRun.id}, + } { + _, err := harness.pool.Exec(ctx, ` + INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) + VALUES ($1, 'measurement', 'assessment_result', $2, $2, 'personal', 1, 'intern', 'synthetic_demo', 'uncalibrated', now())`, source.owner, source.attempt) + assertPgError(t, name, err, "23514", "skill_evidence_facts_source_result") + } + // Neither run enters the card cohort as a confirmed category. + consent := privacy.grant(t, expressOnly.id, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, expressOnly.id, consent.ID(), 0, domain.CardFieldCategories) + sources, err := postgresadapter.NewPrivacyCohortStore(harness.pool).ListVisibleCandidateViewSources(ctx, organizationA.ID()) + if err != nil { + t.Fatalf("ListVisibleCandidateViewSources() error = %v", err) + } + for _, source := range sources { + categories := source.Input("cv1_"+strings.Repeat("A", 43), now).ConfirmedCategories + if source.CandidateID() == expressOnly.id && len(categories) != 0 { + t.Fatalf("express-only candidate has categories %v in the cohort", categories) + } + } + // Withdraw the express-only publication so that it does not join the cohort of the target. + privacy.revokeC2(t, expressOnly.id, now.Add(time.Second)) + }) + + t.Run("the list pages by a cursor bound to its owner", func(t *testing.T) { + pager := client.candidate(t, "evidence-pager@example.test") + first := passingIntern(pager) + moveFinishedAttemptBack(t, ctx, harness.pool, first.id, categoryHTTPPromotionGap) + second := client.run(t, pager, "backend", "junior", func(int) int { return threshold }) + if second.result["outcome"] != "confirmed" { + t.Fatalf("promotion run = %v, want confirmed", second.result["outcome"]) + } + firstPage, response := readOwn(pager, "?limit=1") + if response.Code != http.StatusOK || len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || + firstPage.Items[0].Source.ResultID != second.id || firstPage.Items[0].Result.Grade != "junior" { + t.Fatalf("first page = %d %s, want the junior fact and a cursor", response.Code, response.Body.String()) + } + secondPage, response := readOwn(pager, "?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) + if response.Code != http.StatusOK || len(secondPage.Items) != 1 || secondPage.Page.HasMore || secondPage.Page.NextCursor != nil || + secondPage.Items[0].Source.ResultID != first.id || secondPage.Items[0].Result.Grade != "intern" { + t.Fatalf("second page = %d %s, want the intern fact and no more", response.Code, response.Body.String()) + } + if firstPage.Items[0].ID == secondPage.Items[0].ID { + t.Fatal("two events produced one fact") + } + for _, query := range []string{"?cursor=" + url.QueryEscape(*firstPage.Page.NextCursor), "?limit=0", "?limit=101", "?cursor=not-a-cursor"} { + who := pager + if strings.HasPrefix(query, "?cursor="+url.QueryEscape(*firstPage.Page.NextCursor)) { + who = target // the cursor belongs to the pager + } + if response := get(who, "/api/v1/me/evidence"+query); response.Code != http.StatusBadRequest { + t.Fatalf("evidence query %q = %d %s, want 400", query, response.Code, response.Body.String()) + } + } + }) + + t.Run("the preview shows the one fact for each category that an organization would read", func(t *testing.T) { + type previewBody struct { + Card json.RawMessage `json:"card"` + Evidence *struct { + Items []struct { + Skill string `json:"skill"` + Grade string `json:"grade"` + Trust int `json:"trust"` + ObservedYear int `json:"observed_year"` + Basis string `json:"basis"` + Calibration string `json:"calibration_status"` + } `json:"items"` + } `json:"evidence"` + } + preview := func(who categoryHTTPCandidate) previewBody { + t.Helper() + response := get(who, "/api/v1/me/privacy/preview") + var body previewBody + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" || json.Unmarshal(response.Body.Bytes(), &body) != nil { + t.Fatalf("preview of %s = %d %q %s", who.email, response.Code, response.Header().Get("Cache-Control"), response.Body.String()) + } + return body + } + decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string)) + body := preview(target) + if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Skill != "backend" || + body.Evidence.Items[0].Grade != "intern" || body.Evidence.Items[0].Trust != 1 || + body.Evidence.Items[0].Basis != "synthetic_demo" || body.Evidence.Items[0].Calibration != "uncalibrated" || body.Evidence.Items[0].ObservedYear != decidedAt.UTC().Year() { + t.Fatalf("preview evidence = %+v, want the backend intern fact of %d", body.Evidence, decidedAt.UTC().Year()) + } + // A closed profile has no card and no evidence section. + if closed := preview(failed); string(closed.Card) != "null" || closed.Evidence != nil { + t.Fatalf("preview of a closed profile = card %s, evidence %+v, want both null", closed.Card, closed.Evidence) + } + + // A candidate with a lower and a higher passed grade: one fact, the one + // that supports the confirmed grade, whichever way it is asked for. + pagerAccount := client.candidate(t, "evidence-supporting@example.test") + lower := passingIntern(pagerAccount) + moveFinishedAttemptBack(t, ctx, harness.pool, lower.id, categoryHTTPPromotionGap) + higher := client.run(t, pagerAccount, "backend", "junior", func(int) int { return threshold }) + if higher.result["outcome"] != "confirmed" { + t.Fatalf("promotion run = %v, want confirmed", higher.result["outcome"]) + } + consent := privacy.grant(t, pagerAccount.id, domain.ConsentPurposePublication, privacyC2Version, now) + privacy.publish(t, pagerAccount.id, consent.ID(), 0, domain.CardFieldCategories) + body = preview(pagerAccount) + if body.Evidence == nil || len(body.Evidence.Items) != 1 || body.Evidence.Items[0].Grade != "junior" { + t.Fatalf("preview evidence with two passed grades = %+v, want only the junior fact", body.Evidence) + } + if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeJunior { + t.Fatalf("organization evidence for the junior category = %+v, want the junior fact", facts) + } + if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeIntern)); len(facts) != 1 || facts[0].Input().Grade != domain.GradeIntern { + t.Fatalf("organization evidence for the intern category = %+v, want the intern fact", facts) + } + // A hidden fact leaves the preview as it leaves the organization. + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, pagerAccount.id); err != nil { + t.Fatalf("hide the facts: %v", err) + } + if body = preview(pagerAccount); body.Evidence == nil || len(body.Evidence.Items) != 0 { + t.Fatalf("preview evidence of hidden facts = %+v, want an empty list", body.Evidence) + } + if facts := organizationFacts(organizationA.ID(), pagerAccount.id, category(domain.SpecializationBackend, domain.GradeJunior)); len(facts) != 0 { + t.Fatalf("organization evidence of hidden facts = %+v, want none", facts) + } + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, pagerAccount.id); err != nil { + t.Fatalf("show the facts: %v", err) + } + }) + + t.Run("an organization reads the permitted projection only while the card is visible", func(t *testing.T) { + handle := aliasIn(organizationA.ID(), target.id) + path := organizationPath(organizationA.ID(), handle) + response := get(employerAccount, path) + if response.Code != http.StatusOK || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("permitted projection = %d %q %s\n%s", response.Code, response.Header().Get("Cache-Control"), response.Body.String(), harness.logs.String()) + } + decidedAt, _ := time.Parse(time.RFC3339Nano, targetRun.result["decided_at"].(string)) + // One fact for the one category of the card, with the skill, the grade, + // the trust level, and the year only; the other tags stay with the candidate. + wantBody := fmt.Sprintf(`{"items":[{"skill":"backend","grade":"intern","trust":1,"basis":"synthetic_demo","calibration_status":"uncalibrated","observed_year":%d}]}`, decidedAt.UTC().Year()) + if strings.TrimSpace(response.Body.String()) != wantBody { + t.Fatalf("permitted projection = %s, want %s", response.Body.String(), wantBody) + } + for _, private := range []string{target.id.String(), targetRun.id.String(), "event_id", "result_id", "occurred_at", "observed_month", "visibility", "answer", "score", "points", "signal", "review", "not_confirmed", `"id"`} { + if strings.Contains(response.Body.String(), private) { + t.Fatalf("permitted projection exposes %q: %s", private, response.Body.String()) + } + } + // The read is a card view: the quota is used once and the candidate sees the access. + for range 2 { + if again := get(employerAccount, path); again.Code != http.StatusOK { + t.Fatalf("repeated projection = %d %s", again.Code, again.Body.String()) + } + } + if usage := countRows(`SELECT count(*) FROM company_card_view_quota_usage WHERE candidate_id = $1 AND organization_id = $2`, target.id, organizationA.ID()); usage != 1 { + t.Fatalf("card-view quota usage = %d, want one distinct card", usage) + } + if audits := countRows(`SELECT count(*) FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 AND kind = 'card_viewed' AND field_codes = ARRAY['categories']::text[]`, target.id, organizationA.ID()); audits != 3 { + t.Fatalf("access records of the categories field = %d, want 3", audits) + } + + // Access: the roles and the scope of the handle. + if response := get(target, path); response.Code != http.StatusForbidden { + t.Fatalf("candidate account reads the projection = %d, want 403", response.Code) + } + if response := get(categoryHTTPCandidate{}, path); response.Code != http.StatusUnauthorized { + t.Fatalf("guest reads the projection = %d, want 401", response.Code) + } + for name, other := range map[string]string{ + "other member's organization": organizationPath(foreignOrganization.ID(), handle), + "unknown organization": organizationPath(uuid.New(), handle), + "alias of another organization": organizationPath(organizationB.ID(), handle), + "unknown alias": organizationPath(organizationA.ID(), "cv1_"+strings.Repeat("A", 43)), + } { + if response := get(employerAccount, other); response.Code != http.StatusNotFound { + t.Fatalf("%s = %d %s, want 404", name, response.Code, response.Body.String()) + } + } + if response := get(employerAccount, organizationPath(organizationA.ID(), "candidate")); response.Code != http.StatusBadRequest { + t.Fatalf("malformed handle = %d, want 400", response.Code) + } + if response := get(foreignAccount, path); response.Code != http.StatusNotFound { + t.Fatalf("employer without a membership = %d, want 404", response.Code) + } + + // The statement itself rechecks the barrier, whatever the caller did. + backendIntern := category(domain.SpecializationBackend, domain.GradeIntern) + if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 1 || + facts[0].Input() != (domain.EvidenceOrganizationFactInput{ + Skill: "backend", Grade: domain.GradeIntern, Trust: 1, Basis: domain.AssessmentCategorySourceSyntheticDemo, + CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, ObservedYear: int32(decidedAt.UTC().Year()), + }) { + t.Fatalf("repository projection = %+v, want the one backend intern fact", facts) + } + for name, categories := range map[string][]domain.CandidateViewCategory{ + "a specialization without a fact": {category(domain.SpecializationQA, domain.GradeIntern)}, + "a grade the candidate did not pass": {category(domain.SpecializationBackend, domain.GradeSenior)}, + "no category on the card": nil, + } { + if facts := organizationFacts(organizationA.ID(), target.id, categories...); len(facts) != 0 { + t.Fatalf("repository projection for %s = %+v, want none", name, facts) + } + } + if facts := organizationFacts(organizationA.ID(), uuid.New(), backendIntern); len(facts) != 0 { + t.Fatalf("repository projection for an unknown candidate = %+v, want none", facts) + } + + // A hidden fact is absent from what the organization reads. + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE candidate_id = $1`, target.id); err != nil { + t.Fatalf("hide the fact: %v", err) + } + hidden := get(employerAccount, path) + if hidden.Code != http.StatusOK || strings.TrimSpace(hidden.Body.String()) != `{"items":[]}` { + t.Fatalf("projection of a hidden fact = %d %s, want no data", hidden.Code, hidden.Body.String()) + } + if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Visibility != "hidden" { + t.Fatalf("owner after hiding = %+v, want the fact with visibility hidden", page.Items) + } + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE candidate_id = $1`, target.id); err != nil { + t.Fatalf("show the fact: %v", err) + } + + // A card that does not publish the categories field carries no evidence. + publication := privacy.loadPublication(t, target.id) + privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldStack) + if response := get(employerAccount, path); response.Code != http.StatusNotFound { + t.Fatalf("projection of a card without categories = %d %s, want 404", response.Code, response.Body.String()) + } + if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 { + t.Fatalf("repository projection without the categories field = %+v, want none", facts) + } + publication = privacy.loadPublication(t, target.id) + privacy.publish(t, target.id, consents[target.id], publication.Version(), domain.CardFieldCategories) + if response := get(employerAccount, path); response.Code != http.StatusOK { + t.Fatalf("projection after publishing the categories again = %d %s", response.Code, response.Body.String()) + } + + // Hiding the organization closes it for that organization only. + privacy.hide(t, target.id, organizationA.ID(), now.Add(2*time.Second)) + if response := get(employerAccount, path); response.Code != http.StatusNotFound { + t.Fatalf("projection for a hidden organization = %d %s, want 404", response.Code, response.Body.String()) + } + if facts := organizationFacts(organizationA.ID(), target.id, backendIntern); len(facts) != 0 { + t.Fatalf("repository projection for a hidden organization = %+v, want none", facts) + } + if facts := organizationFacts(organizationB.ID(), target.id, backendIntern); len(facts) != 1 { + t.Fatalf("repository projection for another organization = %+v, want one fact", facts) + } + if _, err := harness.pool.Exec(ctx, `DELETE FROM candidate_hidden_organizations WHERE user_id = $1`, target.id); err != nil { + t.Fatalf("lift the hiding: %v", err) + } + if response := get(employerAccount, path); response.Code != http.StatusOK { + t.Fatalf("projection after the hiding was lifted = %d %s", response.Code, response.Body.String()) + } + + // C2 true, then false: after the revocation there is no data, for any organization. + privacy.revokeC2(t, target.id, now.Add(3*time.Second)) + for _, organization := range []domain.Organization{organizationA, organizationB} { + response := get(employerAccount, organizationPath(organization.ID(), aliasIn(organization.ID(), target.id))) + if response.Code != http.StatusNotFound || strings.Contains(response.Body.String(), "measurement") { + t.Fatalf("projection after the C2 revocation = %d %s, want 404 without data", response.Code, response.Body.String()) + } + if facts := organizationFacts(organization.ID(), target.id, backendIntern); len(facts) != 0 { + t.Fatalf("repository projection after the C2 revocation = %+v, want none", facts) + } + } + if page, _ := readOwn(target, ""); len(page.Items) != 1 { + t.Fatalf("owner evidence after the C2 revocation = %+v, want the fact kept", page.Items) + } + }) + + t.Run("deleting the account removes its facts through both cascade paths", func(t *testing.T) { + erased := client.candidate(t, "evidence-erased@example.test") + run := passingIntern(erased) + if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE candidate_id = $1`, erased.id) != 1 { + t.Fatal("the candidate to erase has no fact") + } + // The ledger and history guards keep a confirmed account; this fixture + // lifts them for one transaction, as the deletion procedure will. The + // foreign keys and the triggers of the evidence stay on. + tx, err := harness.pool.Begin(ctx) + if err != nil { + t.Fatalf("begin the erasure: %v", err) + } + defer func() { _ = tx.Rollback(ctx) }() + for _, statement := range []string{ + `ALTER TABLE consent_records DISABLE TRIGGER USER`, + `ALTER TABLE users DISABLE TRIGGER USER`, + } { + if _, err := tx.Exec(ctx, statement); err != nil { + t.Fatalf("lift the retention guards (%s): %v", statement, err) + } + } + // Both paths lead to the fact: the owner of the fact and the result it names. + if _, err := tx.Exec(ctx, `ALTER TABLE assessment_attempt_results DISABLE TRIGGER assessment_attempt_result_refuse_mutation`); err != nil { + t.Fatalf("lift the result guard: %v", err) + } + if _, err := tx.Exec(ctx, `ALTER TABLE candidate_assessment_categories DISABLE TRIGGER candidate_assessment_category_refuse_delete`); err != nil { + t.Fatalf("lift the category guard: %v", err) + } + if _, err := tx.Exec(ctx, `DELETE FROM consent_records WHERE subject_id = $1`, erased.id); err != nil { + t.Fatalf("delete the consent records: %v", err) + } + if _, err := tx.Exec(ctx, `DELETE FROM users WHERE id = $1`, erased.id); err != nil { + t.Fatalf("delete the account: %v", err) + } + for table, column := range map[string]string{ + "skill_evidence_facts": "candidate_id", "assessment_attempt_results": "user_id", + } { + var remaining int + if err := tx.QueryRow(ctx, fmt.Sprintf(`SELECT count(*) FROM %s WHERE %s = $1`, table, column), erased.id).Scan(&remaining); err != nil || remaining != 0 { + t.Fatalf("rows of %s after the account was deleted = %d (error %v), want 0", table, remaining, err) + } + } + var tags int + if err := tx.QueryRow(ctx, `SELECT count(*) FROM skill_evidence_skills AS tag WHERE NOT EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = tag.fact_id)`).Scan(&tags); err != nil || tags != 0 { + t.Fatalf("orphan tags = %d (error %v), want 0", tags, err) + } + // The guards come back before the erasure is committed. + for _, statement := range []string{ + `ALTER TABLE consent_records ENABLE TRIGGER USER`, + `ALTER TABLE users ENABLE TRIGGER USER`, + `ALTER TABLE assessment_attempt_results ENABLE TRIGGER assessment_attempt_result_refuse_mutation`, + `ALTER TABLE candidate_assessment_categories ENABLE TRIGGER candidate_assessment_category_refuse_delete`, + } { + if _, err := tx.Exec(ctx, statement); err != nil { + t.Fatalf("restore the guard (%s): %v", statement, err) + } + } + if err := tx.Commit(ctx); err != nil { + t.Fatalf("commit the erasure: %v", err) + } + if countRows(`SELECT count(*) FROM pg_trigger WHERE tgenabled = 'D' AND NOT tgisinternal`) != 0 { + t.Fatal("a trigger stayed disabled after the erasure") + } + if countRows(`SELECT count(*) FROM skill_evidence_facts WHERE result_id = $1`, run.id) != 0 { + t.Fatal("a fact of the erased account remains") + } + }) + + t.Run("the projection is rebuilt from the results and survives the migration", func(t *testing.T) { + qualifying := countRows(` + SELECT count(*) FROM assessment_attempt_results + WHERE schema_version = 2 AND kind IN ('root', 'corrective') AND outcome = 'confirmed' + AND category_decision ->> 'status' IN ('assigned', 'unchanged')`) + eventsBefore := evidenceEventIDs(t, ctx, harness) + // Cohort of five, two promotions of the pager and two of the candidate of the + // preview; nothing from the failed or express runs. + if want := evidenceCohortSize + 4; qualifying != want || len(eventsBefore) != want { + t.Fatalf("qualifying results = %d, facts = %d, want %d of each", qualifying, len(eventsBefore), want) + } + + // A fact without a skill cannot be committed. + if _, err := harness.pool.Exec(ctx, `TRUNCATE skill_evidence_skills, skill_evidence_facts`); err != nil { + t.Fatalf("empty the projection: %v", err) + } + _, err := harness.pool.Exec(ctx, ` + INSERT INTO skill_evidence_facts (candidate_id, kind, source_type, event_id, result_id, attribution, trust, grade, basis, calibration_status, occurred_at) + SELECT user_id, 'measurement', 'assessment_result', attempt_id, attempt_id, 'personal', 1, category_decision ->> 'attempted_grade', + category_decision ->> 'source', category_decision ->> 'calibration_status', decided_at + FROM assessment_attempt_results WHERE attempt_id = $1`, targetRun.id) + assertPgError(t, "fact without a skill", err, "23514", "skill_evidence_facts_require_skill") + + if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil { + t.Fatalf("project the stored results again: %v", err) + } + if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) { + t.Fatalf("rebuilt events = %v, want %v", eventsAfter, eventsBefore) + } + if _, err := harness.pool.Exec(ctx, `SELECT skill_evidence_project_assessment_result(attempt_id) FROM assessment_attempt_results`); err != nil { + t.Fatalf("project the stored results a second time: %v", err) + } + if countRows(`SELECT count(*) FROM skill_evidence_facts`) != qualifying || countRows(`SELECT count(*) FROM skill_evidence_skills`) != qualifying { + t.Fatal("a repeated projection duplicated facts or tags") + } + + // Rolling the migration back removes the projection and applying it again + // derives it once more from the results that stayed. + migrator := newMigrator(t, databaseURL) + // A fact that the candidate hid is a decision no result can bring back, so + // the rollback refuses until nothing is hidden. + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'hidden' WHERE event_id = $1`, targetRun.id); err != nil { + t.Fatalf("hide the fact: %v", err) + } + // The rollback of the holdings migration refuses a holding that groups several + // organizations. The second organization moves to a holding of its own first; + // the evidence rollback under test does not depend on the grouping. + split := client.employer(t, "evidence-holding-split@example.test") + if _, err := harness.pool.Exec(ctx, ` + INSERT INTO holdings (id, founder_account_id, created_at) VALUES (gen_random_uuid(), $1, now())`, split.id); err != nil { + t.Fatalf("create the holding of the split organization: %v", err) + } + if _, err := harness.pool.Exec(ctx, ` + UPDATE organizations SET holding_id = (SELECT id FROM holdings WHERE founder_account_id = $1) WHERE id = $2`, split.id, organizationB.ID()); err != nil { + t.Fatalf("move the second organization to its own holding: %v", err) + } + // Later migrations may exist; the rollback under test is the evidence one. + rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion) + _, err = migrator.DownOne(ctx) + assertPgError(t, "rollback with a hidden fact", err, "23000", "skill_evidence_retained") + assertTablesExist(ctx, t, harness.pool, true, "skill_evidence_facts", "skill_evidence_skills") + if _, err := harness.pool.Exec(ctx, `UPDATE skill_evidence_facts SET visibility = 'visible' WHERE event_id = $1`, targetRun.id); err != nil { + t.Fatalf("show the fact: %v", err) + } + rollBackAboveMigration(ctx, t, migrator, skillEvidenceMigrationVersion-1) + assertTablesExist(ctx, t, harness.pool, false, "skill_evidence_facts", "skill_evidence_skills") + assertFunctionsExist(ctx, t, harness.pool, false, + "skill_evidence_result_qualifies(assessment_attempt_results)", "skill_evidence_project_assessment_result(uuid)") + applyMigrations(ctx, t, databaseURL) + if eventsAfter := evidenceEventIDs(t, ctx, harness); !slices.Equal(eventsAfter, eventsBefore) { + t.Fatalf("events after the migration was applied again = %v, want %v", eventsAfter, eventsBefore) + } + if page, _ := readOwn(target, ""); len(page.Items) != 1 || page.Items[0].Trust != 1 || page.Items[0].Source.ResultID != targetRun.id { + t.Fatalf("evidence after the migration was applied again = %+v, want the backfilled fact", page.Items) + } + }) +} + +// readOwnBody returns the raw body of the owner's evidence. +func readOwnBody(t *testing.T, get func(categoryHTTPCandidate, string) *httptest.ResponseRecorder, who categoryHTTPCandidate) string { + t.Helper() + response := get(who, "/api/v1/me/evidence") + if response.Code != http.StatusOK { + t.Fatalf("own evidence = %d %s", response.Code, response.Body.String()) + } + return response.Body.String() +} + +// evidenceEventIDs lists the source events of the stored facts in a stable order. +func evidenceEventIDs(t *testing.T, ctx context.Context, harness *skillEvidenceHarness) []string { + t.Helper() + rows, err := harness.pool.Query(ctx, `SELECT event_id::text FROM skill_evidence_facts ORDER BY event_id`) + if err != nil { + t.Fatalf("list evidence events: %v", err) + } + defer rows.Close() + events, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + t.Fatalf("read evidence events: %v", err) + } + return events +} + +// runPerfectExpress answers every item of an express training run correctly, +// finalizes it, and returns its attempt identifier. +func runPerfectExpress(t *testing.T, ctx context.Context, client *categoryHTTPClient, harness *assessmentAttemptHTTPHarness, who categoryHTTPCandidate) uuid.UUID { + t.Helper() + key := uuid.NewString() + status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`, key+"-create") + var attempt assessmentAnswerHTTPAttempt + if status != http.StatusCreated || json.Unmarshal(body, &attempt) != nil || attempt.ID == uuid.Nil { + t.Fatalf("create express attempt = %d %s", status, body) + } + version := attempt.Version + for _, item := range readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID) { + status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", + string(assessmentAnswerHTTPBody(t, version, item)), fmt.Sprintf("%s-answer-%d", key, item.Ordinal)) + var next assessmentAnswerHTTPAttempt + if status != http.StatusOK || json.Unmarshal(body, &next) != nil { + t.Fatalf("answer express item %d = %d %s", item.Ordinal, status, body) + } + version = next.Version + } + finalizeBody, err := json.Marshal(map[string]int64{"expected_version": version}) + if err != nil { + t.Fatalf("marshal finalize body: %v", err) + } + if status, body := client.call(t, who, http.MethodPost, "/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/finalize", + string(finalizeBody), key+"-finalize"); status != http.StatusOK { + t.Fatalf("finalize express attempt = %d %s", status, body) + } + if result := client.result(t, who, attempt.ID); result["outcome"] != "demonstration" { + t.Fatalf("express result = %v, want a demonstration", result) + } + return attempt.ID +} diff --git a/backend/integration_test/support_cases_test.go b/backend/integration_test/support_cases_test.go new file mode 100644 index 0000000..b0cf784 --- /dev/null +++ b/backend/integration_test/support_cases_test.go @@ -0,0 +1,770 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/policy" + questionnaireusecase "lincodex/backend/internal/usecase/questionnaire" + "lincodex/backend/internal/usecase/supportcase" +) + +const supportCaseHTTPTimeout = 5 * time.Minute + +type supportCaseHTTPHarness struct { + *sessionHTTPHarness + supportClock *testClock + keyring *identity.Keyring +} + +func TestSupportCasesOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-owner@example.test", passwordHash, true) + other := createSupportCaseHTTPEmployer(ctx, t, harness, "support-other@example.test", passwordHash) + ownerLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.231:1234") + otherLogin := loginSessionHTTP(t, harness.sessionHTTPHarness, other.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.232:1234") + ownerCookie, ownerCSRF := supportCaseLoginCredentials(t, ownerLogin) + otherCookie, otherCSRF := supportCaseLoginCredentials(t, otherLogin) + + if got := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", "", "", "", "192.0.2.233:1234").Code; got != http.StatusUnauthorized { + t.Fatalf("guest list status = %d, want 401", got) + } + + createSupport := `{"type":"support","description":"The assessment is unavailable; please help with access."}` + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.234:1234") + if created.Code != http.StatusCreated || created.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("create support case = %d Cache-Control=%q: %s, want 201 no-store; server logs: %s", created.Code, + created.Header().Get("Cache-Control"), created.Body.String(), harness.logs.String()) + } + var createdBody supportCaseHTTPResponse + if err := json.Unmarshal(created.Body.Bytes(), &createdBody); err != nil { + t.Fatalf("decode created support case: %v", err) + } + if createdBody.ID == "" || createdBody.Number == "" || createdBody.Type != "support" || createdBody.Status != "submitted" || + createdBody.Description != "The assessment is unavailable; please help with access." || len(createdBody.History) != 1 || createdBody.History[0].Kind != "created" { + t.Fatalf("created support case = %+v", createdBody) + } + + replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1234") + if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() { + t.Fatalf("same-key replay = %d %s, want original 201 body %s", replay.Code, replay.Body.String(), created.Body.String()) + } + var supportCaseCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE id = $1::uuid", createdBody.ID).Scan(&supportCaseCount); err != nil { + t.Fatalf("count idempotent support case: %v", err) + } + if supportCaseCount != 1 { + t.Fatalf("same-key support create stored %d cases, want exactly one", supportCaseCount) + } + changedBody := `{"type":"support","description":"The assessment result is missing; please investigate."}` + changedReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", changedBody, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.235:1236") + requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3) + assertSupportCaseCount(t, ctx, harness, owner.ID, 1) + csrfDenied := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + ownerCookie, "", "support-csrf-denied", "192.0.2.235:1237") + requireSessionProblem(t, csrfDenied, http.StatusForbidden, "csrf_check_failed") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3) + assertSupportCaseCount(t, ctx, harness, owner.ID, 1) + ownRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+createdBody.ID, + "", ownerCookie, "", "", "192.0.2.235:1235") + var ownReadBody supportCaseHTTPResponse + if ownRead.Code != http.StatusOK || ownRead.Header().Get("Cache-Control") != "no-store" || + json.Unmarshal(ownRead.Body.Bytes(), &ownReadBody) != nil || ownReadBody.ID != createdBody.ID || + ownReadBody.Number != createdBody.Number || ownReadBody.Status != "submitted" { + t.Fatalf("owner GET = %d Cache-Control=%q %s, want own submitted case %s", ownRead.Code, + ownRead.Header().Get("Cache-Control"), ownRead.Body.String(), createdBody.ID) + } + + manualBody := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}` + manual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + ownerCookie, ownerCSRF, "support-manual-1", "192.0.2.236:1234") + if manual.Code != http.StatusCreated { + t.Fatalf("manual assessment request without C3 or an earlier attempt = %d %s, want 201", manual.Code, manual.Body.String()) + } + var manualCase supportCaseHTTPResponse + if err := json.Unmarshal(manual.Body.Bytes(), &manualCase); err != nil { + t.Fatalf("decode manual assessment request: %v", err) + } + if manualCase.Type != "manual_assessment" || manualCase.Status != "waiting_expert" || len(manualCase.History) != 2 || + manualCase.History[1].Kind != "status_changed" || manualCase.RubricVersion != nil || + manualCase.ResponseTarget.BusinessDays != 5 || manualCase.ResponseTarget.Kind != "operational_goal" { + t.Fatalf("manual assessment request = %+v, want expert queue, optional rubric, and five-day operational target", manualCase) + } + manualRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+manualCase.ID, + "", ownerCookie, "", "", "192.0.2.236:1235") + var manualReadBody supportCaseHTTPResponse + if manualRead.Code != http.StatusOK || json.Unmarshal(manualRead.Body.Bytes(), &manualReadBody) != nil || + manualReadBody.ID != manualCase.ID || manualReadBody.Status != "waiting_expert" || manualReadBody.RubricVersion != nil { + t.Fatalf("manual case GET = %d %s, want unchanged waiting_expert case without a rubric", manualRead.Code, manualRead.Body.String()) + } + var attemptCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil { + t.Fatalf("read assessment attempts: %v", err) + } + if attemptCount != 0 { + t.Fatalf("manual request unexpectedly has %d prior assessment attempts", attemptCount) + } + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 4) + duplicateManual := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1236") + requireSessionProblem(t, duplicateManual, http.StatusConflict, "state_conflict") + duplicateManualReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + ownerCookie, ownerCSRF, "support-manual-conflict", "192.0.2.236:1237") + requireSessionProblem(t, duplicateManualReplay, http.StatusConflict, "state_conflict") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 6) + var openManualCount int64 + if err := harness.pool.QueryRow(ctx, `SELECT count(*) FROM support_cases + WHERE owner_id = $1 AND case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed')`, owner.ID). + Scan(&openManualCount); err != nil { + t.Fatalf("count open manual assessment cases: %v", err) + } + if openManualCount != 1 { + t.Fatalf("duplicate manual request created %d open cases, want one", openManualCount) + } + invalidDescription := `{"type":"support","description":"\u0085"}` + invalidDomain := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription, + ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1238") + requireSessionProblem(t, invalidDomain, http.StatusBadRequest, "validation_failed") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 7) + invalidDomainRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", invalidDescription, + ownerCookie, ownerCSRF, "support-invalid-description", "192.0.2.236:1239") + requireSessionProblem(t, invalidDomainRetry, http.StatusBadRequest, "validation_failed") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 8) + var consentCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil { + t.Fatalf("read consent side effects: %v", err) + } + if consentCount != 0 { + t.Fatalf("manual assessment changed consent records to %d, want none", consentCount) + } + companyLimited := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", manualBody, + otherCookie, otherCSRF, "support-employer-manual", "192.0.2.236:1241") + requireSessionProblem(t, companyLimited, http.StatusForbidden, "forbidden") + requireSupportCaseRequestCount(t, ctx, harness, other.ID, 0) + resetSupportCaseRequestEvents(t, ctx, harness, owner.ID) + harness.supportClock.Advance(24 * time.Hour) + expiredKeyBody := `{"type":"support","description":"The original support key expired and was accepted again."}` + expiredKeyRetry := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", expiredKeyBody, + ownerCookie, ownerCSRF, "support-owner-1", "192.0.2.236:1240") + var expiredKeyCase supportCaseHTTPResponse + if expiredKeyRetry.Code != http.StatusCreated || json.Unmarshal(expiredKeyRetry.Body.Bytes(), &expiredKeyCase) != nil || + expiredKeyCase.ID == createdBody.ID || expiredKeyCase.Number == createdBody.Number || + expiredKeyCase.Description != "The original support key expired and was accepted again." { + t.Fatalf("same key at exact 24-hour expiry = %d %s, want a new 201 case", expiredKeyRetry.Code, expiredKeyRetry.Body.String()) + } + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 1) + + otherCase := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", createSupport, + otherCookie, otherCSRF, "support-other-1", "192.0.2.237:1234") + if otherCase.Code != http.StatusCreated { + t.Fatalf("other account create = %d %s, want 201", otherCase.Code, otherCase.Body.String()) + } + var otherCaseBody supportCaseHTTPResponse + if err := json.Unmarshal(otherCase.Body.Bytes(), &otherCaseBody); err != nil { + t.Fatalf("decode other account case: %v", err) + } + foreignReference := fmt.Sprintf(`{"type":"support","description":"Reference another account's case.","object":{"type":"support_case","id":%q}}`, otherCaseBody.ID) + foreign := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference, + ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.238:1234") + requireSessionProblem(t, foreign, http.StatusNotFound, "not_found") + foreignReplay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", foreignReference, + ownerCookie, ownerCSRF, "support-foreign-1", "192.0.2.239:1234") + requireSessionProblem(t, foreignReplay, http.StatusNotFound, "not_found") + requireSupportCaseRequestCount(t, ctx, harness, owner.ID, 3) + foreignRead := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+otherCaseBody.ID, + "", ownerCookie, "", "", "192.0.2.240:1234") + requireSessionProblem(t, foreignRead, http.StatusNotFound, "not_found") + + list := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases", "", ownerCookie, "", "", "192.0.2.241:1234") + if list.Code != http.StatusOK || list.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("list own cases = %d Cache-Control=%q: %s", list.Code, list.Header().Get("Cache-Control"), list.Body.String()) + } + var listBody struct { + Items []json.RawMessage `json:"items"` + } + if err := json.Unmarshal(list.Body.Bytes(), &listBody); err != nil { + t.Fatalf("decode own support case list: %v", err) + } + if len(listBody.Items) != 3 || strings.Contains(list.Body.String(), "The assessment is unavailable") || strings.Contains(list.Body.String(), "history") { + t.Fatalf("owner list leaked another case or full-case fields: %s", list.Body.String()) + } + pageOne := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases?limit=1", "", + ownerCookie, "", "", "192.0.2.241:1235") + var firstPage struct { + Items []json.RawMessage `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` + } + if pageOne.Code != http.StatusOK || json.Unmarshal(pageOne.Body.Bytes(), &firstPage) != nil || + len(firstPage.Items) != 1 || !firstPage.Page.HasMore || firstPage.Page.NextCursor == nil || *firstPage.Page.NextCursor == "" { + t.Fatalf("first support-case page = %d %s, want a cursor for more results", pageOne.Code, pageOne.Body.String()) + } + pageTwo := supportCaseHTTP(t, harness, http.MethodGet, + "/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", + ownerCookie, "", "", "192.0.2.241:1236") + var secondPage struct { + Items []json.RawMessage `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + NextCursor *string `json:"next_cursor"` + } `json:"page"` + } + if pageTwo.Code != http.StatusOK || json.Unmarshal(pageTwo.Body.Bytes(), &secondPage) != nil || + len(secondPage.Items) != 1 || !secondPage.Page.HasMore || secondPage.Page.NextCursor == nil || + string(secondPage.Items[0]) == string(firstPage.Items[0]) { + t.Fatalf("second support-case page = %d %s, want one item and another page", pageTwo.Code, pageTwo.Body.String()) + } + pageThree := supportCaseHTTP(t, harness, http.MethodGet, + "/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*secondPage.Page.NextCursor), "", + ownerCookie, "", "", "192.0.2.241:1237") + var lastPage struct { + Items []json.RawMessage `json:"items"` + Page struct { + HasMore bool `json:"has_more"` + } `json:"page"` + } + if pageThree.Code != http.StatusOK || json.Unmarshal(pageThree.Body.Bytes(), &lastPage) != nil || + len(lastPage.Items) != 1 || lastPage.Page.HasMore { + t.Fatalf("last support-case page = %d %s, want one item without another page", pageThree.Code, pageThree.Body.String()) + } + foreignCursor := supportCaseHTTP(t, harness, http.MethodGet, + "/api/v1/me/support-cases?limit=1&cursor="+url.QueryEscape(*firstPage.Page.NextCursor), "", + otherCookie, "", "", "192.0.2.241:1238") + requireSessionProblem(t, foreignCursor, http.StatusBadRequest, "validation_failed") + + resetSupportCaseRequestEvents(t, ctx, harness, owner.ID, other.ID) + for index := range 10 { + body := fmt.Sprintf(`{"type":"support","description":"Rate limit request %d."}`, index) + response := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + ownerCookie, ownerCSRF, fmt.Sprintf("support-limit-%d", index), fmt.Sprintf("192.0.2.%d:1234", 242+index)) + if response.Code != http.StatusCreated { + t.Fatalf("within-limit create %d = %d %s, want 201", index, response.Code, response.Body.String()) + } + } + overLimit := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", + `{"type":"support","description":"This request exceeds the account budget."}`, + ownerCookie, ownerCSRF, "support-limit-over", "192.0.2.247:1234") + if overLimit.Code != http.StatusTooManyRequests || overLimit.Header().Get("Retry-After") == "" { + t.Fatalf("eleventh owner create = %d Retry-After=%q %s, want 429 with a retry interval", overLimit.Code, overLimit.Header().Get("Retry-After"), overLimit.Body.String()) + } + assertRowCount(ctx, t, harness.pool, pgx.Identifier{"support_case_request_events"}, 10) +} + +func TestManualAssessmentPinsPublishedRubricAcrossReplayAndReopening(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + isolatedEnv := *env + isolatedEnv.Config.DatabaseURL = databaseURL + harness := newSupportCaseHTTPHarness(ctx, t, &isolatedEnv) + + firstPolicy, opening, bank, metadata := seedSupportManualRubric(ctx, t, harness) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + owner := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "support-rubric-owner@example.test", passwordHash, true) + login := loginSessionHTTP(t, harness.sessionHTTPHarness, owner.Email.Address(), sessionHTTPTestPass, + sessionHTTPTestOrigin, "", "192.0.2.251:1234") + cookie, csrf := supportCaseLoginCredentials(t, login) + body := `{"type":"manual_assessment","description":"Please assess my Go skills.","assessment_target":{"specialization":"backend","grade":"junior"}}` + created := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1234") + var original supportCaseHTTPResponse + if created.Code != http.StatusCreated || json.Unmarshal(created.Body.Bytes(), &original) != nil || + original.RubricVersion == nil || *original.RubricVersion != firstPolicy.Version() || original.Status != "waiting_expert" { + t.Fatalf("manual request with a current reviewed rubric = %d %s, want 201 pinned to policy version %d", + created.Code, created.Body.String(), firstPolicy.Version()) + } + if strings.Contains(created.Body.String(), "rubric_opening_id") || strings.Contains(created.Body.String(), "rubric_policy_version_id") { + t.Fatalf("public response exposed private rubric pin columns: %s", created.Body.String()) + } + + assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID()) + var consentCount, attemptCount int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", owner.ID).Scan(&consentCount); err != nil { + t.Fatalf("read manual-assessment consent side effects: %v", err) + } + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM assessment_attempts WHERE user_id = $1", owner.ID).Scan(&attemptCount); err != nil { + t.Fatalf("read manual-assessment attempt side effects: %v", err) + } + if consentCount != 0 || attemptCount != 0 { + t.Fatalf("manual request created %d consent records and %d attempts; want neither", consentCount, attemptCount) + } + read := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID, + "", cookie, "", "", "192.0.2.252:1235") + var readBody supportCaseHTTPResponse + if read.Code != http.StatusOK || json.Unmarshal(read.Body.Bytes(), &readBody) != nil || + readBody.ID != original.ID || readBody.RubricVersion == nil || *readBody.RubricVersion != firstPolicy.Version() { + t.Fatalf("manual case GET = %d %s, want the original rubric version", read.Code, read.Body.String()) + } + replay := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1236") + if replay.Code != http.StatusCreated || replay.Body.String() != created.Body.String() { + t.Fatalf("same-key manual replay = %d %s, want the immutable original response %s", replay.Code, replay.Body.String(), created.Body.String()) + } + + secondProductPolicy := domain.DemoProductPolicyV2() + secondProductPolicy.Assessment.MaxAttemptsPerWindow++ + secondPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, + Author: domain.DemoPolicySeedAuthor, Policy: secondProductPolicy, + }) + if err != nil || secondPolicy.Version() <= firstPolicy.Version() { + t.Fatalf("publish later product policy = v%d, %v; want a later immutable version", secondPolicy.Version(), err) + } + harness.supportClock.now = secondPolicy.EffectiveAt() + secondOpening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: opening.Category, GradingPolicyID: secondPolicy.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata, + }) + if err != nil || secondOpening.ID == opening.ID { + t.Fatalf("reopen category under later policy = %+v, %v; want a distinct current opening", secondOpening, err) + } + current, err := bank.CategoryAvailability(ctx, opening.Category) + if err != nil || current.ID != secondOpening.ID { + t.Fatalf("current category opening = %+v, %v; want the later opening", current, err) + } + + readAfterReopening := supportCaseHTTP(t, harness, http.MethodGet, "/api/v1/me/support-cases/"+original.ID, + "", cookie, "", "", "192.0.2.252:1237") + replayAfterReopening := supportCaseHTTP(t, harness, http.MethodPost, "/api/v1/me/support-cases", body, + cookie, csrf, "support-pinned-rubric-1", "192.0.2.252:1238") + var readAfterBody supportCaseHTTPResponse + if readAfterReopening.Code != http.StatusOK || json.Unmarshal(readAfterReopening.Body.Bytes(), &readAfterBody) != nil || + readAfterBody.RubricVersion == nil || *readAfterBody.RubricVersion != firstPolicy.Version() || + replayAfterReopening.Code != http.StatusCreated || replayAfterReopening.Body.String() != created.Body.String() { + t.Fatalf("old manual case changed after category reopening: GET=%d %s replay=%d %s", + readAfterReopening.Code, readAfterReopening.Body.String(), replayAfterReopening.Code, replayAfterReopening.Body.String()) + } + assertStoredSupportRubricPin(ctx, t, harness, original.ID, firstPolicy.Version(), opening.ID, firstPolicy.ID().UUID()) +} + +func seedSupportManualRubric( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, +) (domain.PolicyVersion, domain.AssessmentCategoryOpening, *assessment.Bank, domain.AssessmentCategoryCatalogMetadata) { + t.Helper() + policyStore := postgresadapter.NewPolicyStore(harness.pool) + policyVersion, err := policyStore.Policies().GetEffective(ctx, domain.ProductPolicyKey, harness.supportClock.Now()) + if err != nil { + t.Fatalf("read current support policy for reviewed bank fixture: %v", err) + } + transactor := postgresadapter.NewTransactor(harness.pool) + bank := assessment.NewBank(transactor) + fixture := assessmentFixture{demoBundle: loadDemoBundleFile(t)} + required, err := domain.RequiredPublishedAssessmentFamilies(policyVersion.Policy()) + if err != nil { + t.Fatalf("RequiredPublishedAssessmentFamilies() error = %v", err) + } + bundle := fixture.reviewedBundle(int(required)) + bundle.Name = "support-case-manual-rubric" + bundle.Category = "support-case-manual-rubric" + if _, err := bank.ImportBundle(ctx, bundle); err != nil { + t.Fatalf("ImportBundle(support rubric fixture) error = %v", err) + } + for _, family := range bundle.Families { + if _, err := bank.PublishFamily(ctx, domain.AssessmentFamilyKey(family.Key), family.Version, fixturePublisher); err != nil { + t.Fatalf("PublishFamily(%s) error = %v", family.Key, err) + } + } + metadata, err := domain.NewAssessmentCategoryCatalogMetadata( + domain.SpecializationBackend, domain.GradeJunior, []domain.TaskLanguageCode{domain.TaskLanguageGo}, + ) + if err != nil { + t.Fatalf("NewAssessmentCategoryCatalogMetadata() error = %v", err) + } + category := domain.AssessmentCategory(bundle.Category) + opening, err := bank.OpenCategory(ctx, assessment.OpenCategoryInput{ + Category: category, GradingPolicyID: policyVersion.ID(), OpenedBy: fixtureOpener, CatalogMetadata: &metadata, + }) + if err != nil { + t.Fatalf("OpenCategory(support rubric fixture) error = %v", err) + } + return policyVersion, opening, bank, metadata +} + +func assertStoredSupportRubricPin( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, + caseID string, + version int32, + openingID uuid.UUID, + policyID uuid.UUID, +) { + t.Helper() + var storedVersion int32 + var storedOpeningID, storedPolicyID uuid.UUID + err := harness.pool.QueryRow(ctx, `SELECT rubric_version, rubric_opening_id, rubric_policy_version_id + FROM support_cases WHERE id = $1::uuid`, caseID).Scan(&storedVersion, &storedOpeningID, &storedPolicyID) + if err != nil || storedVersion != version || storedOpeningID != openingID || storedPolicyID != policyID { + t.Fatalf("stored private rubric pin = v%d opening %s policy %s, %v; want v%d opening %s policy %s", + storedVersion, storedOpeningID, storedPolicyID, err, version, openingID, policyID) + } +} + +func TestSupportCaseRequestBudgetSerializesTimestampWithOwnerLock(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), supportCaseHTTPTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + applyMigrations(ctx, t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + store := postgresadapter.NewIdentityStore(pool) + transactor := postgresadapter.NewTransactor(pool) + + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + passwordHash, err := identity.NewCredentials(hasher).HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + address, err := domain.NewEmailAddress("support-budget@example.test") + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + registeredAt := time.Now().UTC().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioCandidate, RegisteredAt: registeredAt, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(user) error = %v", err) + } + if _, err := store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)); err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + + productPolicy := domain.DemoProductPolicyV2() + baseSupport := domain.DemoSupportPolicy() + limitedSupport, err := domain.NewSupportPolicy(domain.SupportPolicyInput{ + SupportResponseDays: baseSupport.SupportResponseDays(), ComplaintResponseDays: baseSupport.ComplaintResponseDays(), + ManualAssessmentResponseDays: baseSupport.ManualAssessmentResponseDays(), AppealResponseDays: baseSupport.AppealResponseDays(), + MaxRequestsPerWindow: 1, RequestWindow: time.Hour, MaxAppealsPerTarget: baseSupport.MaxAppealsPerTarget(), + PauseWhenWaitingForUser: baseSupport.PausesWhenWaitingForUser(), BusinessCalendarVersion: baseSupport.BusinessCalendarVersion(), + }) + if err != nil { + t.Fatalf("NewSupportPolicy() error = %v", err) + } + productPolicy.Support = &limitedSupport + policyClock := time.Now + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), policyClock).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: productPolicy, + }); err != nil { + t.Fatalf("publish budget test policy: %v", err) + } + + firstTimestamp := time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond) + var clockCalls atomic.Int32 + clock := func() time.Time { + if clockCalls.Add(1) == 1 { + return firstTimestamp + } + return firstTimestamp.Add(-time.Hour) + } + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: clock}) + if err != nil { + t.Fatalf("NewSupportCaseService() error = %v", err) + } + start := make(chan struct{}) + results := make(chan error, 2) + for index := range 2 { + go func(index int) { + <-start + _, err := service.Create(ctx, supportcase.CreateCommand{ + ActorID: user.ID, IdempotencyKey: fmt.Sprintf("support-budget-%d", index), + Type: domain.SupportCaseTypeSupport, Description: fmt.Sprintf("Budget request %d.", index), + }) + results <- err + }(index) + } + close(start) + firstError, secondError := <-results, <-results + if clockCalls.Load() != 2 { + t.Fatalf("service clock calls = %d, want one post-lock sample per request", clockCalls.Load()) + } + successes := 0 + limited := 0 + for _, err := range []error{firstError, secondError} { + switch { + case err == nil: + successes++ + case errors.Is(err, supportcase.ErrRateLimited): + limited++ + default: + t.Fatalf("concurrent request error = %v, want one create and one rate limit", err) + } + } + if successes != 1 || limited != 1 { + t.Fatalf("concurrent requests had %d creates and %d rate limits, want one each", successes, limited) + } + assertRowCount(ctx, t, pool, pgx.Identifier{"support_cases"}, 1) + assertRowCount(ctx, t, pool, pgx.Identifier{"support_case_request_events"}, 1) +} + +func requireSupportCaseRequestCount( + t *testing.T, + ctx context.Context, + harness *supportCaseHTTPHarness, + ownerID uuid.UUID, + want int64, +) { + t.Helper() + var count int64 + if err := harness.pool.QueryRow(ctx, + "SELECT count(*) FROM support_case_request_events WHERE owner_id = $1", ownerID, + ).Scan(&count); err != nil { + t.Fatalf("count support request events for owner: %v", err) + } + if count != want { + t.Fatalf("support request events for owner = %d, want %d", count, want) + } +} + +func assertSupportCaseCount(t *testing.T, ctx context.Context, harness *supportCaseHTTPHarness, ownerID uuid.UUID, want int64) { + t.Helper() + var count int64 + if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM support_cases WHERE owner_id = $1", ownerID).Scan(&count); err != nil { + t.Fatalf("count support cases for owner: %v", err) + } + if count != want { + t.Fatalf("support cases for owner = %d, want %d", count, want) + } +} + +func resetSupportCaseRequestEvents( + t *testing.T, + ctx context.Context, + harness *supportCaseHTTPHarness, + ownerIDs ...uuid.UUID, +) { + t.Helper() + for _, ownerID := range ownerIDs { + if _, err := harness.pool.Exec(ctx, "DELETE FROM support_case_request_events WHERE owner_id = $1", ownerID); err != nil { + t.Fatalf("reset support request events for owner: %v", err) + } + } +} + +func createSupportCaseHTTPEmployer( + ctx context.Context, + t *testing.T, + harness *supportCaseHTTPHarness, + email string, + passwordHash domain.PasswordHash, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + registeredAt := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, PasswordHash: passwordHash, Scenario: domain.ScenarioEmployer, RegisteredAt: registeredAt, + }) + if err != nil { + t.Fatalf("NewUser(employer) error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(employer) error = %v", err) + } + user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, registeredAt.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified(employer) error = %v", err) + } + return user +} + +type supportCaseHTTPResponse struct { + ID string `json:"id"` + Number string `json:"number"` + Type string `json:"type"` + Status string `json:"status"` + Description string `json:"description"` + RubricVersion *int32 `json:"rubric_version"` + Decision *json.RawMessage `json:"decision"` + AssessmentTarget *struct { + Specialization string `json:"specialization"` + Grade string `json:"grade"` + } `json:"assessment_target"` + History []struct { + Kind string `json:"kind"` + Actor string `json:"actor"` + Status string `json:"status"` + } `json:"history"` + ResponseTarget struct { + Kind string `json:"kind"` + BusinessDays int32 `json:"business_days"` + } `json:"response_target"` +} + +func newSupportCaseHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *supportCaseHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + supportClock := &testClock{now: clock.Now()} + transactor := postgresadapter.NewTransactor(pool) + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, Users: store.Users(), Sessions: store.Sessions(), + Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + publishedPolicy, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).Publish(ctx, policy.PublishInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, Policy: domain.DemoProductPolicyV2(), + }) + if err != nil { + t.Fatalf("publish explicit support demo policy: %v", err) + } + // Publication time comes from PostgreSQL and is later than the fixed + // session clock. Start support requests at the returned effective time. + supportClock.now = publishedPolicy.EffectiveAt() + service, err := supportcase.NewService(supportcase.Dependencies{Transactor: transactor, Keyring: keyring, Clock: supportClock.Now}) + if err != nil { + t.Fatalf("NewSupportCaseService() error = %v", err) + } + logs := &strings.Builder{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(sessions), v1.WithPublicOrigin(env.Config.AppPublicURL), + ) + supportHandler := v1.NewSupportHandler(service) + // Consent, questionnaire, and assessment routes share the support clock and + // policy so one test can drive a C3 revocation, a failed attempt, and a + // manual assessment request through the real router. + consentHandler := v1.NewConsentHandler( + consent.NewQueryService(postgresadapter.NewConsentStore(pool), time.Now), consent.NewService(transactor, time.Now), + ) + questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, supportClock.Now)) + attemptService, err := assessment.NewAttemptService(transactor, transactor, keyring, supportClock.Now) + if err != nil { + t.Fatalf("NewAttemptService() error = %v", err) + } + handler := v1.NewHandler(healthHandler, responder, + v1.WithIdentity(identityHandler), v1.WithSupport(supportHandler), + v1.WithConsent(consentHandler), v1.WithQuestionnaire(questionnaireHandler), + v1.WithAssessment(v1.NewAssessmentHandler(attemptService)), + ) + router, err := httpadapter.NewRouter(healthHandler, handler, identityHandler.SessionSecurity(), responder, + prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &supportCaseHTTPHarness{ + sessionHTTPHarness: &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs}, + supportClock: supportClock, + keyring: keyring, + } +} + +func supportCaseLoginCredentials(t *testing.T, response *httptest.ResponseRecorder) (string, string) { + t.Helper() + if response.Code != http.StatusCreated { + t.Fatalf("login support case account = %d %s, want 201", response.Code, response.Body.String()) + } + cookie := requireSessionCookie(t, response) + var body struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil || body.CSRFToken == "" { + t.Fatalf("decode support case login response: %v", err) + } + return cookie.Value, body.CSRFToken +} + +func supportCaseHTTP( + t *testing.T, + harness *supportCaseHTTPHarness, + method, path, body, cookie, csrf, idempotencyKey, remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if method == http.MethodPost { + request.Header.Set("Origin", sessionHTTPTestOrigin) + request.Header.Set("Idempotency-Key", idempotencyKey) + } + if cookie != "" { + request.Header.Set("Cookie", "__Host-lincodex_session="+cookie) + } + if csrf != "" { + request.Header.Set("X-CSRF-Token", csrf) + } + request.RemoteAddr = remoteAddr + response := httptest.NewRecorder() + harness.router.ServeHTTP(response, request) + return response +} diff --git a/backend/internal/adapter/primary/cli/assessmentreview/command.go b/backend/internal/adapter/primary/cli/assessmentreview/command.go new file mode 100644 index 0000000..6f9b88a --- /dev/null +++ b/backend/internal/adapter/primary/cli/assessmentreview/command.go @@ -0,0 +1,135 @@ +// Package assessmentreview implements the local operator command that prints +// the stored manual-review band of an assessment attempt. The band is never +// served over HTTP; this command is the only reader until staff roles exist. +package assessmentreview + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" +) + +const usage = "usage: assessment-review inspect --attempt --actor operator:" + +// Command is a parsed, validated review inspection. +type Command struct { + AttemptID domain.AssessmentAttemptID + Actor string +} + +// Operator reads a review and records the read. +type Operator interface { + Inspect(ctx context.Context, attemptID domain.AssessmentAttemptID, actor string) (domain.AssessmentAttemptReview, error) +} + +// Parse validates every argument before Run reads configuration or connects +// to PostgreSQL. +func Parse(args []string) (Command, error) { + if len(args) == 0 || args[0] != "inspect" { + return Command{}, errors.New(usage) + } + flags := flag.NewFlagSet("assessment-review inspect", flag.ContinueOnError) + flags.SetOutput(io.Discard) + attempt := flags.String("attempt", "", "attempt UUID") + actor := flags.String("actor", "", "operator handle") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + attemptID, err := uuid.Parse(strings.TrimSpace(*attempt)) + if err != nil || attemptID == uuid.Nil { + return Command{}, errors.New("attempt must be a non-zero UUID") + } + if _, err := domain.ParseAssessmentReviewActor(strings.TrimSpace(*actor)); err != nil { + return Command{}, errors.New("actor must be operator:") + } + return Command{AttemptID: domain.AssessmentAttemptID(attemptID), Actor: strings.TrimSpace(*actor)}, nil +} + +// Run parses the command, loads only DATABASE_URL from the supplied +// environment, and executes the operator usecase. It does not load dotenv +// files. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil { + return errors.New("assessment review command dependencies are required") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + operator, err := assessment.NewReviewOperator(postgres.NewTransactor(pool)) + if err != nil { + return errors.New("assessment review is unavailable") + } + return Execute(ctx, command, operator, output) +} + +// Execute prints the review. The output holds counts, durations, the band, the +// reason codes, and the policy version; it holds no answer, address, session, +// candidate, or contact data. +func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error { + if operator == nil || output == nil { + return errors.New("assessment review command dependencies are required") + } + review, err := operator.Inspect(ctx, command.AttemptID, command.Actor) + if err != nil { + return safeOperationError(err) + } + reasons := make([]string, 0, len(review.Outcome.Reasons)) + for _, reason := range review.Outcome.Reasons { + reasons = append(reasons, string(reason)) + } + measures := review.Measures + if _, err := fmt.Fprintf(output, + "attempt: %s\nband: %s\nreasons: %s\npolicy_version: %d\nevaluated_at: %s\nupdated_at: %s\n"+ + "answered_items: %d\nfast_answers: %d\ndeviating_answers: %d\nparallel_alternations: %d\nextra_networks: %d\nextra_agents: %d\n"+ + "matched_integer_items: %d\nmatched_sequence_items: %d\nduplicate_evidence_bits: %d\n"+ + "client_focus_loss_ms: %d\nclient_clipboard_events: %d\nclient_fullscreen_exits: %d\n"+ + "client_screenshot_keys: %d\nclient_devtools_opens: %d\n"+ + "note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged; "+ + "a screenshot or a phone photo cannot be prevented or seen by the page\n", + review.AttemptID, review.Outcome.Band, strings.Join(reasons, ","), review.PolicyVersion, + review.EvaluatedAt.UTC().Format(time.RFC3339), review.UpdatedAt.UTC().Format(time.RFC3339), + measures.AnsweredItems, measures.FastAnswers, measures.DeviatingAnswers, measures.ParallelAlternations, + measures.ExtraNetworks, measures.ExtraAgents, measures.MatchedIntegerItems, measures.MatchedSequenceItems, + measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents, + measures.ClientFullscreenExits, measures.ClientScreenshotKeys, measures.ClientDevtoolsOpens, + ); err != nil { + return errors.New("could not write the review") + } + return nil +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, outbound.ErrAssessmentReviewNotFound): + return errors.New("attempt has no review (the read was recorded)") + case errors.Is(err, domain.ErrInvalidAssessmentReview): + return errors.New("attempt or actor is invalid") + default: + return errors.New("assessment review operation failed") + } +} diff --git a/backend/internal/adapter/primary/cli/assessmentreview/command_test.go b/backend/internal/adapter/primary/cli/assessmentreview/command_test.go new file mode 100644 index 0000000..dd146a8 --- /dev/null +++ b/backend/internal/adapter/primary/cli/assessmentreview/command_test.go @@ -0,0 +1,113 @@ +package assessmentreview + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type operatorFake struct { + review domain.AssessmentAttemptReview + err error + calls int + actor string +} + +func (operator *operatorFake) Inspect(_ context.Context, _ domain.AssessmentAttemptID, actor string) (domain.AssessmentAttemptReview, error) { + operator.calls++ + operator.actor = actor + return operator.review, operator.err +} + +func TestParseRequiresAnAttemptAndAnOperatorHandle(t *testing.T) { + id := uuid.New().String() + command, err := Parse([]string{"inspect", "--attempt", id, "--actor", "operator:night"}) + if err != nil || command.AttemptID.String() != id || command.Actor != "operator:night" { + t.Fatalf("Parse(valid) = %+v, %v", command, err) + } + for _, args := range [][]string{ + nil, + {"list"}, + {"inspect"}, + {"inspect", "--attempt", id}, + {"inspect", "--attempt", id, "--actor", "alice"}, + {"inspect", "--attempt", "not-a-uuid", "--actor", "operator:night"}, + {"inspect", "--attempt", uuid.Nil.String(), "--actor", "operator:night"}, + {"inspect", "--attempt", id, "--actor", "operator:night", "extra"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) { + lookup := func(string) (string, bool) { + t.Fatal("environment read before arguments were validated") + return "", false + } + if err := Run(context.Background(), []string{"inspect"}, lookup, &bytes.Buffer{}); err == nil { + t.Fatal("Run(invalid arguments) succeeded") + } + var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false } + err := Run(context.Background(), []string{"inspect", "--attempt", uuid.New().String(), "--actor", "operator:night"}, noDatabase, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") { + t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err) + } +} + +func TestExecutePrintsOnlyBandCountsAndReasons(t *testing.T) { + attemptID := domain.AssessmentAttemptID(uuid.New()) + operator := &operatorFake{review: domain.AssessmentAttemptReview{ + AttemptID: attemptID, PolicyVersion: 4, + Measures: domain.AssessmentReviewMeasures{AnsweredItems: 9, FastAnswers: 5, ParallelAlternations: 2, ExtraNetworks: 1, MatchedIntegerItems: 3, DuplicateEvidenceBits: 9}, + Outcome: domain.AssessmentReviewOutcome{ + Band: domain.AssessmentReviewBandAttention, + Reasons: []domain.AssessmentReviewReason{domain.AssessmentReviewReasonFastAnswers, domain.AssessmentReviewReasonParallelSessions}, + }, + EvaluatedAt: time.Date(2026, time.October, 1, 10, 0, 0, 0, time.UTC), UpdatedAt: time.Date(2026, time.October, 2, 10, 0, 0, 0, time.UTC), + }} + var output bytes.Buffer + command := Command{AttemptID: attemptID, Actor: "operator:night"} + if err := Execute(context.Background(), command, operator, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + for _, want := range []string{"attempt: " + attemptID.String(), "band: attention", "reasons: fast_answers,parallel_sessions", "policy_version: 4", "fast_answers: 5", "matched_integer_items: 3", "extra_networks: 1", "duplicate_evidence_bits: 9", "a hint for a manual check"} { + if !strings.Contains(output.String(), want) { + t.Errorf("output lacks %q:\n%s", want, output.String()) + } + } + for _, forbidden := range []string{"user", "email", "address", "session", "answer:", "fingerprint"} { + if strings.Contains(output.String(), forbidden+":") { + t.Errorf("output has a %q line:\n%s", forbidden, output.String()) + } + } + if operator.calls != 1 || operator.actor != "operator:night" { + t.Fatalf("operator calls/actor = %d/%q, want one call with the handle", operator.calls, operator.actor) + } +} + +func TestExecuteMapsFailuresToSafeMessages(t *testing.T) { + for _, test := range []struct { + err error + want string + }{ + {outbound.ErrAssessmentReviewNotFound, "no review"}, + {domain.ErrInvalidAssessmentReview, "invalid"}, + {errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "operation failed"}, + } { + err := Execute(context.Background(), Command{}, &operatorFake{err: test.err}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") { + t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want) + } + } +} diff --git a/backend/internal/adapter/primary/cli/bankcoverage/command.go b/backend/internal/adapter/primary/cli/bankcoverage/command.go new file mode 100644 index 0000000..5b41ba9 --- /dev/null +++ b/backend/internal/adapter/primary/cli/bankcoverage/command.go @@ -0,0 +1,225 @@ +// Package bankcoverage implements the local assessment bank coverage command. +package bankcoverage + +import ( + "bytes" + "errors" + "flag" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + + assessment "lincodex/backend/internal/usecase/assessment" +) + +// Run reports how valid bundle drafts and implementation paths match the bank manifest. +func Run(arguments []string, stdout, stderr io.Writer) error { + const location = "bankcoverage.Run" + flags := flag.NewFlagSet("assessment-bank-coverage", flag.ContinueOnError) + flags.SetOutput(stderr) + manifestPath := flags.String("manifest", "testdata/assessment/bank_manifest.json", "path to the planned bank manifest") + bundleDir := flags.String("bundles", "testdata/assessment", "directory containing bank bundle JSON files and solution files") + strict := flags.Bool("strict", false, "fail when planned families, review declarations, or implementation paths are missing") + if err := flags.Parse(arguments); err != nil { + return fmt.Errorf("%s - parse arguments: %w", location, err) + } + if flags.NArg() != 0 { + return fmt.Errorf("%s - unexpected positional arguments", location) + } + content, err := os.ReadFile(*manifestPath) + if err != nil { + return fmt.Errorf("%s - read manifest: %w", location, err) + } + manifest, err := assessment.ParseBankCoverageManifest(content) + if err != nil { + return err + } + inventory, err := loadBankCoverageInventory(*bundleDir, *manifestPath, manifest) + if err != nil { + return fmt.Errorf("%s - load bundle inventory: %w", location, err) + } + report, err := assessment.BuildBankCoverageReport(manifest, inventory) + if err != nil { + return fmt.Errorf("%s - build report: %w", location, err) + } + if err := printBankCoverageReport(stdout, report); err != nil { + return fmt.Errorf("%s - write report: %w", location, err) + } + if *strict { + return report.StrictError() + } + return nil +} + +func loadBankCoverageInventory(bundleDir, manifestPath string, manifest assessment.BankCoverageManifest) (result assessment.BankCoverageInventory, returnErr error) { + const location = "bankcoverage.loadBankCoverageInventory" + manifestPath, err := canonicalPath(manifestPath) + if err != nil { + return assessment.BankCoverageInventory{}, fmt.Errorf("%s - resolve manifest path: %w", location, err) + } + bundleRoot, err := os.OpenRoot(bundleDir) + if err != nil { + return assessment.BankCoverageInventory{}, fmt.Errorf("%s - open bundle directory: %w", location, err) + } + defer func() { + if err := bundleRoot.Close(); err != nil { + returnErr = errors.Join(returnErr, fmt.Errorf("%s - close bundle directory: %w", location, err)) + } + }() + inventory := assessment.BankCoverageInventory{} + err = fs.WalkDir(bundleRoot.FS(), ".", func(path string, entry fs.DirEntry, walkErr error) error { + if walkErr != nil { + return fmt.Errorf("%s - scan bundle directory: %w", location, walkErr) + } + if entry.IsDir() || filepath.Ext(path) != ".json" { + return nil + } + candidatePath, err := canonicalPath(filepath.Join(bundleDir, filepath.FromSlash(path))) + if err != nil { + return fmt.Errorf("%s - resolve candidate path %s: %w", location, filepath.ToSlash(path), err) + } + if candidatePath == manifestPath { + return nil + } + content, err := bundleRoot.ReadFile(filepath.FromSlash(path)) + if err != nil { + return fmt.Errorf("%s - read bundle %s: %w", location, filepath.ToSlash(path), err) + } + bundle, err := assessment.ParseBundle(bytes.NewReader(content)) + if err != nil { + inventory.InvalidBundleFiles = append(inventory.InvalidBundleFiles, fmt.Sprintf("%s: %v", filepath.ToSlash(path), err)) + return nil + } + drafts, err := bundle.Drafts() + if err != nil { + inventory.InvalidBundleFiles = append(inventory.InvalidBundleFiles, fmt.Sprintf("%s: %v", filepath.ToSlash(path), err)) + return nil + } + for _, draft := range drafts { + core := draft.Core() + inventory.Families = append(inventory.Families, assessment.BankCoverageFamilyRecord{ + Key: string(core.Key), Category: string(core.Category), Version: core.Version, + Author: string(core.Author), Reviewer: string(core.Reviewer), + ReviewStatus: string(core.ReviewStatus), Source: filepath.ToSlash(path), + }) + } + return nil + }) + if err != nil { + return assessment.BankCoverageInventory{}, err + } + if err := collectImplementationPaths(bundleRoot, manifest, &inventory); err != nil { + return assessment.BankCoverageInventory{}, fmt.Errorf("%s - collect implementation paths: %w", location, err) + } + return inventory, nil +} + +func collectImplementationPaths(root *os.Root, manifest assessment.BankCoverageManifest, inventory *assessment.BankCoverageInventory) error { + const location = "bankcoverage.collectImplementationPaths" + for _, category := range manifest.Categories { + for _, topic := range category.Topics { + for _, key := range topic.FamilyKeys { + for _, language := range category.RequiredLanguages { + relative := filepath.Join(category.ImplementationsDir, key+implementationExtension(language)) + info, err := root.Stat(relative) + if err != nil { + if errors.Is(err, fs.ErrNotExist) { + continue + } + return fmt.Errorf("%s - inspect %s: %w", location, filepath.ToSlash(relative), err) + } + if info.Mode().IsRegular() && info.Size() > 0 { + inventory.ImplementationFiles = append(inventory.ImplementationFiles, filepath.ToSlash(relative)) + } + } + } + } + } + return nil +} + +func canonicalPath(path string) (string, error) { + absPath, err := filepath.Abs(path) + if err != nil { + return "", err + } + resolvedPath, err := filepath.EvalSymlinks(absPath) + if err != nil { + return "", err + } + return filepath.Clean(resolvedPath), nil +} + +func implementationExtension(language string) string { + if language == "python" { + return ".py" + } + return ".go" +} + +func printBankCoverageReport(writer io.Writer, report assessment.BankCoverageReport) error { + const location = "bankcoverage.printBankCoverageReport" + write := func(format string, values ...any) error { + if _, err := fmt.Fprintf(writer, format, values...); err != nil { + return fmt.Errorf("%s - write output: %w", location, err) + } + return nil + } + if err := write("Assessment bank coverage inventory\n"); err != nil { + return err + } + if err := write("Family records are valid drafts from bundle files; this report does not publish or calibrate them.\n"); err != nil { + return err + } + for _, category := range report.Categories { + if err := write("%s: %d/%d planned family keys present; %d keys inventoried; %d/%d implementation paths present\n", + category.Code, category.PresentFamilies, category.PlannedFamilies, category.InventoriedFamilies, + category.PresentImplementationFiles, category.RequiredImplementationFiles); err != nil { + return err + } + } + if err := write("Review declarations: %d approved, %d pending, %d rejected; %d distinct family keys inventoried\n", + report.DeclaredApprovedReviews, report.PendingReviewDeclarations, report.RejectedReviewDeclarations, report.InventoriedFamilies); err != nil { + return err + } + for _, names := range []struct { + label string + names []string + }{ + {"Missing family keys", report.MissingFamilyKeys}, + {"Families without an approved independent reviewer declaration", report.MissingIndependentReviews}, + {"Missing Go/Python implementation paths", report.MissingImplementationFiles}, + {"Unassigned family keys", report.UnassignedFamilyKeys}, + {"Unassigned categories", report.UnassignedCategories}, + {"Category mismatches", report.CategoryMismatches}, + {"Invalid bundle records", report.InvalidBundleFiles}, + {"Evidence not verifiable by this check", report.UnverifiableEvidence}, + } { + if err := printNames(writer, names.label, names.names); err != nil { + return fmt.Errorf("%s - print %s: %w", location, names.label, err) + } + } + if report.CalibrationMeasurementRequired { + if err := write("Calibration thresholds remain external measurement gates; no quality result is inferred.\n"); err != nil { + return err + } + } + return nil +} + +func printNames(writer io.Writer, label string, names []string) error { + if len(names) == 0 { + return nil + } + if _, err := fmt.Fprintf(writer, "%s (%d):\n", label, len(names)); err != nil { + return err + } + for _, name := range names { + if _, err := fmt.Fprintf(writer, " %s\n", name); err != nil { + return err + } + } + return nil +} diff --git a/backend/internal/adapter/primary/cli/bankcoverage/command_test.go b/backend/internal/adapter/primary/cli/bankcoverage/command_test.go new file mode 100644 index 0000000..64eb332 --- /dev/null +++ b/backend/internal/adapter/primary/cli/bankcoverage/command_test.go @@ -0,0 +1,115 @@ +package bankcoverage + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +const assessmentFixturePath = "../../../../../testdata/assessment" + +func TestRunReportsIncompleteInventoryWithoutFailing(t *testing.T) { + manifestPath, bundleDir := prepareCoverageFixtures(t) + var output bytes.Buffer + if err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err != nil { + t.Fatalf("run() error = %v, want informational success", err) + } + if !strings.Contains(output.String(), "backend: 0/25 planned family keys present") || + !strings.Contains(output.String(), "network: 0/15 planned family keys present") { + t.Fatalf("report omitted incomplete family counts:\n%s", output.String()) + } +} + +func TestRunStrictRefusesIncompleteInventory(t *testing.T) { + manifestPath, bundleDir := prepareCoverageFixtures(t) + var output bytes.Buffer + err := Run([]string{"--strict", "--manifest", manifestPath, "--bundles", bundleDir}, &output, &output) + if err == nil || !strings.Contains(err.Error(), "assessment.BankCoverageReport.StrictError") { + t.Fatalf("run(--strict) error = %v, want strict incomplete-inventory error", err) + } + if !strings.Contains(output.String(), "Missing family keys (40)") { + t.Fatalf("strict report omitted missing keys:\n%s", output.String()) + } +} + +func TestRunReportsMalformedBundleAndStrictModeRejectsIt(t *testing.T) { + manifestPath, bundleDir := prepareCoverageFixtures(t) + malformedPath := filepath.Join(bundleDir, "malformed.json") + if err := os.WriteFile(malformedPath, []byte("not a bundle"), 0o600); err != nil { + t.Fatalf("write malformed bundle: %v", err) + } + var output bytes.Buffer + if err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err != nil { + t.Fatalf("run() error = %v, want informational success", err) + } + if !strings.Contains(output.String(), "Invalid bundle records (1)") || !strings.Contains(output.String(), "malformed.json") { + t.Fatalf("report omitted malformed bundle diagnostic:\n%s", output.String()) + } + if err := Run([]string{"--strict", "--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err == nil { + t.Fatal("run(--strict) error = nil, want malformed bundle refusal") + } +} + +func TestRunSkipsTheCustomManifestInsideBundleDirectory(t *testing.T) { + _, bundleDir := prepareCoverageFixtures(t) + manifestPath := filepath.Join(bundleDir, "plan-custom.json") + content, err := os.ReadFile(filepath.Join(assessmentFixturePath, "bank_manifest.json")) + if err != nil { + t.Fatalf("read manifest fixture: %v", err) + } + if err := os.WriteFile(manifestPath, content, 0o600); err != nil { + t.Fatalf("write custom manifest: %v", err) + } + var output bytes.Buffer + if err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, &output, &output); err != nil { + t.Fatalf("run() error = %v, want report success", err) + } + if strings.Contains(output.String(), "plan-custom.json") { + t.Fatalf("custom manifest was parsed as a bundle:\n%s", output.String()) + } +} + +func TestRunPropagatesOutputWriteFailure(t *testing.T) { + manifestPath, bundleDir := prepareCoverageFixtures(t) + writeErr := errors.New("closed output") + err := Run([]string{"--manifest", manifestPath, "--bundles", bundleDir}, failingCoverageWriter{err: writeErr}, &bytes.Buffer{}) + if !errors.Is(err, writeErr) { + t.Fatalf("run() error = %v, want wrapped output error", err) + } +} + +func prepareCoverageFixtures(t *testing.T) (string, string) { + t.Helper() + root := t.TempDir() + bundleDir := filepath.Join(root, "bundles") + if err := os.Mkdir(bundleDir, 0o700); err != nil { + t.Fatalf("create bundle directory: %v", err) + } + manifestContent, err := os.ReadFile(filepath.Join(assessmentFixturePath, "bank_manifest.json")) + if err != nil { + t.Fatalf("read manifest fixture: %v", err) + } + manifestPath := filepath.Join(root, "bank-plan.json") + if err := os.WriteFile(manifestPath, manifestContent, 0o600); err != nil { + t.Fatalf("write manifest fixture: %v", err) + } + bundleContent, err := os.ReadFile(filepath.Join(assessmentFixturePath, "backend_demo_bundle.json")) + if err != nil { + t.Fatalf("read demo bundle fixture: %v", err) + } + if err := os.WriteFile(filepath.Join(bundleDir, "backend_demo_bundle.json"), bundleContent, 0o600); err != nil { + t.Fatalf("write demo bundle fixture: %v", err) + } + return manifestPath, bundleDir +} + +type failingCoverageWriter struct { + err error +} + +func (writer failingCoverageWriter) Write([]byte) (int, error) { + return 0, writer.err +} diff --git a/backend/internal/adapter/primary/cli/categoryattest/command.go b/backend/internal/adapter/primary/cli/categoryattest/command.go new file mode 100644 index 0000000..dfbdfce --- /dev/null +++ b/backend/internal/adapter/primary/cli/categoryattest/command.go @@ -0,0 +1,151 @@ +// Package categoryattest implements the local operator command that attests the +// current opening of an assessment category as a source of synthetic +// demonstration categories. It is meant for isolated synthetic stands: a +// category is assigned only when the runtime gate +// ASSESSMENT_DEMO_CATEGORIES_ENABLED is also on. +package categoryattest + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strings" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" +) + +// syntheticOnlyWarning is printed before any work, also when the command fails. +const syntheticOnlyWarning = "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand\n" + +const usage = "usage: assessment-category-attest attest --specialization --grade [--task-language ] --actor operator:" + +// Command is a parsed, validated attestation request. +type Command struct { + Specialization domain.SpecializationCode + Grade domain.GradeCode + TaskLanguage *domain.TaskLanguageCode + Actor string +} + +// Attestor stores an attestation. +type Attestor interface { + Attest( + ctx context.Context, + specialization domain.SpecializationCode, + grade domain.GradeCode, + language *domain.TaskLanguageCode, + actor string, + ) (assessment.CategoryAttestation, error) +} + +// Parse validates every argument before Run reads configuration or connects +// to PostgreSQL. +func Parse(args []string) (Command, error) { + if len(args) == 0 || args[0] != "attest" { + return Command{}, errors.New(usage) + } + flags := flag.NewFlagSet("assessment-category-attest attest", flag.ContinueOnError) + flags.SetOutput(io.Discard) + specialization := flags.String("specialization", "", "specialization code") + grade := flags.String("grade", "", "grade code") + language := flags.String("task-language", "", "task language code") + actor := flags.String("actor", "", "operator handle") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + command := Command{ + Specialization: domain.SpecializationCode(strings.TrimSpace(*specialization)), + Grade: domain.GradeCode(strings.TrimSpace(*grade)), + Actor: strings.TrimSpace(*actor), + } + if !command.Specialization.IsKnown() { + return Command{}, errors.New("specialization must be a known specialization code") + } + if !command.Grade.IsKnown() { + return Command{}, errors.New("grade must be intern, junior, middle, or senior") + } + if trimmed := strings.TrimSpace(*language); trimmed != "" { + taskLanguage := domain.TaskLanguageCode(trimmed) + if !taskLanguage.IsKnown() { + return Command{}, errors.New("task language must be a known task language code") + } + command.TaskLanguage = &taskLanguage + } + if _, err := domain.ParseAssessmentOperator(command.Actor); err != nil { + return Command{}, errors.New("actor must be operator:") + } + return command, nil +} + +// Run parses the command, loads only DATABASE_URL from the supplied +// environment, and executes the attestation. It does not load dotenv files. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil { + return errors.New("category attestation command dependencies are required") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + attestor, err := assessment.NewCategoryAttestor(postgres.NewTransactor(pool)) + if err != nil { + return errors.New("category attestation is unavailable") + } + return Execute(ctx, command, attestor, output) +} + +// Execute stores the attestation and prints identifiers and versions only; it +// prints no candidate, answer, or contact data. +func Execute(ctx context.Context, command Command, attestor Attestor, output io.Writer) error { + if attestor == nil || output == nil { + return errors.New("category attestation command dependencies are required") + } + if _, err := io.WriteString(output, syntheticOnlyWarning); err != nil { + return errors.New("could not write the result") + } + attestation, err := attestor.Attest(ctx, command.Specialization, command.Grade, command.TaskLanguage, command.Actor) + if err != nil { + return safeOperationError(err) + } + status := "already attested" + if attestation.Created { + status = "attested" + } + if _, err := fmt.Fprintf(output, + "%s: category %s, opening %s, review %s, policy_version %d, by %s\n"+ + "note: synthetic demonstration only; categories are assigned only while ASSESSMENT_DEMO_CATEGORIES_ENABLED is true on this stand\n", + status, attestation.Category, attestation.OpeningID, attestation.ReviewID, attestation.ProductPolicyVersion, attestation.ReviewedBy, + ); err != nil { + return errors.New("could not write the result") + } + return nil +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, outbound.ErrAssessmentSelectionUnavailable), errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous): + return errors.New("no single current reviewed category matches the request") + case errors.Is(err, domain.ErrInvalidAssessmentCategory): + return errors.New("the request is invalid or the current policy is not the explicit demo_basic demonstration policy") + default: + return errors.New("category attestation failed") + } +} diff --git a/backend/internal/adapter/primary/cli/categoryattest/command_test.go b/backend/internal/adapter/primary/cli/categoryattest/command_test.go new file mode 100644 index 0000000..7a5ba2e --- /dev/null +++ b/backend/internal/adapter/primary/cli/categoryattest/command_test.go @@ -0,0 +1,120 @@ +package categoryattest + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" +) + +type attestorFake struct { + attestation assessment.CategoryAttestation + err error + calls int + command Command +} + +func (attestor *attestorFake) Attest( + _ context.Context, + specialization domain.SpecializationCode, + grade domain.GradeCode, + language *domain.TaskLanguageCode, + actor string, +) (assessment.CategoryAttestation, error) { + attestor.calls++ + attestor.command = Command{Specialization: specialization, Grade: grade, TaskLanguage: language, Actor: actor} + return attestor.attestation, attestor.err +} + +func TestParseRequiresATrackAndAnOperatorHandle(t *testing.T) { + command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:night"}) + if err != nil || command.Specialization != domain.SpecializationBackend || command.Grade != domain.GradeIntern || + command.TaskLanguage == nil || *command.TaskLanguage != domain.TaskLanguageGo || command.Actor != "operator:night" { + t.Fatalf("Parse(valid) = %+v, %v", command, err) + } + if command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night"}); err != nil || command.TaskLanguage != nil { + t.Fatalf("Parse(without language) = %+v, %v", command, err) + } + for _, args := range [][]string{ + nil, + {"list"}, + {"attest"}, + {"attest", "--specialization", "backend", "--grade", "junior"}, + {"attest", "--specialization", "backend", "--grade", "junior", "--actor", "alice"}, + {"attest", "--specialization", "chef", "--grade", "junior", "--actor", "operator:night"}, + {"attest", "--specialization", "backend", "--grade", "lead", "--actor", "operator:night"}, + {"attest", "--specialization", "backend", "--grade", "junior", "--task-language", "cobol", "--actor", "operator:night"}, + {"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night", "extra"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) { + lookup := func(string) (string, bool) { + t.Fatal("environment read before arguments were validated") + return "", false + } + if err := Run(context.Background(), []string{"attest"}, lookup, &bytes.Buffer{}); err == nil { + t.Fatal("Run(invalid arguments) succeeded") + } + var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false } + err := Run(context.Background(), []string{"attest", "--specialization", "backend", "--grade", "intern", "--actor", "operator:night"}, noDatabase, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") { + t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err) + } +} + +func TestExecutePrintsIdentifiersAndTheSyntheticOnlyNote(t *testing.T) { + attestor := &attestorFake{attestation: assessment.CategoryAttestation{ + ReviewID: uuid.New(), OpeningID: uuid.New(), Category: "backend-intern", ProductPolicyVersion: 2, + ReviewedBy: "operator:night", Created: true, + }} + var output bytes.Buffer + command := Command{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Actor: "operator:night"} + if err := Execute(context.Background(), command, attestor, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !strings.HasPrefix(output.String(), "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand") { + t.Errorf("output does not start with the synthetic-only warning:\n%s", output.String()) + } + for _, want := range []string{"attested: category backend-intern", attestor.attestation.ReviewID.String(), "policy_version 2", "by operator:night", "synthetic demonstration only", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"} { + if !strings.Contains(output.String(), want) { + t.Errorf("output lacks %q:\n%s", want, output.String()) + } + } + attestor.attestation.Created = false + output.Reset() + if err := Execute(context.Background(), command, attestor, &output); err != nil || !strings.Contains(output.String(), "\nalready attested") { + t.Fatalf("Execute(repeat) = %v, %q, want an already attested line", err, output.String()) + } + if attestor.calls != 2 || attestor.command.Actor != "operator:night" || attestor.command.Grade != domain.GradeIntern { + t.Fatalf("attestor calls/command = %d/%+v, want the parsed request", attestor.calls, attestor.command) + } +} + +func TestExecuteMapsFailuresToSafeMessages(t *testing.T) { + for _, test := range []struct { + err error + want string + }{ + {outbound.ErrAssessmentSelectionUnavailable, "no single current reviewed category"}, + {domain.ErrInvalidAssessmentCategory, "demo_basic"}, + {errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "attestation failed"}, + } { + err := Execute(context.Background(), Command{}, &attestorFake{err: test.err}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") { + t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want) + } + } +} diff --git a/backend/internal/adapter/primary/cli/demoseed/command.go b/backend/internal/adapter/primary/cli/demoseed/command.go new file mode 100644 index 0000000..8bef964 --- /dev/null +++ b/backend/internal/adapter/primary/cli/demoseed/command.go @@ -0,0 +1,332 @@ +// Package demoseed implements the local operator command of the isolated +// demonstration stand: it seeds the synthetic demo world, checks whether the +// stand's database may be discarded by a reset, and prints an inventory of +// counts. Every subcommand requires DEMO_MODE=isolated, and the command never +// deletes anything; the reset itself is a deploy target that discards the +// dedicated demo Compose project after this check. +package demoseed + +import ( + "context" + "crypto/rand" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/argon2id" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/candidateprivacy" + "lincodex/backend/internal/usecase/consent" + seedusecase "lincodex/backend/internal/usecase/demoseed" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/profile" + "lincodex/backend/internal/usecase/questionnaire" +) + +const ( + usage = "usage: demo-seed seed --actor operator: | demo-seed check-reset | demo-seed inventory" + + // DemoModeName and IsolatedDemoMode are the explicit guard of the command. + DemoModeName = "DEMO_MODE" + IsolatedDemoMode = "isolated" + // PasswordName holds the shared password of the synthetic accounts. It + // comes from the demo env file and is never printed. + PasswordName = "DEMO_ACCOUNT_PASSWORD" //nolint:gosec // The name of an environment variable, not a credential. + + // poolSize covers the seed's sequential transactions and the nested + // reads of the services it drives. + poolSize = 4 + // hashConcurrency is one Argon2id derivation at a time; the seed creates a + // handful of accounts once. + hashConcurrency = 1 + // ephemeralKeyBytes is the size of the per-run idempotency secret. The + // seed is idempotent by the state it reads, so its idempotency records + // need no key shared with the backend. + ephemeralKeyBytes = 48 +) + +const syntheticWarning = "warning: synthetic demonstration data for an isolated demo stand only; never on a stand with real people\n" + +// Subcommand names one action. +type Subcommand string + +const ( + SubcommandSeed Subcommand = "seed" + SubcommandCheckReset Subcommand = "check-reset" + SubcommandInventory Subcommand = "inventory" +) + +// Command is a parsed, validated request. +type Command struct { + Subcommand Subcommand + Actor domain.AssessmentOperator +} + +// Parse validates every argument before Run reads configuration or connects. +func Parse(args []string) (Command, error) { + if len(args) == 0 { + return Command{}, errors.New(usage) + } + switch Subcommand(args[0]) { + case SubcommandCheckReset, SubcommandInventory: + if len(args) != 1 { + return Command{}, errors.New(usage) + } + return Command{Subcommand: Subcommand(args[0])}, nil + case SubcommandSeed: + default: + return Command{}, errors.New(usage) + } + flags := flag.NewFlagSet("demo-seed seed", flag.ContinueOnError) + flags.SetOutput(io.Discard) + actor := flags.String("actor", "", "operator handle") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + operator, err := domain.ParseAssessmentOperator(strings.TrimSpace(*actor)) + if err != nil { + return Command{}, errors.New("actor must be operator:") + } + return Command{Subcommand: SubcommandSeed, Actor: operator}, nil +} + +// settings are the validated environment values of one run. +type settings struct { + databaseURL string + password domain.Password +} + +// readSettings checks the demo mode guard, DATABASE_URL, and, for the seed, +// the account password, all before any connection. It loads no dotenv file. +func readSettings(command Command, lookup config.LookupEnv) (settings, error) { + mode, _ := lookup(DemoModeName) + if strings.TrimSpace(mode) != IsolatedDemoMode { + return settings{}, errors.New("DEMO_MODE=isolated is required; the demo seed runs only on an isolated demo stand") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return settings{}, errors.New("DATABASE_URL is not set") + } + result := settings{databaseURL: databaseURL} + if command.Subcommand != SubcommandSeed { + return result, nil + } + raw, _ := lookup(PasswordName) + password, err := domain.NewPassword(raw) + if err != nil { + return settings{}, fmt.Errorf("%s must be a password of at least %d characters", PasswordName, domain.MinNewPasswordCodePoints) + } + result.password = password + return result, nil +} + +// Run parses the command, validates the environment, connects, and executes. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil || clock == nil { + return errors.New("demo seed command dependencies are required") + } + values, err := readSettings(command, lookup) + if err != nil { + return err + } + if _, err := io.WriteString(output, syntheticWarning); err != nil { + return errors.New("could not write the result") + } + pool, err := postgres.NewSizedPool(ctx, values.databaseURL, poolSize) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + store := postgres.NewDemoSeedStore(pool) + inspector, err := seedusecase.NewInspector(store) + if err != nil { + return errors.New("demo seed is unavailable") + } + switch command.Subcommand { + case SubcommandCheckReset: + return ExecuteCheckReset(ctx, inspector, output) + case SubcommandInventory: + return ExecuteInventory(ctx, inspector, output) + case SubcommandSeed: + seeder, err := newSeeder(pool, store, clock) + if err != nil { + return errors.New("demo seed is unavailable") + } + return ExecuteSeed(ctx, seeder, seedusecase.Input{Actor: command.Actor, Password: values.password}, output) + } + return errors.New(usage) +} + +// newSeeder wires the product services the seed drives. Synthetic category +// assignment is on because the command runs only with DEMO_MODE=isolated. +func newSeeder(pool *pgxpool.Pool, store outbound.DemoSeedStore, clock func() time.Time) (*seedusecase.Seeder, error) { + transactor := postgres.NewTransactor(pool) + hasher, err := argon2id.NewHasher(hashConcurrency) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create hasher: %w", err) + } + secret := make([]byte, ephemeralKeyBytes) + if _, err := rand.Read(secret); err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - draw idempotency secret: %w", err) + } + keyring, err := identity.NewKeyring(secret) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create keyring: %w", err) + } + attempts, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock, + assessment.AssessmentCategoryDecisionSettings{SyntheticDemoAssignmentsEnabled: true}) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create attempt service: %w", err) + } + privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: clock}) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create privacy service: %w", err) + } + attestor, err := assessment.NewCategoryAttestor(transactor) + if err != nil { + return nil, fmt.Errorf("demoseed.newSeeder - create attestor: %w", err) + } + return seedusecase.NewSeeder(seedusecase.Dependencies{ + Transactor: transactor, Store: store, Hasher: hasher, + Consents: consent.NewService(transactor, clock), + Profiles: profile.NewService(transactor, clock), + Questionnaires: questionnaire.NewService(transactor, clock), + Privacy: privacy, Attempts: attempts, + Bank: assessment.NewBank(transactor), Attestor: attestor, Clock: clock, + }) +} + +// Seeder runs the seed. +type Seeder interface { + Seed(ctx context.Context, input seedusecase.Input) (seedusecase.Report, error) +} + +// ExecuteSeed seeds and prints what was created, the logins, and the +// prepared attempts. It prints synthetic addresses and identifiers only; the +// password stays in the demo env file. +func ExecuteSeed(ctx context.Context, seeder Seeder, input seedusecase.Input, output io.Writer) error { + if seeder == nil || output == nil { + return errors.New("demo seed command dependencies are required") + } + report, err := seeder.Seed(ctx, input) + if err != nil { + return safeSeedError(err) + } + var text strings.Builder + fmt.Fprintf(&text, "seeded: product policy version %d; created %d records, found %d already present\n", + report.PolicyVersion, len(report.Created), len(report.Present)) + for _, item := range report.Created { + fmt.Fprintf(&text, "created: %s\n", item) + } + for _, item := range report.Updated { + fmt.Fprintf(&text, "updated: %s\n", item) + } + for _, login := range report.Logins { + fmt.Fprintf(&text, "login: %s (%s)\n", login.Email, login.Role) + } + text.WriteString("password: the " + PasswordName + " value of the demo env file; it is not printed\n") + for _, prepared := range report.PreparedAttempts { + fmt.Fprintf(&text, "prepared full attempt: %s of %s\n", prepared.AttemptID, prepared.Email) + } + text.WriteString("note: the prepared attempts were answered by the seed through the ordinary attempt operations; " + + "they are synthetic and no person took them. The express mode has its own policy section and bank and never assigns a category.\n") + if _, err := io.WriteString(output, text.String()); err != nil { + return errors.New("could not write the result") + } + return nil +} + +func safeSeedError(err error) error { + switch { + case errors.Is(err, seedusecase.ErrStandNotFresh): + return errors.New("the stand holds ordinary accounts and was never seeded; seed only a fresh isolated demo stand") + case errors.Is(err, seedusecase.ErrForeignPolicy): + return errors.New("the product policy is neither the initial demo version nor the seeded one; seed only a fresh isolated demo stand") + case errors.Is(err, seedusecase.ErrAccountConflict): + return errors.New("a demo address belongs to an account the seed did not create; reset the isolated demo stand") + case errors.Is(err, seedusecase.ErrPreparedAttemptFailed): + return errors.New("a prepared attempt did not assign its demonstration category; reset the isolated demo stand") + case errors.Is(err, outbound.ErrPolicyVersionNotFound): + return errors.New("the product policy has no version yet; start the backend once so that it seeds the demo policy") + default: + return errors.New("demo seed failed") + } +} + +// Inspector reads the census and the inventory. +type Inspector interface { + CheckReset(ctx context.Context) (seedusecase.ResetCheck, error) + Inventory(ctx context.Context) (outbound.DemoInventory, error) +} + +// ExecuteCheckReset prints the verdict and fails when the database holds an +// account outside the synthetic domain, so the reset target stops before it +// discards anything. +func ExecuteCheckReset(ctx context.Context, inspector Inspector, output io.Writer) error { + if inspector == nil || output == nil { + return errors.New("demo seed command dependencies are required") + } + check, err := inspector.CheckReset(ctx) + if err != nil { + return errors.New("reset check failed") + } + if !check.Verdict.Allowed() { + return fmt.Errorf("reset refused: the stand holds %d accounts outside @%s; the reset never deletes ordinary data", + check.Census.Ordinary(), seedusecase.SyntheticDomain) + } + if _, err := fmt.Fprintf(output, "reset allowed (%s): %d accounts, all on @%s\n", + check.Verdict, check.Census.Total, seedusecase.SyntheticDomain); err != nil { + return errors.New("could not write the result") + } + return nil +} + +// ExecuteInventory prints stable key=value counts, so two runs can be +// compared line by line. +func ExecuteInventory(ctx context.Context, inspector Inspector, output io.Writer) error { + if inspector == nil || output == nil { + return errors.New("demo seed command dependencies are required") + } + inventory, err := inspector.Inventory(ctx) + if err != nil { + return errors.New("inventory failed") + } + lines := []struct { + name string + value int64 + }{ + {"synthetic_accounts", inventory.SyntheticAccounts}, {"verified_synthetic_accounts", inventory.VerifiedSynthetic}, + {"ordinary_accounts", inventory.OrdinaryAccounts}, {"organizations", inventory.Organizations}, + {"memberships", inventory.Memberships}, {"consent_records", inventory.ConsentRecords}, + {"candidate_profiles", inventory.CandidateProfiles}, {"questionnaires", inventory.Questionnaires}, + {"attempts", inventory.Attempts}, {"attempt_results", inventory.AttemptResults}, + {"current_categories", inventory.CurrentCategories}, {"evidence_facts", inventory.EvidenceFacts}, + {"published_cards", inventory.PublishedCards}, {"product_policy_versions", inventory.ProductPolicyVersions}, + {"published_families", inventory.PublishedFamilies}, {"category_openings", inventory.CategoryOpenings}, + {"category_attestations", inventory.CategoryAttestations}, {"training_bindings", inventory.TrainingBindings}, + } + var text strings.Builder + for _, line := range lines { + fmt.Fprintf(&text, "%s=%d\n", line.name, line.value) + } + if _, err := io.WriteString(output, text.String()); err != nil { + return errors.New("could not write the result") + } + return nil +} diff --git a/backend/internal/adapter/primary/cli/demoseed/command_test.go b/backend/internal/adapter/primary/cli/demoseed/command_test.go new file mode 100644 index 0000000..3b10f87 --- /dev/null +++ b/backend/internal/adapter/primary/cli/demoseed/command_test.go @@ -0,0 +1,175 @@ +package demoseed + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + seedusecase "lincodex/backend/internal/usecase/demoseed" +) + +func TestParseAcceptsOnlyTheThreeSubcommands(t *testing.T) { + command, err := Parse([]string{"seed", "--actor", "operator:night"}) + if err != nil || command.Subcommand != SubcommandSeed || command.Actor != "operator:night" { + t.Fatalf("Parse(seed) = %+v, %v", command, err) + } + for _, args := range [][]string{{"check-reset"}, {"inventory"}} { + if command, err := Parse(args); err != nil || string(command.Subcommand) != args[0] { + t.Errorf("Parse(%v) = %+v, %v", args, command, err) + } + } + for _, args := range [][]string{ + nil, {"reset"}, {"seed"}, {"seed", "--actor", "alice"}, {"seed", "--actor", "system:demo-seed"}, + {"seed", "--actor", "operator:night", "extra"}, {"check-reset", "--force"}, {"inventory", "all"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func lookupOf(values map[string]string) func(string) (string, bool) { + return func(key string) (string, bool) { + value, ok := values[key] + return value, ok + } +} + +func TestRunRefusesWithoutTheIsolatedModeBeforeReadingAnythingElse(t *testing.T) { + for _, mode := range []string{"", "production", "ISOLATED", "isolated-ish"} { + values := map[string]string{"DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "a long synthetic password"} + if mode != "" { + values[DemoModeName] = mode + } + var output bytes.Buffer + err := Run(context.Background(), []string{"check-reset"}, lookupOf(values), &output, time.Now) + if err == nil || !strings.Contains(err.Error(), "DEMO_MODE=isolated") || output.Len() != 0 { + t.Errorf("Run with DEMO_MODE=%q = %v, output %q; want a refusal before any output", mode, err, output.String()) + } + } + err := Run(context.Background(), []string{"seed", "--actor", "operator:night"}, + lookupOf(map[string]string{DemoModeName: IsolatedDemoMode, "DATABASE_URL": "postgres://unreachable.invalid/none", PasswordName: "short"}), + &bytes.Buffer{}, time.Now) + if err == nil || !strings.Contains(err.Error(), PasswordName) || strings.Contains(err.Error(), "short") { + t.Fatalf("Run(seed, short password) = %v, want a refusal that does not echo the value", err) + } + err = Run(context.Background(), []string{"inventory"}, lookupOf(map[string]string{DemoModeName: IsolatedDemoMode}), &bytes.Buffer{}, time.Now) + if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") { + t.Fatalf("Run(inventory) without a database = %v", err) + } +} + +type seederFake struct { + report seedusecase.Report + err error +} + +func (fake seederFake) Seed(context.Context, seedusecase.Input) (seedusecase.Report, error) { + return fake.report, fake.err +} + +func TestExecuteSeedPrintsLoginsAndAttemptsButNeverThePassword(t *testing.T) { + attemptID, err := domain.NewAssessmentAttemptID() + if err != nil { + t.Fatalf("NewAssessmentAttemptID() error = %v", err) + } + report := seedusecase.Report{ + PolicyVersion: 2, Created: []string{"account candidate@demo.lincodex.test"}, + Logins: []seedusecase.Login{{Email: "candidate@demo.lincodex.test", Role: "candidate"}}, + PreparedAttempts: []seedusecase.PreparedAttempt{{Email: "prepared-1@demo.lincodex.test", AttemptID: attemptID}}, + } + var output bytes.Buffer + password, err := domain.NewPassword("a long synthetic password") + if err != nil { + t.Fatalf("NewPassword() error = %v", err) + } + if err := ExecuteSeed(context.Background(), seederFake{report: report}, seedusecase.Input{Password: password}, &output); err != nil { + t.Fatalf("ExecuteSeed() error = %v", err) + } + text := output.String() + for _, want := range []string{ + "created 1 records, found 0", "login: candidate@demo.lincodex.test", "prepared full attempt: " + attemptID.String(), + "no person took them", "never assigns a category", + } { + if !strings.Contains(text, want) { + t.Errorf("output lacks %q:\n%s", want, text) + } + } + if strings.Contains(text, "a long synthetic password") { + t.Fatal("the output contains the password") + } + for _, test := range []struct { + err error + want string + }{ + {seedusecase.ErrStandNotFresh, "never seeded"}, + {seedusecase.ErrForeignPolicy, "neither the initial demo version"}, + {seedusecase.ErrAccountConflict, "did not create"}, + {seedusecase.ErrPreparedAttemptFailed, "did not assign"}, + {outbound.ErrPolicyVersionNotFound, "no version yet"}, + {errors.New("pq: password authentication failed for user x"), "demo seed failed"}, + } { + err := ExecuteSeed(context.Background(), seederFake{err: test.err}, seedusecase.Input{}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "authentication") { + t.Errorf("ExecuteSeed(%v) = %v, want a safe message containing %q", test.err, err, test.want) + } + } +} + +type inspectorFake struct { + census outbound.DemoAccountCensus + err error +} + +func (fake inspectorFake) CheckReset(context.Context) (seedusecase.ResetCheck, error) { + return seedusecase.ResetCheck{Verdict: seedusecase.DecideReset(fake.census), Census: fake.census}, fake.err +} + +func (fake inspectorFake) Inventory(context.Context) (outbound.DemoInventory, error) { + return outbound.DemoInventory{SyntheticAccounts: fake.census.Synthetic, OrdinaryAccounts: fake.census.Ordinary()}, fake.err +} + +func TestExecuteCheckResetFailsOnOrdinaryAccounts(t *testing.T) { + for _, test := range []struct { + census outbound.DemoAccountCensus + want string + fails bool + }{ + {outbound.DemoAccountCensus{}, "reset allowed (empty)", false}, + {outbound.DemoAccountCensus{Total: 9, Synthetic: 9}, "reset allowed (synthetic): 9 accounts", false}, + {outbound.DemoAccountCensus{Total: 10, Synthetic: 9}, "holds 1 accounts outside", true}, + {outbound.DemoAccountCensus{Total: 1}, "holds 1 accounts outside", true}, + } { + var output bytes.Buffer + err := ExecuteCheckReset(context.Background(), inspectorFake{census: test.census}, &output) + if test.fails != (err != nil) { + t.Fatalf("ExecuteCheckReset(%+v) = %v, want failure %v", test.census, err, test.fails) + } + text := output.String() + if err != nil { + text = err.Error() + } + if !strings.Contains(text, test.want) { + t.Errorf("ExecuteCheckReset(%+v) said %q, want %q", test.census, text, test.want) + } + } + if err := ExecuteCheckReset(context.Background(), inspectorFake{err: errors.New("connection reset")}, &bytes.Buffer{}); err == nil || + err.Error() != "reset check failed" { + t.Fatalf("ExecuteCheckReset(store failure) = %v, want a refusal", err) + } +} + +func TestExecuteInventoryPrintsStableCounts(t *testing.T) { + var output bytes.Buffer + if err := ExecuteInventory(context.Background(), inspectorFake{census: outbound.DemoAccountCensus{Total: 10, Synthetic: 9}}, &output); err != nil { + t.Fatalf("ExecuteInventory() error = %v", err) + } + if !strings.HasPrefix(output.String(), "synthetic_accounts=9\nverified_synthetic_accounts=0\nordinary_accounts=1\n") { + t.Fatalf("inventory = %q", output.String()) + } +} diff --git a/backend/internal/adapter/primary/cli/leaktrace/command.go b/backend/internal/adapter/primary/cli/leaktrace/command.go new file mode 100644 index 0000000..ab36fac --- /dev/null +++ b/backend/internal/adapter/primary/cli/leaktrace/command.go @@ -0,0 +1,182 @@ +// Package leaktrace implements the local operator command that finds the +// assessment attempt behind a leaked task text. It takes text: a screenshot has +// to be read by an OCR tool first, which is outside this command. Every search +// is recorded in an audit table before a result is printed. The result is a hint +// for a manual review and an appeal: it is never shown to an employer and never +// changes a score, a category, or a quota. +package leaktrace + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/identity" +) + +const usage = "usage: assessment-leak-trace search --actor operator: (--file | --stdin) [--code XXXXX-XXXXX]" + +// maxInputBytes is the largest text the command reads. It is one byte above the +// limit of the usecase, so an oversize text is refused instead of cut. +const maxInputBytes = 64<<10 + 1 + +// Command is a parsed, validated search. +type Command struct { + Actor string + // File is the path of the leaked text; empty when the text comes from stdin. + File string + Stdin bool + // Code is a visible code that the operator read from a screenshot by eye. + Code string +} + +// Tracer finds the attempt behind a text and records the search. +type Tracer interface { + Trace(ctx context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error) +} + +// Parse validates every argument before Run reads configuration or connects to +// PostgreSQL. +func Parse(args []string) (Command, error) { + if len(args) == 0 || args[0] != "search" { + return Command{}, errors.New(usage) + } + flags := flag.NewFlagSet("assessment-leak-trace search", flag.ContinueOnError) + flags.SetOutput(io.Discard) + actor := flags.String("actor", "", "operator handle") + file := flags.String("file", "", "file with the leaked text") + stdin := flags.Bool("stdin", false, "read the leaked text from standard input") + code := flags.String("code", "", "visible code read from a screenshot") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + if _, err := domain.ParseAssessmentReviewActor(strings.TrimSpace(*actor)); err != nil { + return Command{}, errors.New("actor must be operator:") + } + if *file != "" && *stdin { + return Command{}, errors.New("give the text with --file or --stdin, not both") + } + if *file == "" && !*stdin && strings.TrimSpace(*code) == "" { + return Command{}, errors.New("give the leaked text with --file or --stdin, or a visible code with --code") + } + if strings.TrimSpace(*code) != "" { + if _, err := domain.ParseAssessmentWatermarkCode(*code); err != nil { + return Command{}, errors.New("code must be a watermark code of two groups of five characters, such as 7K3QD-9XM2T") + } + } + return Command{Actor: strings.TrimSpace(*actor), File: *file, Stdin: *stdin, Code: strings.TrimSpace(*code)}, nil +} + +// Run parses the command, loads only DATABASE_URL and IDENTITY_KEY_SECRET from +// the supplied environment, and executes the search. It does not load dotenv +// files. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, stdin io.Reader, output io.Writer) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || stdin == nil || output == nil { + return errors.New("leak trace command dependencies are required") + } + text, err := readText(command, stdin) + if err != nil { + return err + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + secret, err := config.IdentityKeySecretFromEnv(lookup) + if err != nil { + return errors.New("IDENTITY_KEY_SECRET must be the secret of the server that served the attempts") + } + keyring, err := identity.NewKeyring(secret) + if err != nil { + return errors.New("IDENTITY_KEY_SECRET is invalid") + } + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + tracer, err := assessment.NewLeakTracer(postgres.NewTransactor(pool), keyring, keyring) + if err != nil { + return errors.New("leak trace is unavailable") + } + return Execute(ctx, command, text, tracer, output) +} + +func readText(command Command, stdin io.Reader) (string, error) { + var reader io.Reader + switch { + case command.File != "": + file, err := os.Open(command.File) + if err != nil { + return "", errors.New("the text file cannot be opened") + } + defer func() { _ = file.Close() }() + reader = file + case command.Stdin: + reader = stdin + default: + return "", nil + } + text, err := io.ReadAll(io.LimitReader(reader, maxInputBytes)) + if err != nil { + return "", errors.New("the text cannot be read") + } + return string(text), nil +} + +// Execute runs the search and prints the outcome. The output names the outcome, +// the method, the attempt, the strength of the evidence, and fixed notes about +// it. It never prints the leaked text and no data of the candidate. +func Execute(ctx context.Context, command Command, text string, tracer Tracer, output io.Writer) error { + if tracer == nil || output == nil { + return errors.New("leak trace command dependencies are required") + } + result, err := tracer.Trace(ctx, assessment.LeakTraceCommand{Actor: command.Actor, Text: text, Code: command.Code}) + if err != nil { + return safeOperationError(err) + } + var builder strings.Builder + fmt.Fprintf(&builder, "search: %s\nresult: %s\n", result.SearchID, result.Status) + if result.Status == domain.AssessmentLeakTraceFound { + fmt.Fprintf(&builder, "method: %s\nattempt: %s\nevidence_bits: %d\n", result.Method, result.AttemptID, result.EvidenceBits) + } + fmt.Fprintf(&builder, "candidates: %d\n", result.Candidates) + for _, note := range result.Notes { + fmt.Fprintf(&builder, "note: %s\n", note) + } + builder.WriteString("note: a hint for a manual review and an appeal; it changes no score, category, or quota, " + + "and an employer never sees it. The search is recorded in the audit.\n") + if result.Status == domain.AssessmentLeakTraceNotFound { + builder.WriteString("note: not found is an honest answer: the data is not enough to name an attempt.\n") + } + if _, err := io.WriteString(output, builder.String()); err != nil { + return errors.New("could not write the result") + } + return nil +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, assessment.ErrInvalidLeakTrace): + return errors.New("the text or the code cannot be searched (empty, not valid UTF-8, or longer than 64 KiB)") + case errors.Is(err, domain.ErrInvalidAssessmentReview): + return errors.New("actor is invalid") + default: + return errors.New("assessment leak trace operation failed") + } +} diff --git a/backend/internal/adapter/primary/cli/leaktrace/command_test.go b/backend/internal/adapter/primary/cli/leaktrace/command_test.go new file mode 100644 index 0000000..460c0b7 --- /dev/null +++ b/backend/internal/adapter/primary/cli/leaktrace/command_test.go @@ -0,0 +1,187 @@ +package leaktrace + +import ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/assessment" +) + +type tracerFake struct { + result assessment.LeakTraceResult + err error + command assessment.LeakTraceCommand + calls int +} + +func (tracer *tracerFake) Trace(_ context.Context, command assessment.LeakTraceCommand) (assessment.LeakTraceResult, error) { + tracer.calls++ + tracer.command = command + return tracer.result, tracer.err +} + +func TestParseTakesTheTextFromAFileOrStandardInputAndAnOperatorHandle(t *testing.T) { + command, err := Parse([]string{"search", "--actor", "operator:night", "--file", "leak.txt"}) + if err != nil || command.File != "leak.txt" || command.Actor != "operator:night" || command.Stdin { + t.Fatalf("Parse(file) = %+v, %v", command, err) + } + command, err = Parse([]string{"search", "--actor", "operator:night", "--stdin", "--code", "7k3qd 9xm2t"}) + if err != nil || !command.Stdin || command.Code != "7k3qd 9xm2t" { + t.Fatalf("Parse(stdin and code) = %+v, %v", command, err) + } + // A code read from a screenshot by eye is enough on its own. + if _, err := Parse([]string{"search", "--actor", "operator:night", "--code", "7K3QD-9XM2T"}); err != nil { + t.Fatalf("Parse(code only) error = %v", err) + } + for _, args := range [][]string{ + nil, + {"find"}, + {"search"}, + {"search", "--file", "leak.txt"}, + {"search", "--actor", "alice", "--file", "leak.txt"}, + {"search", "--actor", "operator:night"}, + {"search", "--actor", "operator:night", "--file", "leak.txt", "--stdin"}, + {"search", "--actor", "operator:night", "--code", "NOT A CODE"}, + {"search", "--actor", "operator:night", "--file", "leak.txt", "extra"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func TestRunValidatesArgumentsBeforeReadingTheEnvironmentAndNeverEchoesTheSecret(t *testing.T) { + lookup := func(string) (string, bool) { + t.Fatal("environment read before arguments were validated") + return "", false + } + if err := Run(context.Background(), []string{"search"}, lookup, strings.NewReader(""), &bytes.Buffer{}); err == nil { + t.Fatal("Run(invalid arguments) succeeded") + } + args := []string{"search", "--actor", "operator:night", "--stdin"} + var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false } + if err := Run(context.Background(), args, noDatabase, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "DATABASE_URL") { + t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err) + } + // A secret that the server could not have used makes every code unreadable, so the command refuses it. + const shortSecret = "too-short-secret" + var weakSecret config.LookupEnv = func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return "postgres://operator@localhost/lincodex", true + case "IDENTITY_KEY_SECRET": + return shortSecret, true + default: + return "", false + } + } + err := Run(context.Background(), args, weakSecret, strings.NewReader("leaked text"), &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") || strings.Contains(err.Error(), shortSecret) { + t.Fatalf("Run(weak secret) error = %v, want a message that does not echo the secret", err) + } + var noSecret config.LookupEnv = func(key string) (string, bool) { + if key == "DATABASE_URL" { + return "postgres://operator@localhost/lincodex", true + } + return "", false + } + if err := Run(context.Background(), args, noSecret, strings.NewReader("leaked text"), &bytes.Buffer{}); err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET") { + t.Fatalf("Run(no secret) error = %v, want an IDENTITY_KEY_SECRET message", err) + } +} + +func TestTheTextIsReadFromAFileOrStandardInputWithinTheLimit(t *testing.T) { + path := filepath.Join(t.TempDir(), "leak.txt") + if err := os.WriteFile(path, []byte("text from a file"), 0o600); err != nil { + t.Fatalf("write fixture: %v", err) + } + fromFile, err := readText(Command{File: path}, strings.NewReader("ignored")) + if err != nil || fromFile != "text from a file" { + t.Fatalf("readText(file) = %q, %v", fromFile, err) + } + fromStdin, err := readText(Command{Stdin: true}, strings.NewReader("text from stdin")) + if err != nil || fromStdin != "text from stdin" { + t.Fatalf("readText(stdin) = %q, %v", fromStdin, err) + } + // One byte above the limit of the usecase is read, so an oversize text is refused and not cut. + oversize, err := readText(Command{Stdin: true}, strings.NewReader(strings.Repeat("a", 1<<20))) + if err != nil || len(oversize) != maxInputBytes { + t.Fatalf("readText(oversize) read %d bytes, %v, want %d", len(oversize), err, maxInputBytes) + } + if _, err := readText(Command{File: filepath.Join(t.TempDir(), "missing.txt")}, strings.NewReader("")); err == nil { + t.Fatal("readText(missing file) succeeded") + } + if text, err := readText(Command{Code: "7K3QD-9XM2T"}, strings.NewReader("ignored")); err != nil || text != "" { + t.Fatalf("readText(code only) = %q, %v, want no text", text, err) + } +} + +func TestExecutePrintsTheOutcomeAndNeverTheLeakedText(t *testing.T) { + const leaked = "SECRET-LEAKED-STATEMENT about a sliding-window limiter" + attemptID := domain.AssessmentAttemptID(uuid.New()) + found := &tracerFake{result: assessment.LeakTraceResult{ + SearchID: uuid.New(), Status: domain.AssessmentLeakTraceFound, Method: domain.AssessmentLeakTraceInvisibleMark, + AttemptID: attemptID, Candidates: 1, EvidenceBits: 50, Notes: []string{"the invisible mark of the statement carries one code"}, + }} + var output bytes.Buffer + if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, found, &output); err != nil { + t.Fatalf("Execute(found) error = %v", err) + } + for _, want := range []string{ + "result: found", "method: invisible_mark", "attempt: " + attemptID.String(), "evidence_bits: 50", "candidates: 1", + "note: the invisible mark of the statement carries one code", "an employer never sees it", "changes no score, category, or quota", + } { + if !strings.Contains(output.String(), want) { + t.Errorf("output lacks %q:\n%s", want, output.String()) + } + } + if strings.Contains(output.String(), "SECRET-LEAKED") || strings.Contains(output.String(), "sliding-window") { + t.Fatalf("the output quotes the leaked text:\n%s", output.String()) + } + if found.command.Actor != "operator:night" || found.command.Text != leaked { + t.Fatalf("command = %+v, want the actor and the text passed on", found.command) + } + + notFound := &tracerFake{result: assessment.LeakTraceResult{ + SearchID: uuid.New(), Status: domain.AssessmentLeakTraceNotFound, Notes: []string{"no statement of any real attempt contains this text"}, + }} + output.Reset() + if err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, notFound, &output); err != nil { + t.Fatalf("Execute(not found) error = %v", err) + } + if !strings.Contains(output.String(), "result: not_found") || !strings.Contains(output.String(), "not found is an honest answer") || + strings.Contains(output.String(), "attempt:") || strings.Contains(output.String(), "method:") { + t.Fatalf("not found output:\n%s", output.String()) + } +} + +func TestExecuteMapsFailuresToSafeMessages(t *testing.T) { + const leaked = "SECRET-LEAKED-STATEMENT" + for name, test := range map[string]struct { + err error + want string + }{ + "a request the usecase refuses": {err: assessment.ErrInvalidLeakTrace, want: "cannot be searched"}, + "an invalid actor": {err: domain.ErrInvalidAssessmentReview, want: "actor is invalid"}, + "a storage failure": {err: errors.New("pq: connection refused for " + leaked), want: "operation failed"}, + } { + t.Run(name, func(t *testing.T) { + err := Execute(context.Background(), Command{Actor: "operator:night", Stdin: true}, leaked, &tracerFake{err: test.err}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), leaked) { + t.Fatalf("Execute() error = %v, want a safe message containing %q", err, test.want) + } + }) + } + if err := Execute(context.Background(), Command{}, "", nil, &bytes.Buffer{}); err == nil { + t.Fatal("Execute() without a tracer succeeded") + } +} diff --git a/backend/internal/adapter/primary/cli/mailretry/command.go b/backend/internal/adapter/primary/cli/mailretry/command.go new file mode 100644 index 0000000..9834756 --- /dev/null +++ b/backend/internal/adapter/primary/cli/mailretry/command.go @@ -0,0 +1,196 @@ +// Package mailretry implements the local operator command for inspecting and +// authorizing a retry of an unknown mail delivery. +package mailretry + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +const usage = "usage: mail-retry inspect --delivery | mail-retry retry --delivery --actor operator: --acknowledge-duplicate-risk" + +type action uint8 + +const ( + inspectAction action = iota + 1 + retryAction +) + +// Command is a parsed, validated local mail retry command. +type Command struct { + Action action + DeliveryID uuid.UUID + Actor string + AcknowledgeDuplicateRisk bool +} + +// Operator is the metadata-only and audit-backed retry usecase. +type Operator interface { + Inspect(ctx context.Context, deliveryID uuid.UUID) (notification.DeliveryRetryInspection, error) + RetryUnknown(ctx context.Context, deliveryID uuid.UUID, actor string, acknowledgeDuplicateRisk bool) (string, error) +} + +// Parse validates every argument before Run reads configuration or connects +// to PostgreSQL. +func Parse(args []string) (Command, error) { + if len(args) == 0 { + return Command{}, errors.New(usage) + } + + var command Command + var actor *string + var acknowledge *bool + switch args[0] { + case "inspect": + command.Action = inspectAction + case "retry": + command.Action = retryAction + default: + return Command{}, errors.New(usage) + } + + flags := flag.NewFlagSet("mail-retry "+args[0], flag.ContinueOnError) + flags.SetOutput(io.Discard) + deliveryID := flags.String("delivery", "", "delivery UUID") + if command.Action == retryAction { + actor = flags.String("actor", "", "operator handle") + acknowledge = flags.Bool("acknowledge-duplicate-risk", false, "acknowledge that a duplicate may be sent") + } + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + parsedID, err := uuid.Parse(strings.TrimSpace(*deliveryID)) + if err != nil || parsedID == uuid.Nil { + return Command{}, errors.New("delivery must be a non-zero UUID") + } + command.DeliveryID = parsedID + if command.Action == retryAction { + if _, err := domain.ParseMailRetryActor(strings.TrimSpace(*actor)); err != nil { + return Command{}, errors.New("actor must be operator:") + } + if !*acknowledge { + return Command{}, errors.New("--acknowledge-duplicate-risk is required") + } + command.Actor = strings.TrimSpace(*actor) + command.AcknowledgeDuplicateRisk = true + } + return command, nil +} + +// Run parses the command, loads only its database and mail-account settings +// from the supplied environment, then executes the operator usecase. It does +// not load dotenv files or read transport credentials. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil { + return errors.New("mail retry command dependencies are required") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + provider := strings.ToLower(strings.TrimSpace(envValue(lookup, "EMAIL_PROVIDER", ""))) + if provider != string(config.EmailProviderResend) { + return errors.New("mail retry is available only with EMAIL_PROVIDER=resend in this build") + } + accountLabel := strings.TrimSpace(envValue(lookup, "EMAIL_ACCOUNT", "default")) + account, err := domain.NewMailProviderAccount(provider, accountLabel) + if err != nil { + return errors.New("mail provider account configuration is invalid") + } + + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + deliveries := postgres.NewDeliveryStore(pool).Deliveries() + operator, err := notification.NewDeliveryRetryOperator( + postgres.NewTransactor(pool), + deliveries, + account, + resend.IdempotencyWindow, + time.Now, + ) + if err != nil { + return errors.New("mail retry is unavailable") + } + return Execute(ctx, command, operator, output) +} + +// Execute prints the duplicate-risk warning before retry authorization can +// mutate the delivery or append an audit decision. +func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error { + if operator == nil || output == nil { + return errors.New("mail retry command dependencies are required") + } + snapshot, err := operator.Inspect(ctx, command.DeliveryID) + if err != nil { + return safeOperationError(err) + } + if command.Action == inspectAction { + if _, err := fmt.Fprintf(output, + "delivery: %s\nprovider: %s\nstatus: %s\nattempts: %d\n%s\n", + snapshot.DeliveryID, snapshot.Provider, snapshot.Status, snapshot.AttemptCount, notification.DuplicateRiskWarning, + ); err != nil { + return errors.New("could not write mail retry inspection") + } + return nil + } + if command.Action != retryAction || !command.AcknowledgeDuplicateRisk { + return errors.New(usage) + } + if _, err := fmt.Fprintln(output, notification.DuplicateRiskWarning); err != nil { + return errors.New("could not write duplicate-risk warning") + } + if _, err := operator.RetryUnknown(ctx, command.DeliveryID, command.Actor, command.AcknowledgeDuplicateRisk); err != nil { + return safeOperationError(err) + } + if _, err := fmt.Fprintln(output, "retry scheduled; audit decision recorded"); err != nil { + return errors.New("retry was scheduled, but the result could not be written") + } + return nil +} + +func envValue(lookup config.LookupEnv, name, fallback string) string { + value, ok := lookup(name) + if !ok || strings.TrimSpace(value) == "" { + return fallback + } + return value +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, outbound.ErrDeliveryNotFound): + return errors.New("delivery not found") + case errors.Is(err, outbound.ErrDeliveryRetryNotAllowed): + return errors.New("delivery is not eligible for manual retry") + case errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired): + return errors.New("duplicate-risk acknowledgement is required") + case errors.Is(err, domain.ErrInvalidDelivery): + return errors.New("delivery or actor is invalid") + default: + return errors.New("mail retry operation failed") + } +} diff --git a/backend/internal/adapter/primary/cli/mailretry/command_test.go b/backend/internal/adapter/primary/cli/mailretry/command_test.go new file mode 100644 index 0000000..17116bd --- /dev/null +++ b/backend/internal/adapter/primary/cli/mailretry/command_test.go @@ -0,0 +1,142 @@ +package mailretry + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +const testDeliveryID = "2e203b62-3fb5-4ef7-b118-360bbff7f2aa" + +func TestParseRequiresExplicitCommandFields(t *testing.T) { + tests := []struct { + name string + args []string + want string + }{ + {name: "command", args: nil, want: "usage:"}, + {name: "unknown command", args: []string{"send"}, want: "usage:"}, + {name: "inspect delivery", args: []string{"inspect"}, want: "non-zero UUID"}, + {name: "invalid delivery", args: []string{"inspect", "--delivery", "not-a-uuid"}, want: "non-zero UUID"}, + {name: "retry delivery", args: []string{"retry", "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk"}, want: "non-zero UUID"}, + {name: "retry actor", args: []string{"retry", "--delivery", testDeliveryID, "--acknowledge-duplicate-risk"}, want: "actor must be"}, + {name: "retry acknowledgement", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, want: "--acknowledge-duplicate-risk is required"}, + {name: "invalid actor", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "mail-ops", "--acknowledge-duplicate-risk"}, want: "actor must be"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := Parse(test.args) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("Parse(%q) error = %v, want text %q", test.args, err, test.want) + } + }) + } +} + +func TestRunValidatesArgumentsBeforeReadingEnvironment(t *testing.T) { + var reads int + err := Run(context.Background(), []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, func(string) (string, bool) { + reads++ + return "", false + }, &bytes.Buffer{}) + if err == nil || reads != 0 { + t.Fatalf("Run() error = %v, environment reads = %d; want argument error before config access", err, reads) + } +} + +func TestRunDoesNotPrintDatabaseURL(t *testing.T) { + const secretURL = "postgres://operator:secret-password@127.0.0.1:1/mail" + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return secretURL, true + case "EMAIL_PROVIDER": + return "resend", true + default: + return "", false + } + } + var output bytes.Buffer + err := Run(context.Background(), []string{"inspect", "--delivery", testDeliveryID}, lookup, &output) + if err == nil || strings.Contains(err.Error(), "secret-password") || strings.Contains(output.String(), "secret-password") { + t.Fatalf("Run() error/output leaked connection details: error %v, output %q", err, output.String()) + } +} + +func TestExecuteWarnsBeforeSchedulingAndRedactsMetadata(t *testing.T) { + deliveryID := uuid.MustParse(testDeliveryID) + var output bytes.Buffer + operator := &testOperator{ + inspection: notification.DeliveryRetryInspection{ + DeliveryID: deliveryID, + Provider: "resend", + ProviderAccount: "sensitive-account-label", + Status: domain.DeliveryStatusUnknown, + AttemptCount: 2, + }, + output: &output, + } + command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true} + if err := Execute(context.Background(), command, operator, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !operator.retryCalled || !strings.Contains(output.String(), notification.DuplicateRiskWarning) || + strings.Contains(output.String(), "sensitive-account-label") { + t.Fatalf("Execute() output/calls = %q, %t; want warning before retry and redacted account", output.String(), operator.retryCalled) + } +} + +func TestExecuteDoesNotScheduleWhenWarningCannotBeWritten(t *testing.T) { + deliveryID := uuid.MustParse(testDeliveryID) + operator := &testOperator{inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown}} + command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true} + if err := Execute(context.Background(), command, operator, errorWriter{}); err == nil || operator.retryCalled { + t.Fatalf("Execute() error = %v, retry called = %t; want output error before mutation", err, operator.retryCalled) + } +} + +func TestExecuteReturnsSafeStateError(t *testing.T) { + deliveryID := uuid.MustParse(testDeliveryID) + operator := &testOperator{ + inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown}, + retryErr: errors.Join(outbound.ErrDeliveryRetryNotAllowed, errors.New("recipient private@example.invalid")), + } + var output bytes.Buffer + command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true} + err := Execute(context.Background(), command, operator, &output) + if err == nil || err.Error() != "delivery is not eligible for manual retry" || strings.Contains(err.Error(), "private@example.invalid") { + t.Fatalf("Execute() error = %v; want a safe state error", err) + } +} + +type testOperator struct { + inspection notification.DeliveryRetryInspection + inspectErr error + retryErr error + output *bytes.Buffer + retryCalled bool +} + +func (operator *testOperator) Inspect(context.Context, uuid.UUID) (notification.DeliveryRetryInspection, error) { + return operator.inspection, operator.inspectErr +} + +func (operator *testOperator) RetryUnknown(context.Context, uuid.UUID, string, bool) (string, error) { + operator.retryCalled = true + if operator.output != nil && !strings.Contains(operator.output.String(), notification.DuplicateRiskWarning) { + return "", errors.New("retry called before warning") + } + return "", operator.retryErr +} + +type errorWriter struct{} + +func (errorWriter) Write([]byte) (int, error) { return 0, errors.New("output unavailable") } diff --git a/backend/internal/adapter/primary/cli/policypublish/command.go b/backend/internal/adapter/primary/cli/policypublish/command.go new file mode 100644 index 0000000..1d56274 --- /dev/null +++ b/backend/internal/adapter/primary/cli/policypublish/command.go @@ -0,0 +1,142 @@ +// Package policypublish implements the local operator command that adds the +// demo matching section, the semantic matching section, or the two-model +// semantic ensemble section to the product policy. Until an administrative policy +// editor exists, this is how a stand gets the coefficients that the match +// search needs: startup seeds only the first demo version. +package policypublish + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +const usage = "usage: policy-publish matching|semantic|semantic-ensemble --actor operator:" + +// Track names which section a command publishes. +type Track string + +const ( + // TrackMatching adds the PRD matching section (Sem weight 0.10). + TrackMatching Track = "matching" + // TrackSemantic adds the semantic matching section (Sem weight 0.5, the + // encoder identity, the calibration, and the explanation thresholds). + TrackSemantic Track = "semantic" + // TrackSemanticEnsemble replaces the semantic section with the two-model + // ensemble (Giga and Qwen3-Embedding) and its calibration; the earlier + // single-model version stays as the previous version. + TrackSemanticEnsemble Track = "semantic-ensemble" +) + +// Command is a parsed, validated request. +type Command struct { + Track Track + Author domain.PolicyAuthor +} + +// Extender publishes the demo matching section. +type Extender interface { + EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) + EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) + EnsureDemoSemanticEnsembleSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) +} + +// Parse validates every argument before Run reads configuration or connects. +func Parse(args []string) (Command, error) { + if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic) && args[0] != string(TrackSemanticEnsemble)) { + return Command{}, errors.New(usage) + } + track := Track(args[0]) + flags := flag.NewFlagSet("policy-publish "+args[0], flag.ContinueOnError) + flags.SetOutput(io.Discard) + actor := flags.String("actor", "", "operator handle") + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + value := strings.TrimSpace(*actor) + author, err := domain.ParsePolicyAuthor(value) + if err != nil || !strings.HasPrefix(value, "operator:") { + return Command{}, errors.New("actor must be operator:") + } + return Command{Track: track, Author: author}, nil +} + +// Run parses the command, loads only DATABASE_URL from the supplied +// environment, and publishes. It does not load dotenv files. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil || clock == nil { + return errors.New("policy publication command dependencies are required") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + return Execute(ctx, command, policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), clock), output) +} + +// Execute publishes the section and prints the version number only. +func Execute(ctx context.Context, command Command, extender Extender, output io.Writer) error { + if extender == nil || output == nil { + return errors.New("policy publication command dependencies are required") + } + publish, section, note := extender.EnsureDemoMatchingSection, "the demo matching section", + "note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n" + switch command.Track { + case TrackSemantic: + publish, section, note = extender.EnsureDemoSemanticMatchingSection, "the semantic matching section", + "note: research-calibrated values (LincodexMatch DEV split), not product measurements; searches use them at once,\n"+ + "and Sem stays neutral for subjects without vectors until the semantic-backfill command has run\n" + case TrackSemanticEnsemble: + publish, section, note = extender.EnsureDemoSemanticEnsembleSection, "the semantic ensemble section (Giga + Qwen3-Embedding)", + "note: research-calibrated values (LincodexMatch DEV split), not product measurements; the ML service must serve both models,\n"+ + "and Sem stays neutral for subjects without Qwen3 vectors until the semantic-backfill command has run\n" + case TrackMatching: + } + result, err := publish(ctx, command.Author) + if err != nil { + return safeOperationError(err) + } + status := "already present" + if result.Created { + status = "published" + } + if _, err := fmt.Fprintf(output, "%s: product policy version %d carries %s\n%s", status, result.Version.Version(), section, note); err != nil { + return errors.New("could not write the result") + } + return nil +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, policy.ErrNotDemoPolicy): + return errors.New("the latest product policy is not a demonstration version; publish the matching section with the calibrated policy instead") + case errors.Is(err, policy.ErrPolicyChanged): + return errors.New("the product policy changed while publishing; run the command again") + case errors.Is(err, outbound.ErrPolicyVersionNotFound): + return errors.New("the product policy has no version yet; start the service once so that it seeds the demo policy") + default: + return errors.New("policy publication failed") + } +} diff --git a/backend/internal/adapter/primary/cli/policypublish/command_test.go b/backend/internal/adapter/primary/cli/policypublish/command_test.go new file mode 100644 index 0000000..381e4f5 --- /dev/null +++ b/backend/internal/adapter/primary/cli/policypublish/command_test.go @@ -0,0 +1,108 @@ +package policypublish + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/policy" +) + +type extenderFake struct { + result policy.MatchingResult + err error + author domain.PolicyAuthor + semantic bool + ensemble bool +} + +func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) { + extender.author = author + return extender.result, extender.err +} + +func (extender *extenderFake) EnsureDemoSemanticMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) { + extender.author = author + extender.semantic = true + return extender.result, extender.err +} + +func (extender *extenderFake) EnsureDemoSemanticEnsembleSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) { + extender.author = author + extender.ensemble = true + return extender.result, extender.err +} + +func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) { + command, err := Parse([]string{"matching", "--actor", "operator:night"}) + if err != nil || command.Author != "operator:night" || command.Track != TrackMatching { + t.Fatalf("Parse(valid) = %+v, %v", command, err) + } + semantic, err := Parse([]string{"semantic", "--actor", "operator:night"}) + if err != nil || semantic.Track != TrackSemantic { + t.Fatalf("Parse(semantic) = %+v, %v", semantic, err) + } + ensemble, err := Parse([]string{"semantic-ensemble", "--actor", "operator:night"}) + if err != nil || ensemble.Track != TrackSemanticEnsemble { + t.Fatalf("Parse(semantic-ensemble) = %+v, %v", ensemble, err) + } + for _, args := range [][]string{ + nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"}, + {"matching", "--actor", "operator:night", "extra"}, + } { + if _, err := Parse(args); err == nil { + t.Errorf("Parse(%v) accepted invalid arguments", args) + } + } +} + +func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T) { + var output bytes.Buffer + extender := &extenderFake{} + if err := Execute(context.Background(), Command{Author: "operator:night"}, extender, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !strings.HasPrefix(output.String(), "already present: product policy version 0") || extender.author != "operator:night" { + t.Fatalf("output = %q, author %q", output.String(), extender.author) + } + for _, test := range []struct { + err error + want string + }{ + {policy.ErrNotDemoPolicy, "not a demonstration version"}, + {outbound.ErrPolicyVersionNotFound, "no version yet"}, + {policy.ErrPolicyChanged, "run the command again"}, + {errors.New("pq: password authentication failed for user x"), "policy publication failed"}, + } { + err := Execute(context.Background(), Command{Author: "operator:night"}, &extenderFake{err: test.err}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "password") { + t.Errorf("Execute(%v) error = %v, want a safe message containing %q", test.err, err, test.want) + } + } +} + +func TestExecuteSemanticTrackPublishesTheSemanticSection(t *testing.T) { + var output bytes.Buffer + extender := &extenderFake{} + if err := Execute(context.Background(), Command{Track: TrackSemantic, Author: "operator:night"}, extender, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !extender.semantic || !strings.Contains(output.String(), "the semantic matching section") { + t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic) + } +} + +func TestExecuteSemanticEnsembleTrackPublishesTheEnsembleSection(t *testing.T) { + var output bytes.Buffer + extender := &extenderFake{} + if err := Execute(context.Background(), Command{Track: TrackSemanticEnsemble, Author: "operator:night"}, extender, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !extender.ensemble || extender.semantic || !strings.Contains(output.String(), "semantic ensemble section") { + t.Fatalf("output = %q, ensemble called %v", output.String(), extender.ensemble) + } +} diff --git a/backend/internal/adapter/primary/cli/semanticbackfill/command.go b/backend/internal/adapter/primary/cli/semanticbackfill/command.go new file mode 100644 index 0000000..cf773e8 --- /dev/null +++ b/backend/internal/adapter/primary/cli/semanticbackfill/command.go @@ -0,0 +1,120 @@ +// Package semanticbackfill implements the operator command that schedules +// vector jobs for existing published candidates and needs, for example after +// semantic matching is enabled, the semantic policy is published, or the ML +// model changes. The jobs run in the backend worker; the command only +// schedules them and prints the resume cursor of every page. +package semanticbackfill + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/usecase/semantic" +) + +const usage = "usage: semantic-backfill candidates|needs|all --run