From b3c6dc870b9acc6a2e74f289c43709384f2ef4b8 Mon Sep 17 00:00:00 2001 From: shira Date: Thu, 8 Oct 2026 23:04:57 +0300 Subject: [PATCH] feat(assessment): add the review band of attempt signals and the disclosed collector --- api/README.en.md | 6 +- api/README.md | 6 +- api/core/components/schemas.yml | 38 +- .../schemas/assessment_signal_schemas.yml | 55 +- api/core/openapi.bundle.yml | 128 +- api/core/openapi.yml | 2 + .../candidate_assessment_signal_notice.yml | 71 + backend/Makefile | 8 + backend/README.en.md | 6 +- backend/README.md | 6 +- backend/cmd/assessment-review/main.go | 28 + backend/cmd/questionnaire-fixture/main.go | 7 +- .../00033_create_assessment_signal_review.sql | 271 +++ ...essment_signal_notice_acknowledgements.sql | 15 + .../db/queries/assessment_signal_notice.sql | 15 + .../db/queries/assessment_signal_review.sql | 247 +++ .../assessment_attempt_http_test.go | 16 +- .../integration_test/assessment_bank_test.go | 2 +- .../assessment_signal_notice_http_test.go | 117 ++ .../assessment_signal_review_http_test.go | 770 ++++++++ ...assessment_signal_review_migration_test.go | 102 ++ .../integration_test/organizations_test.go | 1 + backend/integration_test/policy_test.go | 3 +- .../primary/cli/assessmentreview/command.go | 133 ++ .../cli/assessmentreview/command_test.go | 113 ++ .../primary/http/api/oas_handlers_gen.go | 649 +++++++ .../primary/http/api/oas_interfaces_gen.go | 12 + .../adapter/primary/http/api/oas_json_gen.go | 1625 ++++++++++++++++- .../primary/http/api/oas_operations_gen.go | 131 +- .../primary/http/api/oas_parameters_gen.go | 175 ++ .../http/api/oas_request_decoders_gen.go | 79 + .../http/api/oas_response_encoders_gen.go | 213 +++ .../primary/http/api/oas_router_gen.go | 834 +++++---- .../primary/http/api/oas_schemas_gen.go | 665 ++++++- .../primary/http/api/oas_security_gen.go | 180 +- .../primary/http/api/oas_server_gen.go | 60 + .../primary/http/api/oas_unimplemented_gen.go | 69 + .../primary/http/api/oas_validators_gen.go | 462 +++++ .../assessment_signal_review_contract_test.go | 127 ++ .../adapter/primary/http/v1/assessment.go | 2 +- .../primary/http/v1/assessment_origin.go | 18 + .../primary/http/v1/assessment_signal.go | 3 +- .../http/v1/assessment_signal_notice.go | 103 ++ .../http/v1/assessment_signal_notice_test.go | 102 ++ .../postgres/assessment_signal_notice.go | 74 + .../postgres/assessment_signal_review.go | 299 +++ .../sqlc/assessment_signal_notice.sql.go | 53 + .../sqlc/assessment_signal_review.sql.go | 577 ++++++ .../adapter/secondary/postgres/sqlc/models.go | 71 + .../secondary/postgres/sqlc/querier.go | 38 + backend/internal/bootstrap/assessment.go | 6 + .../internal/bootstrap/assessment_signal.go | 8 +- .../bootstrap/assessment_signal_observer.go | 19 + backend/internal/bootstrap/jobs.go | 14 +- backend/internal/bootstrap/jobs_test.go | 5 +- .../domain/assessment_signal_policy.go | 137 ++ .../domain/assessment_signal_policy_test.go | 80 + .../domain/assessment_signal_review.go | 387 ++++ .../domain/assessment_signal_review_test.go | 167 ++ backend/internal/domain/policy.go | 13 + backend/internal/domain/policy_demo.go | 10 + backend/internal/domain/policy_document.go | 81 +- .../port/outbound/assessment_signal.go | 67 +- .../port/outbound/assessment_signal_notice.go | 29 + backend/internal/port/outbound/transaction.go | 1 + backend/internal/usecase/assessment/answer.go | 11 +- .../internal/usecase/assessment/attempt.go | 1 + .../internal/usecase/assessment/finalize.go | 11 +- backend/internal/usecase/assessment/signal.go | 9 + .../usecase/assessment/signal_notice.go | 88 + .../usecase/assessment/signal_review.go | 491 +++++ .../usecase/assessment/signal_review_test.go | 700 +++++++ backend/internal/usecase/identity/keyring.go | 49 + .../internal/usecase/identity/keyring_test.go | 69 + docs/en/ARCHITECTURE.md | 19 +- docs/en/DEPLOY.md | 19 +- docs/en/TESTING.md | 20 + docs/ru/ARCHITECTURE.md | 19 +- docs/ru/DEPLOY.md | 19 +- docs/ru/TESTING.md | 20 + frontend/README.en.md | 6 +- frontend/README.md | 6 +- frontend/e2e/assessment.spec.ts | 345 +++- .../assessment/api/assessment-queries.ts | 50 + frontend/src/entities/assessment/index.ts | 2 + .../model/contract-validation.test.ts | 14 + .../assessment/model/contract-validation.ts | 11 + .../src/entities/assessment/model/session.ts | 2 + .../src/features/assessment-signals/index.ts | 5 + .../assessment-signals/model/batcher.test.ts | 259 +++ .../assessment-signals/model/batcher.ts | 179 ++ .../model/collector.test.ts | 228 +++ .../assessment-signals/model/collector.ts | 117 ++ .../assessment-signals/model/measure.test.ts | 82 + .../assessment-signals/model/measure.ts | 106 ++ .../model/notice-content.ts | 60 + .../model/notice-gate.test.ts | 89 + .../assessment-signals/model/notice-gate.ts | 72 + .../assessment-signals/model/signal-events.ts | 43 + .../model/signal-session.test.ts | 116 ++ .../model/signal-session.ts | 55 + .../model/use-assessment-signals.ts | 59 + .../model/use-signal-notice-gate.ts | 87 + .../ui/signal-notice.module.css | 107 ++ .../ui/signal-notice.test.tsx | 69 + .../assessment-signals/ui/signal-notice.tsx | 149 ++ .../assessment/ui/assessment-attempt-page.tsx | 43 +- .../assessment/ui/assessment-page.module.css | 20 +- .../pages/assessment/ui/assessment-page.tsx | 31 +- frontend/src/shared/api/client.ts | 3 + .../endpoints/assessment/assessment.msw.ts | 31 + .../api/endpoints/assessment/assessment.ts | 203 +- frontend/src/shared/api/index.ts | 1 + ...owledgeMyAssessmentSignalNoticeBody.zod.ts | 17 + .../assessmentClipboardSignal.zod.ts | 2 +- .../assessment/assessmentSignalBatch.zod.ts | 2 +- .../assessment/assessmentSignalEvent.zod.ts | 2 +- .../assessment/assessmentSignalNotice.zod.ts | 19 + ...sessmentSignalNoticeAcknowledgement.zod.ts | 17 + .../assessmentSignalNoticeVersion.zod.ts | 15 + .../shared/api/schemas/assessment/index.ts | 4 + ...ecordMyAssessmentAttemptSignalsBody.zod.ts | 2 +- frontend/src/shared/api/server-clock.test.ts | 36 + frontend/src/shared/api/server-clock.ts | 33 + 124 files changed, 13522 insertions(+), 633 deletions(-) create mode 100644 api/core/routes/candidate_assessment_signal_notice.yml create mode 100644 backend/cmd/assessment-review/main.go create mode 100644 backend/db/migrations/00033_create_assessment_signal_review.sql create mode 100644 backend/db/migrations/00034_create_assessment_signal_notice_acknowledgements.sql create mode 100644 backend/db/queries/assessment_signal_notice.sql create mode 100644 backend/db/queries/assessment_signal_review.sql create mode 100644 backend/integration_test/assessment_signal_notice_http_test.go create mode 100644 backend/integration_test/assessment_signal_review_http_test.go create mode 100644 backend/integration_test/assessment_signal_review_migration_test.go create mode 100644 backend/internal/adapter/primary/cli/assessmentreview/command.go create mode 100644 backend/internal/adapter/primary/cli/assessmentreview/command_test.go create mode 100644 backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go create mode 100644 backend/internal/adapter/primary/http/v1/assessment_origin.go create mode 100644 backend/internal/adapter/primary/http/v1/assessment_signal_notice.go create mode 100644 backend/internal/adapter/primary/http/v1/assessment_signal_notice_test.go create mode 100644 backend/internal/adapter/secondary/postgres/assessment_signal_notice.go create mode 100644 backend/internal/adapter/secondary/postgres/assessment_signal_review.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_notice.sql.go create mode 100644 backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_review.sql.go create mode 100644 backend/internal/bootstrap/assessment_signal_observer.go create mode 100644 backend/internal/domain/assessment_signal_policy.go create mode 100644 backend/internal/domain/assessment_signal_policy_test.go create mode 100644 backend/internal/domain/assessment_signal_review.go create mode 100644 backend/internal/domain/assessment_signal_review_test.go create mode 100644 backend/internal/port/outbound/assessment_signal_notice.go create mode 100644 backend/internal/usecase/assessment/signal_notice.go create mode 100644 backend/internal/usecase/assessment/signal_review.go create mode 100644 backend/internal/usecase/assessment/signal_review_test.go create mode 100644 frontend/src/features/assessment-signals/index.ts create mode 100644 frontend/src/features/assessment-signals/model/batcher.test.ts create mode 100644 frontend/src/features/assessment-signals/model/batcher.ts create mode 100644 frontend/src/features/assessment-signals/model/collector.test.ts create mode 100644 frontend/src/features/assessment-signals/model/collector.ts create mode 100644 frontend/src/features/assessment-signals/model/measure.test.ts create mode 100644 frontend/src/features/assessment-signals/model/measure.ts create mode 100644 frontend/src/features/assessment-signals/model/notice-content.ts create mode 100644 frontend/src/features/assessment-signals/model/notice-gate.test.ts create mode 100644 frontend/src/features/assessment-signals/model/notice-gate.ts create mode 100644 frontend/src/features/assessment-signals/model/signal-events.ts create mode 100644 frontend/src/features/assessment-signals/model/signal-session.test.ts create mode 100644 frontend/src/features/assessment-signals/model/signal-session.ts create mode 100644 frontend/src/features/assessment-signals/model/use-assessment-signals.ts create mode 100644 frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts create mode 100644 frontend/src/features/assessment-signals/ui/signal-notice.module.css create mode 100644 frontend/src/features/assessment-signals/ui/signal-notice.test.tsx create mode 100644 frontend/src/features/assessment-signals/ui/signal-notice.tsx create mode 100644 frontend/src/shared/api/schemas/assessment/acknowledgeMyAssessmentSignalNoticeBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/assessmentSignalNotice.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/assessmentSignalNoticeAcknowledgement.zod.ts create mode 100644 frontend/src/shared/api/schemas/assessment/assessmentSignalNoticeVersion.zod.ts create mode 100644 frontend/src/shared/api/server-clock.test.ts create mode 100644 frontend/src/shared/api/server-clock.ts diff --git a/api/README.en.md b/api/README.en.md index 88d67d3..25b93ee 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -251,9 +251,13 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | session and CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` or `idempotency_in_progress`, 412 `version_conflict`, 422 | | `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | session | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | +| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | session | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` | +| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | session and CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` or `forbidden`, 409 `state_conflict` | Every operation also declares the `default` problem response. +The signal notice (`assessment-signal-notice`) lists the signals collected during a real attempt: browser events (focus loss, copy, paste and cut with a size, fullscreen exit; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, comparison of answer digests; only one-way keyed digests are stored, never addresses or session tokens). `GET` returns the notice version the server requires and whether the candidate acknowledged it; `PUT` stores the acknowledgement for the account and that version. The acknowledgement is a record that the candidate was informed, not a consent: it does not change C3, and the signal operation neither reads it nor refuses a batch without it. `PUT` needs no Idempotency-Key, because a repeat keeps the first time and answers 200; another version answers 409 `state_conflict`. The `demo_express` mode collects no signals and needs no acknowledgement. + Access: - The candidate comes only from the session; no operation takes a candidate identifier. An employer account answers 403 `forbidden`. An attempt of another candidate answers 404 `not_found`, the same as an unknown identifier, so attempt identifiers cannot be probed. @@ -313,7 +317,7 @@ Result: - `next_steps` come from the server: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (the command is planned), and `take_higher_grade`. A first confirmation is not a promotion, so `take_higher_grade` after it has a null `available_at`; after a promotion the next one waits for the 90-day promotion interval. - The result never contains answers, per-item correctness, keys, seeds, hidden checks, or anti-cheat signals. -Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the notice and storage of the anti-cheat signals (time, focus changes, pastes, parallel sessions), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05). +Planned, additive: a short approach description of up to 1500 characters next to the practice, which never decides the grade (PRD FR05); the debug run operation of the practice; the server signals of the anti-cheat layer (answer time, parallel sessions, address changes), which lead to a review and an appeal, never to a public label and never to the employer (PRD FR05). ### Needs diff --git a/api/README.md b/api/README.md index 62a19fb..35375cd 100644 --- a/api/README.md +++ b/api/README.md @@ -251,9 +251,13 @@ ML-сервис отвечает на ошибки той же схемой `Pro | `POST /api/v1/me/assessment-attempts/{attempt_id}/answers` | `SubmitMyAssessmentAnswer` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422, 429 | | `POST /api/v1/me/assessment-attempts/{attempt_id}/finalize` | `FinalizeMyAssessmentAttempt` | сессия и CSRF, Idempotency-Key | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` или `idempotency_in_progress`, 412 `version_conflict`, 422 | | `GET /api/v1/me/assessment-attempts/{attempt_id}/result` | `GetMyAssessmentResult` | сессия | 200 `AssessmentResult`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found`, 409 `state_conflict` | +| `GET /api/v1/me/assessment-signal-notice` | `GetMyAssessmentSignalNotice` | сессия | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 401, 403 `forbidden` | +| `PUT /api/v1/me/assessment-signal-notice` | `AcknowledgeMyAssessmentSignalNotice` | сессия и CSRF | 200 `AssessmentSignalNotice`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `csrf_check_failed` или `forbidden`, 409 `state_conflict` | Каждая операция также объявляет problem-ответ `default`. +Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Режим `demo_express` сигналы не собирает и подтверждения не требует. + Доступ: - Кандидат берется только из сессии; ни одна операция не принимает идентификатор кандидата. Аккаунт работодателя получает 403 `forbidden`. Попытка другого кандидата дает 404 `not_found`, как и неизвестный идентификатор, поэтому идентификаторы попыток нельзя перебирать. @@ -313,7 +317,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - `next_steps` приходят с сервера: `retake_same_grade`, `take_lower_grade`, `accept_lower_grade` (команда запланирована) и `take_higher_grade`. Первое подтверждение - не повышение, поэтому `take_higher_grade` после него имеет null в `available_at`; после повышения следующее ждет 90-дневный интервал повышения. - Результат никогда не содержит ответы, правильность отдельных заданий, ключи, seed, скрытые проверки или античит-сигналы. -Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; уведомление о собираемых античит-сигналах (время, переключение фокуса, вставки, параллельные сессии) и их хранение; сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD). +Запланировано, добавляется без ломающих изменений: краткое описание подхода до 1500 знаков рядом с практикой, которое не определяет грейд (FR05 в PRD); операция отладочных запусков практики; серверные сигналы античит-слоя (время ответа, параллельные сессии, смена адреса); сигналы ведут к перепроверке и апелляции, а не к публичному ярлыку, и работодателю не показываются (FR05 в PRD). ### Потребности diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index 382e7e0..da8122d 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -1778,7 +1778,7 @@ AssessmentClipboardSignal: format: int32 minimum: 0 maximum: 2147483647 - description: Byte count only. Clipboard or selection contents are not transmitted or retained. + 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 @@ -1831,6 +1831,42 @@ AssessmentSignalReceipt: 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 diff --git a/api/core/components/schemas/assessment_signal_schemas.yml b/api/core/components/schemas/assessment_signal_schemas.yml index 561ff22..37a1630 100644 --- a/api/core/components/schemas/assessment_signal_schemas.yml +++ b/api/core/components/schemas/assessment_signal_schemas.yml @@ -63,7 +63,15 @@ schemas: format: int32 minimum: 0 maximum: 2147483647 - description: Byte count only. Clipboard or selection contents are not transmitted or retained. + 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 @@ -122,3 +130,48 @@ schemas: 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/openapi.bundle.yml b/api/core/openapi.bundle.yml index 5facd98..7c73346 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -711,6 +711,78 @@ paths: $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 client shows it 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. 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 @@ -5411,7 +5483,7 @@ components: format: int32 minimum: 0 maximum: 2147483647 - description: Byte count only. Clipboard or selection contents are not transmitted or retained. + 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 @@ -9504,6 +9576,42 @@ components: - 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. @@ -11900,6 +12008,15 @@ components: 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: @@ -12432,15 +12549,6 @@ components: code: version_conflict detail: The resource changed after it was read. Read it again before retrying. trace_id: 5f6a7b8c-9d0e-4f1a-8b2c-3d4e5f6a7b8c - 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 PayloadTooLarge: summary: The request body exceeds the limit value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index fb2186f..b44b9ed 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -105,6 +105,8 @@ paths: $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}: 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..a45098f --- /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 client shows it 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. 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/backend/Makefile b/backend/Makefile index 384f4a6..7e90a64 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -41,6 +41,14 @@ 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: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download diff --git a/backend/README.en.md b/backend/README.en.md index 7baa96f..c4f367d 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -92,9 +92,11 @@ Answer submission evaluates the frozen server key and stores each answer once. N ## Assessment signals -The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt. +The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` accepts batches of focus-loss durations, clipboard event byte counts, and fullscreen exits. It stores no clipboard or answer content (`size_bytes` is the UTF-8 byte count of the pasted text plus file sizes, computed on the device, for a paste, and an approximate selection length in UTF-16 code units, with the text unread, for copy and cut) and supports no camera, microphone, screenshot, or screen recording. Events are bound to the owned real attempt and one of its frozen items; training attempts do not accept them. New batches require current C3 and an active attempt. -The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Browser collection and interpretation of these signals are separate work. +The operation limits the body to 32 KiB, each batch to 50 events, new receipts to 30 per minute per attempt, and stored events to 10,000 per attempt. Capacity is checked for the whole batch. A saturated receipt accepts zero events; idempotent replay returns the original receipt without consuming the receipt budget. Client timestamps are untrusted metadata: a timestamp outside five minutes before the attempt's creation to five minutes after database time rejects the whole batch with 400, so the client moves its timestamps to server time using the `Date` header; rate windows use database time. Migration 28 cascades event, batch, and receipt deletion with the attempt. Existing consent retention constraints still prevent physical account deletion; this cascade does not implement account erasure. Interpretation of these signals is separate work. + +The notice about the collected signals is stored separately. `GET` and `PUT /api/v1/me/assessment-signal-notice` read and write the candidate's acknowledgement of a text version (`usecase/assessment/signal_notice.go`, table `assessment_signal_notice_acknowledgements`, migration 34). The server sets the text version; a `PUT` with another version answers 409 and stores nothing, and a repeat keeps the time of the first acknowledgement. The acknowledgement is not a consent: the signal operation does not read it and still requires current C3, so the notice cannot be used to hide a consent. Attempt creation does not check the acknowledgement on the server; the candidate screen enforces the requirement. Rows are deleted by cascade with the user. ## Anonymous profile projection diff --git a/backend/README.md b/backend/README.md index 3294915..d0e2962 100644 --- a/backend/README.md +++ b/backend/README.md @@ -92,9 +92,11 @@ ## Сигналы прохождения оценки -Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки. +Доступный только кандидату `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` принимает пакеты длительностей потери фокуса, размеров событий буфера обмена и выходов из полноэкранного режима. Содержимое буфера и ответов не сохраняется; `size_bytes` для вставки - байты UTF-8 вставленного текста плюс размер файлов, посчитанные на устройстве, а для копирования и вырезания - приблизительная длина выделения в единицах UTF-16 (текст не читается); камера, микрофон, скриншоты и запись экрана не поддерживаются. События привязаны к собственной реальной попытке и одному из ее закрепленных вопросов; учебные попытки их не принимают. Новый пакет требует действующего C3 и активной попытки. -Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Сбор событий браузером и их интерпретация относятся к отдельной работе. +Операция ограничивает тело 32 КиБ, пакет 50 событиями, новые квитанции приема 30 в минуту на попытку, а хранение 10 000 событиями на попытку. Вместимость проверяется для всего пакета. При заполнении принимается ноль событий; идемпотентный повтор возвращает исходную квитанцию без расходования лимита. Клиентское время считается недоверенными метаданными: метка вне окна от создания попытки минус пять минут до времени БД плюс пять минут отклоняет весь пакет с 400, поэтому клиент приводит метки к серверному времени по заголовку `Date`; окна частоты используют время БД. Миграция 28 каскадно удаляет события, пакеты и квитанции вместе с попыткой. Действующие ограничения хранения согласий по-прежнему запрещают физическое удаление аккаунта; этот каскад не реализует удаление аккаунта. Интерпретация сигналов относится к отдельной работе. + +Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер; `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем. ## Анонимная проекция профиля 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/questionnaire-fixture/main.go b/backend/cmd/questionnaire-fixture/main.go index 75739a1..d81af80 100644 --- a/backend/cmd/questionnaire-fixture/main.go +++ b/backend/cmd/questionnaire-fixture/main.go @@ -314,8 +314,9 @@ func backendQuestionnaireBankOccupied(ctx context.Context, pool *pgxpool.Pool) ( return occupied, err } -// The isolated browser fixture opts into the extended demo policy explicitly. -// Normal startup still seeds V1, and an operator's policy must never be replaced. +// The isolated browser fixture opts into the extended demo policy explicitly, +// including the manual-review band thresholds. 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, @@ -344,7 +345,7 @@ func publishFixturePolicy(ctx context.Context, transactor outbound.Transactor) ( } 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.DemoProductPolicyV2(), + Author: domain.PolicyAuthor(fixtureAuthor), Policy: domain.DemoProductPolicyV3(), }) return err }) 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/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..578ca4d --- /dev/null +++ b/backend/db/queries/assessment_signal_review.sql @@ -0,0 +1,247 @@ +-- 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, + 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.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 +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 +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 +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, + 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), + 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, + 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.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/integration_test/assessment_attempt_http_test.go b/backend/integration_test/assessment_attempt_http_test.go index bf9f999..62fb8df 100644 --- a/backend/integration_test/assessment_attempt_http_test.go +++ b/backend/integration_test/assessment_attempt_http_test.go @@ -525,12 +525,18 @@ func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *tes if err != nil { t.Fatalf("NewAttemptService() error = %v", err) } + signalObserver, err := assessment.NewSignalObserver(keyring) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + attemptService.WithSignalObserver(signalObserver) attemptHandler := v1.NewAssessmentHandler(attemptService) signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now) if err != nil { t.Fatalf("NewSignalService() error = %v", err) } - signalHandler := v1.NewAssessmentSignalHandler(signalService) + signalService.WithSignalObserver(signalObserver) + signalHandler := v1.NewAssessmentSignalHandler(signalService).WithNotice(signalService) logs := &strings.Builder{} logger := slog.New(slog.NewJSONHandler(logs, nil)) responder := problem.NewResponder(logger) @@ -550,6 +556,13 @@ func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *tes } 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() transactor := postgresadapter.NewTransactor(pool) bank := assessment.NewBank(transactor) @@ -566,6 +579,7 @@ func seedAssessmentAttemptHTTPBank(ctx context.Context, t *testing.T, pool *pgxp 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, diff --git a/backend/integration_test/assessment_bank_test.go b/backend/integration_test/assessment_bank_test.go index 9e414fa..b566637 100644 --- a/backend/integration_test/assessment_bank_test.go +++ b/backend/integration_test/assessment_bank_test.go @@ -122,7 +122,7 @@ func TestAssessmentBank(t *testing.T) { "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`, + "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") 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..cd62943 --- /dev/null +++ b/backend/integration_test/assessment_signal_notice_http_test.go @@ -0,0 +1,117 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +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"` +} + +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) + + 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 != 1 || 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, `{"notice_version":2}`, 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, `{"notice_version":1}`, sessionHTTPTestOrigin, cookie.Value, csrf)) + if !first.Acknowledged || first.AcknowledgedAt == nil || first.NoticeVersion != 1 { + t.Fatalf("first acknowledgement = %+v", first) + } + time.Sleep(5 * time.Millisecond) + repeat := decodeSignalNotice(t, request(http.MethodPut, `{"notice_version":1}`, 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) + } + 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, `{"notice_version":1}`, 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/organizations_test.go b/backend/integration_test/organizations_test.go index 4e20fde..7e44d7e 100644 --- a/backend/integration_test/organizations_test.go +++ b/backend/integration_test/organizations_test.go @@ -51,6 +51,7 @@ var ( assessmentAttemptTables = []pgx.Identifier{ {"assessment_attempt_results"}, {"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"}, + {"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"}, {"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"}, } supportCaseTables = []pgx.Identifier{ diff --git a/backend/integration_test/policy_test.go b/backend/integration_test/policy_test.go index dabd49a..c9ec4cd 100644 --- a/backend/integration_test/policy_test.go +++ b/backend/integration_test/policy_test.go @@ -248,7 +248,8 @@ func TestPolicyVersions(t *testing.T) { company_card_view_quota_usage, assessment_training_bank_bindings, assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items, support_cases, support_case_events, assessment_signal_idempotency_outcomes, - assessment_signal_events, assessment_signal_batches, assessment_attempt_results`}, + assessment_signal_events, assessment_signal_batches, assessment_attempt_results, + assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks`}, } for _, statement := range statements { _, err := fixture.pool.Exec(ctx, statement.sql, statement.args...) 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..9a999d2 --- /dev/null +++ b/backend/internal/adapter/primary/cli/assessmentreview/command.go @@ -0,0 +1,133 @@ +// 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\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"+ + "note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged\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.MatchedIntegerItems, measures.MatchedSequenceItems, + measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents, + measures.ClientFullscreenExits, + ); 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/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 6f92374..357083b 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -320,6 +320,239 @@ func (s *Server) handleAcceptMyInvitationRequest(args [1]string, argsEscaped boo } } +// handleAcknowledgeMyAssessmentSignalNoticeRequest handles AcknowledgeMyAssessmentSignalNotice operation. +// +// 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). +// +// PUT /api/v1/me/assessment-signal-notice +func (s *Server) handleAcknowledgeMyAssessmentSignalNoticeRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("AcknowledgeMyAssessmentSignalNotice"), + semconv.HTTPRequestMethodKey.String("PUT"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-signal-notice"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), AcknowledgeMyAssessmentSignalNoticeOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: AcknowledgeMyAssessmentSignalNoticeOperation, + ID: "AcknowledgeMyAssessmentSignalNotice", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, AcknowledgeMyAssessmentSignalNoticeOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + { + sctx, ok, err := s.securitySessionCsrf(ctx, AcknowledgeMyAssessmentSignalNoticeOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCsrf", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCsrf", err) + } + return + } + if ok { + satisfied[0] |= 1 << 1 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000011}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + request, rawBody, close, err := s.decodeAcknowledgeMyAssessmentSignalNoticeRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response AcknowledgeMyAssessmentSignalNoticeRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: AcknowledgeMyAssessmentSignalNoticeOperation, + OperationSummary: "Record that the current candidate read the signal notice.", + OperationID: "AcknowledgeMyAssessmentSignalNotice", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = *AssessmentSignalNoticeAcknowledgement + Params = struct{} + Response = AcknowledgeMyAssessmentSignalNoticeRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.AcknowledgeMyAssessmentSignalNotice(ctx, request) + return response, err + }, + ) + } else { + response, err = s.h.AcknowledgeMyAssessmentSignalNotice(ctx, request) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeAcknowledgeMyAssessmentSignalNoticeResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleCancelMyInvitationRequest handles CancelMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -4056,6 +4289,209 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped } } +// handleGetMyAssessmentSignalNoticeRequest handles GetMyAssessmentSignalNotice operation. +// +// 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 client shows it 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. 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. +// +// GET /api/v1/me/assessment-signal-notice +func (s *Server) handleGetMyAssessmentSignalNoticeRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("GetMyAssessmentSignalNotice"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-signal-notice"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), GetMyAssessmentSignalNoticeOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: GetMyAssessmentSignalNoticeOperation, + ID: "GetMyAssessmentSignalNotice", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, GetMyAssessmentSignalNoticeOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + + var rawBody []byte + + var response GetMyAssessmentSignalNoticeRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: GetMyAssessmentSignalNoticeOperation, + OperationSummary: "Read whether the current candidate acknowledged the signal notice.", + OperationID: "GetMyAssessmentSignalNotice", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{}, + Raw: r, + } + + type ( + Request = struct{} + Params = struct{} + Response = GetMyAssessmentSignalNoticeRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + nil, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.GetMyAssessmentSignalNotice(ctx) + return response, err + }, + ) + } else { + response, err = s.h.GetMyAssessmentSignalNotice(ctx) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeGetMyAssessmentSignalNoticeResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleGetMyCardPreviewRequest handles GetMyCardPreview operation. // // Requires the session cookie of a candidate account. Returns a private preview of the permitted @@ -7265,6 +7701,219 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool, } } +// handleListMyAssessmentResultsRequest handles ListMyAssessmentResults operation. +// +// 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. +// +// GET /api/v1/me/assessment-results +func (s *Server) handleListMyAssessmentResultsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ListMyAssessmentResults"), + semconv.HTTPRequestMethodKey.String("GET"), + semconv.HTTPRouteKey.String("/api/v1/me/assessment-results"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyAssessmentResultsOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ListMyAssessmentResultsOperation, + ID: "ListMyAssessmentResults", + } + ) + { + type bitset = [1]uint8 + var satisfied bitset + { + sctx, ok, err := s.securitySessionCookie(ctx, ListMyAssessmentResultsOperation, r) + if err != nil { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Security: "SessionCookie", + Err: err, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security:SessionCookie", err) + } + return + } + if ok { + satisfied[0] |= 1 << 0 + ctx = sctx + } + } + + if ok := func() bool { + nextRequirement: + for _, requirement := range []bitset{ + {0b00000001}, + } { + for i, mask := range requirement { + if satisfied[i]&mask != mask { + continue nextRequirement + } + } + return true + } + return false + }(); !ok { + err = &ogenerrors.SecurityError{ + OperationContext: opErrContext, + Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied, + } + if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil { + defer recordError("Security", err) + } + return + } + } + params, err := decodeListMyAssessmentResultsParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + + var response ListMyAssessmentResultsRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ListMyAssessmentResultsOperation, + OperationSummary: "List immutable real assessment results of the current candidate.", + OperationID: "ListMyAssessmentResults", + Body: nil, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "limit", + In: "query", + }: params.Limit, + { + Name: "cursor", + In: "query", + }: params.Cursor, + }, + Raw: r, + } + + type ( + Request = struct{} + Params = ListMyAssessmentResultsParams + Response = ListMyAssessmentResultsRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackListMyAssessmentResultsParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ListMyAssessmentResults(ctx, params) + return response, err + }, + ) + } else { + response, err = s.h.ListMyAssessmentResults(ctx, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeListMyAssessmentResultsResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleListMyCardAccessHistoryRequest handles ListMyCardAccessHistory operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, so the diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 79d761c..bbaefd2 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -5,6 +5,10 @@ type AcceptMyInvitationRes interface { acceptMyInvitationRes() } +type AcknowledgeMyAssessmentSignalNoticeRes interface { + acknowledgeMyAssessmentSignalNoticeRes() +} + type CancelMyInvitationRes interface { cancelMyInvitationRes() } @@ -65,6 +69,10 @@ type GetMyAssessmentResultRes interface { getMyAssessmentResultRes() } +type GetMyAssessmentSignalNoticeRes interface { + getMyAssessmentSignalNoticeRes() +} + type GetMyCardPreviewRes interface { getMyCardPreviewRes() } @@ -121,6 +129,10 @@ type HideOrganizationRes interface { hideOrganizationRes() } +type ListMyAssessmentResultsRes interface { + listMyAssessmentResultsRes() +} + type ListMyCardAccessHistoryRes interface { listMyCardAccessHistoryRes() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index fc0bd6c..af87451 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -494,6 +494,158 @@ func (s *AccountScenario) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AcknowledgeMyAssessmentSignalNoticeBadRequest as json. +func (s *AcknowledgeMyAssessmentSignalNoticeBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcknowledgeMyAssessmentSignalNoticeBadRequest from json. +func (s *AcknowledgeMyAssessmentSignalNoticeBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcknowledgeMyAssessmentSignalNoticeBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcknowledgeMyAssessmentSignalNoticeBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcknowledgeMyAssessmentSignalNoticeConflict as json. +func (s *AcknowledgeMyAssessmentSignalNoticeConflict) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcknowledgeMyAssessmentSignalNoticeConflict from json. +func (s *AcknowledgeMyAssessmentSignalNoticeConflict) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcknowledgeMyAssessmentSignalNoticeConflict to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcknowledgeMyAssessmentSignalNoticeConflict(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeConflict) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeConflict) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcknowledgeMyAssessmentSignalNoticeForbidden as json. +func (s *AcknowledgeMyAssessmentSignalNoticeForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcknowledgeMyAssessmentSignalNoticeForbidden from json. +func (s *AcknowledgeMyAssessmentSignalNoticeForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcknowledgeMyAssessmentSignalNoticeForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcknowledgeMyAssessmentSignalNoticeForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AcknowledgeMyAssessmentSignalNoticeUnauthorized as json. +func (s *AcknowledgeMyAssessmentSignalNoticeUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes AcknowledgeMyAssessmentSignalNoticeUnauthorized from json. +func (s *AcknowledgeMyAssessmentSignalNoticeUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AcknowledgeMyAssessmentSignalNoticeUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AcknowledgeMyAssessmentSignalNoticeUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AcknowledgeMyAssessmentSignalNoticeUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AnonymousCardContent) Encode(e *jx.Encoder) { e.ObjStart() @@ -1965,6 +2117,295 @@ func (s *AssessmentAvailability) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentCategoryDecisionView) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentCategoryDecisionView) encodeFields(e *jx.Encoder) { + { + e.FieldStart("status") + s.Status.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + e.FieldStart("current_confirmed_grade") + s.CurrentConfirmedGrade.Encode(e) + } + { + e.FieldStart("method") + s.Method.Encode(e) + } + { + e.FieldStart("source") + s.Source.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentCategoryDecisionView = [6]string{ + 0: "status", + 1: "previous_confirmed_grade", + 2: "current_confirmed_grade", + 3: "method", + 4: "source", + 5: "calibration_status", +} + +// Decode decodes AssessmentCategoryDecisionView from json. +func (s *AssessmentCategoryDecisionView) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCategoryDecisionView to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "status": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Status.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"status\"") + } + case "previous_confirmed_grade": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.PreviousConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") + } + case "current_confirmed_grade": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.CurrentConfirmedGrade.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"current_confirmed_grade\"") + } + case "method": + requiredBitSet[0] |= 1 << 3 + if err := func() error { + if err := s.Method.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"method\"") + } + case "source": + requiredBitSet[0] |= 1 << 4 + if err := func() error { + if err := s.Source.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"source\"") + } + case "calibration_status": + requiredBitSet[0] |= 1 << 5 + if err := func() error { + if err := s.CalibrationStatus.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"calibration_status\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentCategoryDecisionView") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00111111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentCategoryDecisionView) { + name = jsonFieldsNameOfAssessmentCategoryDecisionView[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentCategoryDecisionView) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCategoryDecisionView) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCategoryDecisionViewMethod as json. +func (s AssessmentCategoryDecisionViewMethod) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCategoryDecisionViewMethod from json. +func (s *AssessmentCategoryDecisionViewMethod) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCategoryDecisionViewMethod to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCategoryDecisionViewMethod(v) { + case AssessmentCategoryDecisionViewMethodDemoBasicPassMark: + *s = AssessmentCategoryDecisionViewMethodDemoBasicPassMark + default: + *s = AssessmentCategoryDecisionViewMethod(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCategoryDecisionViewMethod) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCategoryDecisionViewMethod) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCategoryDecisionViewSource as json. +func (s AssessmentCategoryDecisionViewSource) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCategoryDecisionViewSource from json. +func (s *AssessmentCategoryDecisionViewSource) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCategoryDecisionViewSource to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCategoryDecisionViewSource(v) { + case AssessmentCategoryDecisionViewSourceSyntheticDemo: + *s = AssessmentCategoryDecisionViewSourceSyntheticDemo + default: + *s = AssessmentCategoryDecisionViewSource(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCategoryDecisionViewSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCategoryDecisionViewSource) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCategoryDecisionViewStatus as json. +func (s AssessmentCategoryDecisionViewStatus) Encode(e *jx.Encoder) { + e.Str(string(s)) +} + +// Decode decodes AssessmentCategoryDecisionViewStatus from json. +func (s *AssessmentCategoryDecisionViewStatus) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentCategoryDecisionViewStatus to nil") + } + v, err := d.StrBytes() + if err != nil { + return err + } + // Try to use constant string. + switch AssessmentCategoryDecisionViewStatus(v) { + case AssessmentCategoryDecisionViewStatusNotEligible: + *s = AssessmentCategoryDecisionViewStatusNotEligible + case AssessmentCategoryDecisionViewStatusNotConfirmed: + *s = AssessmentCategoryDecisionViewStatusNotConfirmed + case AssessmentCategoryDecisionViewStatusAssigned: + *s = AssessmentCategoryDecisionViewStatusAssigned + case AssessmentCategoryDecisionViewStatusUnchanged: + *s = AssessmentCategoryDecisionViewStatusUnchanged + default: + *s = AssessmentCategoryDecisionViewStatus(v) + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentCategoryDecisionViewStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentCategoryDecisionViewStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentClipboardSignal) Encode(e *jx.Encoder) { e.ObjStart() @@ -2846,6 +3287,12 @@ func (s *AssessmentCorrectiveResult) encodeFields(e *jx.Encoder) { e.FieldStart("previous_confirmed_grade") s.PreviousConfirmedGrade.Encode(e) } + { + if s.CategoryDecision.Set { + e.FieldStart("category_decision") + s.CategoryDecision.Encode(e) + } + } { e.FieldStart("strength") s.Strength.Encode(e) @@ -2904,7 +3351,7 @@ func (s *AssessmentCorrectiveResult) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAssessmentCorrectiveResult = [23]string{ +var jsonFieldsNameOfAssessmentCorrectiveResult = [24]string{ 0: "attempt_id", 1: "specialization", 2: "target_grade", @@ -2918,16 +3365,17 @@ var jsonFieldsNameOfAssessmentCorrectiveResult = [23]string{ 10: "not_determined_reason", 11: "confirmed_grade", 12: "previous_confirmed_grade", - 13: "strength", - 14: "calibration_status", - 15: "limitations", - 16: "uncertainty", - 17: "basic_score", - 18: "practices", - 19: "gaps", - 20: "durations", - 21: "next_steps", - 22: "decided_at", + 13: "category_decision", + 14: "strength", + 15: "calibration_status", + 16: "limitations", + 17: "uncertainty", + 18: "basic_score", + 19: "practices", + 20: "gaps", + 21: "durations", + 22: "next_steps", + 23: "decided_at", } // Decode decodes AssessmentCorrectiveResult from json. @@ -3071,8 +3519,18 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") } + case "category_decision": + if err := func() error { + s.CategoryDecision.Reset() + if err := s.CategoryDecision.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"category_decision\"") + } case "strength": - requiredBitSet[1] |= 1 << 5 + requiredBitSet[1] |= 1 << 6 if err := func() error { if err := s.Strength.Decode(d); err != nil { return err @@ -3082,7 +3540,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"strength\"") } case "calibration_status": - requiredBitSet[1] |= 1 << 6 + requiredBitSet[1] |= 1 << 7 if err := func() error { if err := s.CalibrationStatus.Decode(d); err != nil { return err @@ -3092,7 +3550,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"calibration_status\"") } case "limitations": - requiredBitSet[1] |= 1 << 7 + requiredBitSet[2] |= 1 << 0 if err := func() error { s.Limitations = make([]AssessmentLimitation, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3110,7 +3568,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"limitations\"") } case "uncertainty": - requiredBitSet[2] |= 1 << 0 + requiredBitSet[2] |= 1 << 1 if err := func() error { if err := s.Uncertainty.Decode(d); err != nil { return err @@ -3120,7 +3578,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"uncertainty\"") } case "basic_score": - requiredBitSet[2] |= 1 << 1 + requiredBitSet[2] |= 1 << 2 if err := func() error { if err := s.BasicScore.Decode(d); err != nil { return err @@ -3130,7 +3588,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"basic_score\"") } case "practices": - requiredBitSet[2] |= 1 << 2 + requiredBitSet[2] |= 1 << 3 if err := func() error { s.Practices = make([]AssessmentPracticeResult, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3148,7 +3606,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"practices\"") } case "gaps": - requiredBitSet[2] |= 1 << 3 + requiredBitSet[2] |= 1 << 4 if err := func() error { s.Gaps = make([]AssessmentGap, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3166,7 +3624,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"gaps\"") } case "durations": - requiredBitSet[2] |= 1 << 4 + requiredBitSet[2] |= 1 << 5 if err := func() error { if err := s.Durations.Decode(d); err != nil { return err @@ -3176,7 +3634,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"durations\"") } case "next_steps": - requiredBitSet[2] |= 1 << 5 + requiredBitSet[2] |= 1 << 6 if err := func() error { s.NextSteps = make([]AssessmentNextStep, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -3194,7 +3652,7 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"next_steps\"") } case "decided_at": - requiredBitSet[2] |= 1 << 6 + requiredBitSet[2] |= 1 << 7 if err := func() error { if err := s.DecidedAt.Decode(d); err != nil { return err @@ -3214,8 +3672,8 @@ func (s *AssessmentCorrectiveResult) Decode(d *jx.Decoder) error { var failures []validate.FieldError for i, mask := range [3]uint8{ 0b11111111, + 0b11011111, 0b11111111, - 0b01111111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -7588,6 +8046,12 @@ func (s *AssessmentQualifiedResult) encodeFields(e *jx.Encoder) { e.FieldStart("previous_confirmed_grade") s.PreviousConfirmedGrade.Encode(e) } + { + if s.CategoryDecision.Set { + e.FieldStart("category_decision") + s.CategoryDecision.Encode(e) + } + } { e.FieldStart("strength") s.Strength.Encode(e) @@ -7646,7 +8110,7 @@ func (s *AssessmentQualifiedResult) encodeFields(e *jx.Encoder) { } } -var jsonFieldsNameOfAssessmentQualifiedResult = [23]string{ +var jsonFieldsNameOfAssessmentQualifiedResult = [24]string{ 0: "attempt_id", 1: "specialization", 2: "target_grade", @@ -7660,16 +8124,17 @@ var jsonFieldsNameOfAssessmentQualifiedResult = [23]string{ 10: "not_determined_reason", 11: "confirmed_grade", 12: "previous_confirmed_grade", - 13: "strength", - 14: "calibration_status", - 15: "limitations", - 16: "uncertainty", - 17: "basic_score", - 18: "practices", - 19: "gaps", - 20: "durations", - 21: "next_steps", - 22: "decided_at", + 13: "category_decision", + 14: "strength", + 15: "calibration_status", + 16: "limitations", + 17: "uncertainty", + 18: "basic_score", + 19: "practices", + 20: "gaps", + 21: "durations", + 22: "next_steps", + 23: "decided_at", } // Decode decodes AssessmentQualifiedResult from json. @@ -7813,8 +8278,18 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { }(); err != nil { return errors.Wrap(err, "decode field \"previous_confirmed_grade\"") } + case "category_decision": + if err := func() error { + s.CategoryDecision.Reset() + if err := s.CategoryDecision.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"category_decision\"") + } case "strength": - requiredBitSet[1] |= 1 << 5 + requiredBitSet[1] |= 1 << 6 if err := func() error { if err := s.Strength.Decode(d); err != nil { return err @@ -7824,7 +8299,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"strength\"") } case "calibration_status": - requiredBitSet[1] |= 1 << 6 + requiredBitSet[1] |= 1 << 7 if err := func() error { if err := s.CalibrationStatus.Decode(d); err != nil { return err @@ -7834,7 +8309,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"calibration_status\"") } case "limitations": - requiredBitSet[1] |= 1 << 7 + requiredBitSet[2] |= 1 << 0 if err := func() error { s.Limitations = make([]AssessmentLimitation, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -7852,7 +8327,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"limitations\"") } case "uncertainty": - requiredBitSet[2] |= 1 << 0 + requiredBitSet[2] |= 1 << 1 if err := func() error { if err := s.Uncertainty.Decode(d); err != nil { return err @@ -7862,7 +8337,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"uncertainty\"") } case "basic_score": - requiredBitSet[2] |= 1 << 1 + requiredBitSet[2] |= 1 << 2 if err := func() error { if err := s.BasicScore.Decode(d); err != nil { return err @@ -7872,7 +8347,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"basic_score\"") } case "practices": - requiredBitSet[2] |= 1 << 2 + requiredBitSet[2] |= 1 << 3 if err := func() error { s.Practices = make([]AssessmentPracticeResult, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -7890,7 +8365,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"practices\"") } case "gaps": - requiredBitSet[2] |= 1 << 3 + requiredBitSet[2] |= 1 << 4 if err := func() error { s.Gaps = make([]AssessmentGap, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -7908,7 +8383,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"gaps\"") } case "durations": - requiredBitSet[2] |= 1 << 4 + requiredBitSet[2] |= 1 << 5 if err := func() error { if err := s.Durations.Decode(d); err != nil { return err @@ -7918,7 +8393,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"durations\"") } case "next_steps": - requiredBitSet[2] |= 1 << 5 + requiredBitSet[2] |= 1 << 6 if err := func() error { s.NextSteps = make([]AssessmentNextStep, 0) if err := d.Arr(func(d *jx.Decoder) error { @@ -7936,7 +8411,7 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { return errors.Wrap(err, "decode field \"next_steps\"") } case "decided_at": - requiredBitSet[2] |= 1 << 6 + requiredBitSet[2] |= 1 << 7 if err := func() error { if err := s.DecidedAt.Decode(d); err != nil { return err @@ -7956,8 +8431,8 @@ func (s *AssessmentQualifiedResult) Decode(d *jx.Decoder) error { var failures []validate.FieldError for i, mask := range [3]uint8{ 0b11111111, + 0b11011111, 0b11111111, - 0b01111111, } { if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { // Mask only required fields and check equality to mask using XOR. @@ -8121,6 +8596,320 @@ func (s *AssessmentRealMode) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentRealResult as json. +func (s AssessmentRealResult) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +func (s AssessmentRealResult) encodeFields(e *jx.Encoder) { + switch s.Type { + case AssessmentQualifiedResultAssessmentRealResult: + e.FieldStart("kind") + e.Str("root") + { + s := s.AssessmentQualifiedResult + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("not_determined_reason") + s.NotDeterminedReason.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + if s.CategoryDecision.Set { + e.FieldStart("category_decision") + s.CategoryDecision.Encode(e) + } + } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("uncertainty") + s.Uncertainty.Encode(e) + } + { + e.FieldStart("basic_score") + s.BasicScore.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } + } + case AssessmentCorrectiveResultAssessmentRealResult: + e.FieldStart("kind") + e.Str("corrective") + { + s := s.AssessmentCorrectiveResult + { + e.FieldStart("attempt_id") + json.EncodeUUID(e, s.AttemptID) + } + { + e.FieldStart("specialization") + s.Specialization.Encode(e) + } + { + e.FieldStart("target_grade") + s.TargetGrade.Encode(e) + } + { + e.FieldStart("root_attempt_id") + s.RootAttemptID.Encode(e) + } + { + e.FieldStart("chain_deadline") + s.ChainDeadline.Encode(e) + } + { + e.FieldStart("task_language") + s.TaskLanguage.Encode(e) + } + { + e.FieldStart("mode") + s.Mode.Encode(e) + } + { + e.FieldStart("versions") + s.Versions.Encode(e) + } + { + e.FieldStart("outcome") + s.Outcome.Encode(e) + } + { + e.FieldStart("not_determined_reason") + s.NotDeterminedReason.Encode(e) + } + { + e.FieldStart("confirmed_grade") + s.ConfirmedGrade.Encode(e) + } + { + e.FieldStart("previous_confirmed_grade") + s.PreviousConfirmedGrade.Encode(e) + } + { + if s.CategoryDecision.Set { + e.FieldStart("category_decision") + s.CategoryDecision.Encode(e) + } + } + { + e.FieldStart("strength") + s.Strength.Encode(e) + } + { + e.FieldStart("calibration_status") + s.CalibrationStatus.Encode(e) + } + { + e.FieldStart("limitations") + e.ArrStart() + for _, elem := range s.Limitations { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("uncertainty") + s.Uncertainty.Encode(e) + } + { + e.FieldStart("basic_score") + s.BasicScore.Encode(e) + } + { + e.FieldStart("practices") + e.ArrStart() + for _, elem := range s.Practices { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("gaps") + e.ArrStart() + for _, elem := range s.Gaps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("durations") + s.Durations.Encode(e) + } + { + e.FieldStart("next_steps") + e.ArrStart() + for _, elem := range s.NextSteps { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("decided_at") + s.DecidedAt.Encode(e) + } + } + } +} + +// Decode decodes AssessmentRealResult from json. +func (s *AssessmentRealResult) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentRealResult to nil") + } + // Sum type discriminator. + if typ := d.Next(); typ != jx.Object { + return errors.Errorf("unexpected json type %q", typ) + } + + var found bool + if err := d.Capture(func(d *jx.Decoder) error { + return d.ObjBytes(func(d *jx.Decoder, key []byte) error { + if found { + return d.Skip() + } + switch string(key) { + case "kind": + typ, err := d.Str() + if err != nil { + return err + } + switch typ { + case "root": + s.Type = AssessmentQualifiedResultAssessmentRealResult + found = true + case "corrective": + s.Type = AssessmentCorrectiveResultAssessmentRealResult + found = true + default: + return errors.Errorf("unknown type %s", typ) + } + return nil + } + return d.Skip() + }) + }); err != nil { + return errors.Wrap(err, "capture") + } + if !found { + return errors.New("unable to detect sum type variant") + } + switch s.Type { + case AssessmentQualifiedResultAssessmentRealResult: + if err := s.AssessmentQualifiedResult.Decode(d); err != nil { + return err + } + case AssessmentCorrectiveResultAssessmentRealResult: + if err := s.AssessmentCorrectiveResult.Decode(d); err != nil { + return err + } + default: + return errors.Errorf("inferred invalid type: %s", s.Type) + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentRealResult) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentRealResult) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentResult as json. func (s AssessmentResult) Encode(e *jx.Encoder) { e.ObjStart() @@ -8183,6 +8972,12 @@ func (s AssessmentResult) encodeFields(e *jx.Encoder) { e.FieldStart("previous_confirmed_grade") s.PreviousConfirmedGrade.Encode(e) } + { + if s.CategoryDecision.Set { + e.FieldStart("category_decision") + s.CategoryDecision.Encode(e) + } + } { e.FieldStart("strength") s.Strength.Encode(e) @@ -8293,6 +9088,12 @@ func (s AssessmentResult) encodeFields(e *jx.Encoder) { e.FieldStart("previous_confirmed_grade") s.PreviousConfirmedGrade.Encode(e) } + { + if s.CategoryDecision.Set { + e.FieldStart("category_decision") + s.CategoryDecision.Encode(e) + } + } { e.FieldStart("strength") s.Strength.Encode(e) @@ -8545,6 +9346,127 @@ func (s *AssessmentResult) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentResultHistoryPage) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentResultHistoryPage) encodeFields(e *jx.Encoder) { + { + e.FieldStart("items") + e.ArrStart() + for _, elem := range s.Items { + elem.Encode(e) + } + e.ArrEnd() + } + { + e.FieldStart("page") + s.Page.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentResultHistoryPage = [2]string{ + 0: "items", + 1: "page", +} + +// Decode decodes AssessmentResultHistoryPage from json. +func (s *AssessmentResultHistoryPage) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentResultHistoryPage to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "items": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + s.Items = make([]AssessmentRealResult, 0) + if err := d.Arr(func(d *jx.Decoder) error { + var elem AssessmentRealResult + if err := elem.Decode(d); err != nil { + return err + } + s.Items = append(s.Items, elem) + return nil + }); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"items\"") + } + case "page": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Page.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"page\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentResultHistoryPage") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000011, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentResultHistoryPage) { + name = jsonFieldsNameOfAssessmentResultHistoryPage[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentResultHistoryPage) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentResultHistoryPage) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentSessions) Encode(e *jx.Encoder) { e.ObjStart() @@ -8935,6 +9857,266 @@ func (s *AssessmentSignalEvent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *AssessmentSignalNotice) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentSignalNotice) encodeFields(e *jx.Encoder) { + { + e.FieldStart("notice_version") + s.NoticeVersion.Encode(e) + } + { + e.FieldStart("acknowledged") + e.Bool(s.Acknowledged) + } + { + e.FieldStart("acknowledged_at") + s.AcknowledgedAt.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentSignalNotice = [3]string{ + 0: "notice_version", + 1: "acknowledged", + 2: "acknowledged_at", +} + +// Decode decodes AssessmentSignalNotice from json. +func (s *AssessmentSignalNotice) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalNotice to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "notice_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.NoticeVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"notice_version\"") + } + case "acknowledged": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + v, err := d.Bool() + s.Acknowledged = bool(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"acknowledged\"") + } + case "acknowledged_at": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + if err := s.AcknowledgedAt.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"acknowledged_at\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentSignalNotice") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentSignalNotice) { + name = jsonFieldsNameOfAssessmentSignalNotice[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentSignalNotice) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalNotice) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode implements json.Marshaler. +func (s *AssessmentSignalNoticeAcknowledgement) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *AssessmentSignalNoticeAcknowledgement) encodeFields(e *jx.Encoder) { + { + e.FieldStart("notice_version") + s.NoticeVersion.Encode(e) + } +} + +var jsonFieldsNameOfAssessmentSignalNoticeAcknowledgement = [1]string{ + 0: "notice_version", +} + +// Decode decodes AssessmentSignalNoticeAcknowledgement from json. +func (s *AssessmentSignalNoticeAcknowledgement) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalNoticeAcknowledgement to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "notice_version": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.NoticeVersion.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"notice_version\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode AssessmentSignalNoticeAcknowledgement") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000001, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfAssessmentSignalNoticeAcknowledgement) { + name = jsonFieldsNameOfAssessmentSignalNoticeAcknowledgement[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *AssessmentSignalNoticeAcknowledgement) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalNoticeAcknowledgement) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentSignalNoticeVersion as json. +func (s AssessmentSignalNoticeVersion) Encode(e *jx.Encoder) { + unwrapped := int32(s) + + e.Int32(unwrapped) +} + +// Decode decodes AssessmentSignalNoticeVersion from json. +func (s *AssessmentSignalNoticeVersion) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode AssessmentSignalNoticeVersion to nil") + } + var unwrapped int32 + if err := func() error { + v, err := d.Int32() + unwrapped = int32(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = AssessmentSignalNoticeVersion(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s AssessmentSignalNoticeVersion) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *AssessmentSignalNoticeVersion) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *AssessmentSignalReceipt) Encode(e *jx.Encoder) { e.ObjStart() @@ -19327,6 +20509,82 @@ func (s *GetMyAssessmentResultUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes GetMyAssessmentSignalNoticeForbidden as json. +func (s *GetMyAssessmentSignalNoticeForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentSignalNoticeForbidden from json. +func (s *GetMyAssessmentSignalNoticeForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentSignalNoticeForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentSignalNoticeForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentSignalNoticeForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentSignalNoticeForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes GetMyAssessmentSignalNoticeUnauthorized as json. +func (s *GetMyAssessmentSignalNoticeUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes GetMyAssessmentSignalNoticeUnauthorized from json. +func (s *GetMyAssessmentSignalNoticeUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode GetMyAssessmentSignalNoticeUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = GetMyAssessmentSignalNoticeUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *GetMyAssessmentSignalNoticeUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *GetMyAssessmentSignalNoticeUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes GetMyCardPreviewForbidden as json. func (s *GetMyCardPreviewForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -24390,6 +25648,120 @@ func (s *ItemContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ListMyAssessmentResultsBadRequest as json. +func (s *ListMyAssessmentResultsBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyAssessmentResultsBadRequest from json. +func (s *ListMyAssessmentResultsBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyAssessmentResultsBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyAssessmentResultsBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyAssessmentResultsBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyAssessmentResultsBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyAssessmentResultsForbidden as json. +func (s *ListMyAssessmentResultsForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyAssessmentResultsForbidden from json. +func (s *ListMyAssessmentResultsForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyAssessmentResultsForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyAssessmentResultsForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyAssessmentResultsForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyAssessmentResultsForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ListMyAssessmentResultsUnauthorized as json. +func (s *ListMyAssessmentResultsUnauthorized) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ListMyAssessmentResultsUnauthorized from json. +func (s *ListMyAssessmentResultsUnauthorized) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ListMyAssessmentResultsUnauthorized to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ListMyAssessmentResultsUnauthorized(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ListMyAssessmentResultsUnauthorized) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ListMyAssessmentResultsUnauthorized) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ListMyCardAccessHistoryBadRequest as json. func (s *ListMyCardAccessHistoryBadRequest) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -34778,6 +36150,94 @@ func (s *NilAnonymousCardContent) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentCategoryDecisionViewMethod as json. +func (o NilAssessmentCategoryDecisionViewMethod) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentCategoryDecisionViewMethod from json. +func (o *NilAssessmentCategoryDecisionViewMethod) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentCategoryDecisionViewMethod to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentCategoryDecisionViewMethod + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentCategoryDecisionViewMethod) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentCategoryDecisionViewMethod) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes AssessmentCategoryDecisionViewSource as json. +func (o NilAssessmentCategoryDecisionViewSource) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes AssessmentCategoryDecisionViewSource from json. +func (o *NilAssessmentCategoryDecisionViewSource) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilAssessmentCategoryDecisionViewSource to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v AssessmentCategoryDecisionViewSource + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilAssessmentCategoryDecisionViewSource) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilAssessmentCategoryDecisionViewSource) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes AssessmentItem as json. func (o NilAssessmentItem) Encode(e *jx.Encoder) { if o.Null { @@ -35132,6 +36592,50 @@ func (s *NilBool) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes CalibrationStatus as json. +func (o NilCalibrationStatus) Encode(e *jx.Encoder) { + if o.Null { + e.Null() + return + } + e.Str(string(o.Value)) +} + +// Decode decodes CalibrationStatus from json. +func (o *NilCalibrationStatus) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode NilCalibrationStatus to nil") + } + if d.Next() == jx.Null { + if err := d.Null(); err != nil { + return err + } + + var v CalibrationStatus + o.Value = v + o.Null = true + return nil + } + o.Null = false + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s NilCalibrationStatus) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *NilCalibrationStatus) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CandidateExperience as json. func (o NilCandidateExperience) Encode(e *jx.Encoder) { if o.Null { @@ -38476,6 +39980,39 @@ func (s *OnboardingStep) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes AssessmentCategoryDecisionView as json. +func (o OptAssessmentCategoryDecisionView) Encode(e *jx.Encoder) { + if !o.Set { + return + } + o.Value.Encode(e) +} + +// Decode decodes AssessmentCategoryDecisionView from json. +func (o *OptAssessmentCategoryDecisionView) Decode(d *jx.Decoder) error { + if o == nil { + return errors.New("invalid: unable to decode OptAssessmentCategoryDecisionView to nil") + } + o.Set = true + if err := o.Value.Decode(d); err != nil { + return err + } + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s OptAssessmentCategoryDecisionView) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *OptAssessmentCategoryDecisionView) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes CandidateSalaryCompatibility as json. func (o OptCandidateSalaryCompatibility) Encode(e *jx.Encoder) { if !o.Set { diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index a2456b0..d3445ca 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -6,68 +6,71 @@ package api type OperationName = string const ( - AcceptMyInvitationOperation OperationName = "AcceptMyInvitation" - CancelMyInvitationOperation OperationName = "CancelMyInvitation" - ConfirmEmailOperation OperationName = "ConfirmEmail" - CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" - CreateMySupportCaseOperation OperationName = "CreateMySupportCase" - CreateOrganizationOperation OperationName = "CreateOrganization" - CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation" - CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed" - DeclineMyInvitationOperation OperationName = "DeclineMyInvitation" - FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt" - GetConsentTextOperation OperationName = "GetConsentText" - GetCurrentAccountOperation OperationName = "GetCurrentAccount" - GetCurrentSessionOperation OperationName = "GetCurrentSession" - GetHealthzOperation OperationName = "GetHealthz" - GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" - GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" - GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" - GetMyCardPreviewOperation OperationName = "GetMyCardPreview" - GetMyConsentTextOperation OperationName = "GetMyConsentText" - GetMyInvitationOperation OperationName = "GetMyInvitation" - GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings" - GetMyProfileOperation OperationName = "GetMyProfile" - GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" - GetMySupportCaseOperation OperationName = "GetMySupportCase" - GetOrganizationOperation OperationName = "GetOrganization" - GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard" - GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation" - GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts" - GetOrganizationNeedOperation OperationName = "GetOrganizationNeed" - GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" - GrantMyConsentOperation OperationName = "GrantMyConsent" - HideOrganizationOperation OperationName = "HideOrganization" - ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory" - ListMyConsentsOperation OperationName = "ListMyConsents" - ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations" - ListMyInvitationsOperation OperationName = "ListMyInvitations" - ListMyOrganizationsOperation OperationName = "ListMyOrganizations" - ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory" - ListMySupportCasesOperation OperationName = "ListMySupportCases" - ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" - ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds" - LoginOperation OperationName = "Login" - LogoutOperation OperationName = "Logout" - RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary" - RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals" - RegisterAccountOperation OperationName = "RegisterAccount" - RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion" - ResendEmailVerificationOperation OperationName = "ResendEmailVerification" - RevokeMyConsentOperation OperationName = "RevokeMyConsent" - RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent" - SaveMyProfileOperation OperationName = "SaveMyProfile" - SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" - SearchOrganizationMatchesOperation OperationName = "SearchOrganizationMatches" - SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation" - SetMyPublicationOperation OperationName = "SetMyPublication" - SetMySearchStatusOperation OperationName = "SetMySearchStatus" - StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession" - SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" - UnhideOrganizationOperation OperationName = "UnhideOrganization" - UpdateOrganizationOperation OperationName = "UpdateOrganization" - UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation" - UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed" - ViewMyInvitationOperation OperationName = "ViewMyInvitation" - WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation" + AcceptMyInvitationOperation OperationName = "AcceptMyInvitation" + AcknowledgeMyAssessmentSignalNoticeOperation OperationName = "AcknowledgeMyAssessmentSignalNotice" + CancelMyInvitationOperation OperationName = "CancelMyInvitation" + ConfirmEmailOperation OperationName = "ConfirmEmail" + CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" + CreateMySupportCaseOperation OperationName = "CreateMySupportCase" + CreateOrganizationOperation OperationName = "CreateOrganization" + CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation" + CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed" + DeclineMyInvitationOperation OperationName = "DeclineMyInvitation" + FinalizeMyAssessmentAttemptOperation OperationName = "FinalizeMyAssessmentAttempt" + GetConsentTextOperation OperationName = "GetConsentText" + GetCurrentAccountOperation OperationName = "GetCurrentAccount" + GetCurrentSessionOperation OperationName = "GetCurrentSession" + GetHealthzOperation OperationName = "GetHealthz" + GetMyAssessmentAttemptOperation OperationName = "GetMyAssessmentAttempt" + GetMyAssessmentAvailabilityOperation OperationName = "GetMyAssessmentAvailability" + GetMyAssessmentResultOperation OperationName = "GetMyAssessmentResult" + GetMyAssessmentSignalNoticeOperation OperationName = "GetMyAssessmentSignalNotice" + GetMyCardPreviewOperation OperationName = "GetMyCardPreview" + GetMyConsentTextOperation OperationName = "GetMyConsentText" + GetMyInvitationOperation OperationName = "GetMyInvitation" + GetMyPrivacySettingsOperation OperationName = "GetMyPrivacySettings" + GetMyProfileOperation OperationName = "GetMyProfile" + GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire" + GetMySupportCaseOperation OperationName = "GetMySupportCase" + GetOrganizationOperation OperationName = "GetOrganization" + GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard" + GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation" + GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts" + GetOrganizationNeedOperation OperationName = "GetOrganizationNeed" + GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog" + GrantMyConsentOperation OperationName = "GrantMyConsent" + HideOrganizationOperation OperationName = "HideOrganization" + ListMyAssessmentResultsOperation OperationName = "ListMyAssessmentResults" + ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory" + ListMyConsentsOperation OperationName = "ListMyConsents" + ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations" + ListMyInvitationsOperation OperationName = "ListMyInvitations" + ListMyOrganizationsOperation OperationName = "ListMyOrganizations" + ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory" + ListMySupportCasesOperation OperationName = "ListMySupportCases" + ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations" + ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds" + LoginOperation OperationName = "Login" + LogoutOperation OperationName = "Logout" + RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary" + RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals" + RegisterAccountOperation OperationName = "RegisterAccount" + RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion" + ResendEmailVerificationOperation OperationName = "ResendEmailVerification" + RevokeMyConsentOperation OperationName = "RevokeMyConsent" + RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent" + SaveMyProfileOperation OperationName = "SaveMyProfile" + SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire" + SearchOrganizationMatchesOperation OperationName = "SearchOrganizationMatches" + SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation" + SetMyPublicationOperation OperationName = "SetMyPublication" + SetMySearchStatusOperation OperationName = "SetMySearchStatus" + StartMyAssessmentAttemptSessionOperation OperationName = "StartMyAssessmentAttemptSession" + SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer" + UnhideOrganizationOperation OperationName = "UnhideOrganization" + UpdateOrganizationOperation OperationName = "UpdateOrganization" + UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation" + UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed" + ViewMyInvitationOperation OperationName = "ViewMyInvitation" + WithdrawOrganizationInvitationOperation OperationName = "WithdrawOrganizationInvitation" ) diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index 4ca4d4d..8834c45 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -2433,6 +2433,181 @@ func decodeHideOrganizationParams(args [1]string, argsEscaped bool, r *http.Requ return params, nil } +// ListMyAssessmentResultsParams is parameters of ListMyAssessmentResults operation. +type ListMyAssessmentResultsParams struct { + // Maximum number of results per page. + Limit OptInt32 `json:",omitempty,omitzero"` + // 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. + Cursor OptString `json:",omitempty,omitzero"` +} + +func unpackListMyAssessmentResultsParams(packed middleware.Parameters) (params ListMyAssessmentResultsParams) { + { + key := middleware.ParameterKey{ + Name: "limit", + In: "query", + } + if v, ok := packed[key]; ok { + params.Limit = v.(OptInt32) + } + } + { + key := middleware.ParameterKey{ + Name: "cursor", + In: "query", + } + if v, ok := packed[key]; ok { + params.Cursor = v.(OptString) + } + } + return params +} + +func decodeListMyAssessmentResultsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyAssessmentResultsParams, _ error) { + q := uri.NewQueryDecoder(r.URL.Query()) + // Set default value for query: limit. + { + val := int32(20) + params.Limit.SetTo(val) + } + // Decode query: limit. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "limit", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotLimitVal int32 + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToInt32(val) + if err != nil { + return err + } + + paramsDotLimitVal = c + return nil + }(); err != nil { + return err + } + params.Limit.SetTo(paramsDotLimitVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Limit.Get(); ok { + if err := func() error { + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 50, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(value)); err != nil { + return errors.Wrap(err, "int") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "limit", + In: "query", + Err: err, + } + } + // Decode query: cursor. + if err := func() error { + cfg := uri.QueryParameterDecodingConfig{ + Name: "cursor", + Style: uri.QueryStyleForm, + Explode: true, + } + + if err := q.HasParam(cfg); err == nil { + if err := q.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotCursorVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotCursorVal = c + return nil + }(); err != nil { + return err + } + params.Cursor.SetTo(paramsDotCursorVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Cursor.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 512, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[A-Za-z0-9_-]+$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "cursor", + In: "query", + Err: err, + } + } + return params, nil +} + // ListMyCardAccessHistoryParams is parameters of ListMyCardAccessHistory operation. type ListMyCardAccessHistoryParams struct { // Maximum number of items in the page. The server may return fewer items even when more remain; use diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index a178d3d..0b43279 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -93,6 +93,85 @@ func (s *Server) decodeAcceptMyInvitationRequest(r *http.Request) ( } } +func (s *Server) decodeAcknowledgeMyAssessmentSignalNoticeRequest(r *http.Request) ( + req *AssessmentSignalNoticeAcknowledgement, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request AssessmentSignalNoticeAcknowledgement + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + func (s *Server) decodeCancelMyInvitationRequest(r *http.Request) ( req *InvitationCommand, rawBody []byte, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index c08ffb6..5645778 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -165,6 +165,89 @@ func encodeAcceptMyInvitationResponse(response AcceptMyInvitationRes, w http.Res } } +func encodeAcknowledgeMyAssessmentSignalNoticeResponse(response AcknowledgeMyAssessmentSignalNoticeRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentSignalNoticeHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcknowledgeMyAssessmentSignalNoticeBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcknowledgeMyAssessmentSignalNoticeUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcknowledgeMyAssessmentSignalNoticeForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *AcknowledgeMyAssessmentSignalNoticeConflict: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(409) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeCancelMyInvitationResponse(response CancelMyInvitationRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CandidateInvitationHeaders: @@ -1683,6 +1766,65 @@ func encodeGetMyAssessmentResultResponse(response GetMyAssessmentResultRes, w ht } } +func encodeGetMyAssessmentSignalNoticeResponse(response GetMyAssessmentSignalNoticeRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentSignalNoticeHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentSignalNoticeUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *GetMyAssessmentSignalNoticeForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeGetMyCardPreviewResponse(response GetMyCardPreviewRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CardPreviewHeaders: @@ -2790,6 +2932,77 @@ func encodeHideOrganizationResponse(response HideOrganizationRes, w http.Respons } } +func encodeListMyAssessmentResultsResponse(response ListMyAssessmentResultsRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *AssessmentResultHistoryPageHeaders: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Cache-Control" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Cache-Control", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + return e.EncodeValue(conv.StringToString(string(response.CacheControl))) + }); err != nil { + return errors.Wrap(err, "encode Cache-Control header") + } + } + } + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyAssessmentResultsBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyAssessmentResultsUnauthorized: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(401) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ListMyAssessmentResultsForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeListMyCardAccessHistoryResponse(response ListMyCardAccessHistoryRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *CardAccessListHeaders: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 98c0825..0ef7d4b 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,105 +11,108 @@ import ( ) var ( - rn69AllowedHeaders = map[string]string{ + rn72AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn7AllowedHeaders = map[string]string{ - "POST": "Content-Type,Origin", - } - rn65AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key", - } - rn61AllowedHeaders = map[string]string{ - "POST": "Content-Type", - } - rn25AllowedHeaders = map[string]string{ - "DELETE": "X-Csrf-Token", - } - rn67AllowedHeaders = map[string]string{ - "POST": "X-Csrf-Token", - } rn9AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + "POST": "Content-Type,Origin", } - rn80AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn20AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn79AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + rn68AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key", } rn64AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + "POST": "Content-Type", } - rn71AllowedHeaders = map[string]string{ + rn27AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn50AllowedHeaders = map[string]string{ + rn70AllowedHeaders = map[string]string{ + "POST": "X-Csrf-Token", + } + rn11AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn83AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn22AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn82AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn67AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn5AllowedHeaders = map[string]string{ + "PUT": "Content-Type,X-Csrf-Token", + } + rn74AllowedHeaders = map[string]string{ + "DELETE": "X-Csrf-Token", + } + rn52AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "Content-Type,X-Csrf-Token", } rn3AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn5AllowedHeaders = map[string]string{ + rn7AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn17AllowedHeaders = map[string]string{ + rn19AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn81AllowedHeaders = map[string]string{ + rn84AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn53AllowedHeaders = map[string]string{ + rn55AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "X-Csrf-Token", } - rn76AllowedHeaders = map[string]string{ + rn79AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn77AllowedHeaders = map[string]string{ + rn80AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn36AllowedHeaders = map[string]string{ + rn38AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn37AllowedHeaders = map[string]string{ + rn39AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn10AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn11AllowedHeaders = map[string]string{ + rn12AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn13AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn15AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn14AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn43AllowedHeaders = map[string]string{ - "PATCH": "Content-Type,X-Csrf-Token", - } - rn63AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn74AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn82AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn72AllowedHeaders = map[string]string{ - "POST": "Content-Type,X-Csrf-Token", - } rn16AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn46AllowedHeaders = map[string]string{ + rn45AllowedHeaders = map[string]string{ + "PATCH": "Content-Type,X-Csrf-Token", + } + rn66AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn77AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn85AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn75AllowedHeaders = map[string]string{ + "POST": "Content-Type,X-Csrf-Token", + } + rn18AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn48AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } ) @@ -266,7 +269,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn69AllowedHeaders, + allowedHeaders: rn72AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -291,7 +294,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn7AllowedHeaders, + allowedHeaders: rn9AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -343,7 +346,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn65AllowedHeaders, + allowedHeaders: rn68AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -367,7 +370,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn61AllowedHeaders, + allowedHeaders: rn64AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -394,7 +397,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn25AllowedHeaders, + allowedHeaders: rn27AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -447,7 +450,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn67AllowedHeaders, + allowedHeaders: rn70AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -456,9 +459,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - case 's': // Prefix: "ssessment-a" + case 's': // Prefix: "ssessment-" - if l := len("ssessment-a"); len(elem) >= l && elem[0:l] == "ssessment-a" { + if l := len("ssessment-"); len(elem) >= l && elem[0:l] == "ssessment-" { elem = elem[l:] } else { break @@ -468,58 +471,35 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case 't': // Prefix: "ttempts" + case 'a': // Prefix: "a" - if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + if l := len("a"); len(elem) >= l && elem[0:l] == "a" { elem = elem[l:] } else { break } if len(elem) == 0 { - switch r.Method { - case "POST": - s.handleCreateMyAssessmentAttemptRequest([0]string{}, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "POST", - allowedHeaders: rn9AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) - } - - return + break } switch elem[0] { - case '/': // Prefix: "/" + case 't': // Prefix: "ttempts" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { elem = elem[l:] } else { break } - // Param: "attempt_id" - // Match until "/" - idx := strings.IndexByte(elem, '/') - if idx < 0 { - idx = len(elem) - } - args[0] = elem[:idx] - elem = elem[idx:] - if len(elem) == 0 { switch r.Method { - case "GET": - s.handleGetMyAssessmentAttemptRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) + case "POST": + s.handleCreateMyAssessmentAttemptRequest([0]string{}, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET", - allowedHeaders: nil, - acceptPost: "", + allowedMethods: "POST", + allowedHeaders: rn11AllowedHeaders, + acceptPost: "application/json", acceptPatch: "", }) } @@ -535,94 +515,36 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } + // Param: "attempt_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + if len(elem) == 0 { - break + switch r.Method { + case "GET": + s.handleGetMyAssessmentAttemptRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return } switch elem[0] { - case 'a': // Prefix: "answers" + case '/': // Prefix: "/" - if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "POST": - s.handleSubmitMyAssessmentAnswerRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "POST", - allowedHeaders: rn80AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) - } - - return - } - - case 'f': // Prefix: "finalize" - - if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "POST": - s.handleFinalizeMyAssessmentAttemptRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "POST", - allowedHeaders: rn20AllowedHeaders, - acceptPost: "application/json", - acceptPatch: "", - }) - } - - return - } - - case 'r': // Prefix: "result" - - if l := len("result"); len(elem) >= l && elem[0:l] == "result" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch r.Method { - case "GET": - s.handleGetMyAssessmentResultRequest([1]string{ - args[0], - }, elemIsEscaped, w, r) - default: - s.notAllowed(w, r, notAllowedParams{ - allowedMethods: "GET", - allowedHeaders: nil, - acceptPost: "", - acceptPatch: "", - }) - } - - return - } - - case 's': // Prefix: "s" - - if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { elem = elem[l:] } else { break @@ -632,9 +554,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { break } switch elem[0] { - case 'e': // Prefix: "essions" + case 'a': // Prefix: "answers" - if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" { + if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { elem = elem[l:] } else { break @@ -644,13 +566,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Leaf node. switch r.Method { case "POST": - s.handleStartMyAssessmentAttemptSessionRequest([1]string{ + s.handleSubmitMyAssessmentAnswerRequest([1]string{ args[0], }, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn79AllowedHeaders, + allowedHeaders: rn83AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -659,9 +581,9 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - case 'i': // Prefix: "ignals" + case 'f': // Prefix: "finalize" - if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" { + if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { elem = elem[l:] } else { break @@ -671,13 +593,13 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Leaf node. switch r.Method { case "POST": - s.handleRecordMyAssessmentAttemptSignalsRequest([1]string{ + s.handleFinalizeMyAssessmentAttemptRequest([1]string{ args[0], }, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn64AllowedHeaders, + allowedHeaders: rn22AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -686,17 +608,137 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + case 'r': // Prefix: "result" + + if l := len("result"); len(elem) >= l && elem[0:l] == "result" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentResultRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'e': // Prefix: "essions" + + if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleStartMyAssessmentAttemptSessionRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn82AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + case 'i': // Prefix: "ignals" + + if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleRecordMyAssessmentAttemptSignalsRequest([1]string{ + args[0], + }, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn67AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + } + } } } + case 'v': // Prefix: "vailability" + + if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentAvailabilityRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET", + allowedHeaders: nil, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + } - case 'v': // Prefix: "vailability" + case 'r': // Prefix: "results" - if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + if l := len("results"); len(elem) >= l && elem[0:l] == "results" { elem = elem[l:] } else { break @@ -706,7 +748,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Leaf node. switch r.Method { case "GET": - s.handleGetMyAssessmentAvailabilityRequest([0]string{}, elemIsEscaped, w, r) + s.handleListMyAssessmentResultsRequest([0]string{}, elemIsEscaped, w, r) default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET", @@ -719,6 +761,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + case 's': // Prefix: "signal-notice" + + if l := len("signal-notice"); len(elem) >= l && elem[0:l] == "signal-notice" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "GET": + s.handleGetMyAssessmentSignalNoticeRequest([0]string{}, elemIsEscaped, w, r) + case "PUT": + s.handleAcknowledgeMyAssessmentSignalNoticeRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "GET,PUT", + allowedHeaders: rn5AllowedHeaders, + acceptPost: "", + acceptPatch: "", + }) + } + + return + } + } } @@ -834,7 +903,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE", - allowedHeaders: rn71AllowedHeaders, + allowedHeaders: rn74AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -868,7 +937,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn50AllowedHeaders, + allowedHeaders: rn52AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -997,7 +1066,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn5AllowedHeaders, + allowedHeaders: rn7AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1024,7 +1093,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn17AllowedHeaders, + allowedHeaders: rn19AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1051,7 +1120,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn81AllowedHeaders, + allowedHeaders: rn84AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1231,7 +1300,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn53AllowedHeaders, + allowedHeaders: rn55AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1322,7 +1391,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn76AllowedHeaders, + allowedHeaders: rn79AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1349,7 +1418,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn77AllowedHeaders, + allowedHeaders: rn80AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1380,7 +1449,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn36AllowedHeaders, + allowedHeaders: rn38AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1409,7 +1478,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn37AllowedHeaders, + allowedHeaders: rn39AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1435,7 +1504,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn10AllowedHeaders, + allowedHeaders: rn12AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1499,7 +1568,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn11AllowedHeaders, + allowedHeaders: rn13AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1538,7 +1607,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn13AllowedHeaders, + allowedHeaders: rn15AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1617,7 +1686,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn14AllowedHeaders, + allowedHeaders: rn16AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1658,7 +1727,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn43AllowedHeaders, + allowedHeaders: rn45AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1738,7 +1807,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn63AllowedHeaders, + allowedHeaders: rn66AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1766,7 +1835,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn74AllowedHeaders, + allowedHeaders: rn77AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1796,7 +1865,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn82AllowedHeaders, + allowedHeaders: rn85AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1829,7 +1898,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn72AllowedHeaders, + allowedHeaders: rn75AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1859,7 +1928,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn16AllowedHeaders, + allowedHeaders: rn18AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1901,7 +1970,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn46AllowedHeaders, + allowedHeaders: rn48AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2339,9 +2408,9 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } - case 's': // Prefix: "ssessment-a" + case 's': // Prefix: "ssessment-" - if l := len("ssessment-a"); len(elem) >= l && elem[0:l] == "ssessment-a" { + if l := len("ssessment-"); len(elem) >= l && elem[0:l] == "ssessment-" { elem = elem[l:] } else { break @@ -2351,57 +2420,36 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case 't': // Prefix: "ttempts" + case 'a': // Prefix: "a" - if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { + if l := len("a"); len(elem) >= l && elem[0:l] == "a" { elem = elem[l:] } else { break } if len(elem) == 0 { - switch method { - case "POST": - r.name = CreateMyAssessmentAttemptOperation - r.summary = "Start a real, corrective, or training assessment attempt." - r.operationID = "CreateMyAssessmentAttempt" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts" - r.args = args - r.count = 0 - return r, true - default: - return - } + break } switch elem[0] { - case '/': // Prefix: "/" + case 't': // Prefix: "ttempts" - if l := len("/"); len(elem) >= l && elem[0:l] == "/" { + if l := len("ttempts"); len(elem) >= l && elem[0:l] == "ttempts" { elem = elem[l:] } else { break } - // Param: "attempt_id" - // Match until "/" - idx := strings.IndexByte(elem, '/') - if idx < 0 { - idx = len(elem) - } - args[0] = elem[:idx] - elem = elem[idx:] - if len(elem) == 0 { switch method { - case "GET": - r.name = GetMyAssessmentAttemptOperation - r.summary = "Read an assessment attempt of the current candidate." - r.operationID = "GetMyAssessmentAttempt" + case "POST": + r.name = CreateMyAssessmentAttemptOperation + r.summary = "Start a real, corrective, or training assessment attempt." + r.operationID = "CreateMyAssessmentAttempt" r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}" + r.pathPattern = "/api/v1/me/assessment-attempts" r.args = args - r.count = 1 + r.count = 0 return r, true default: return @@ -2416,88 +2464,34 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } + // Param: "attempt_id" + // Match until "/" + idx := strings.IndexByte(elem, '/') + if idx < 0 { + idx = len(elem) + } + args[0] = elem[:idx] + elem = elem[idx:] + if len(elem) == 0 { - break + switch method { + case "GET": + r.name = GetMyAssessmentAttemptOperation + r.summary = "Read an assessment attempt of the current candidate." + r.operationID = "GetMyAssessmentAttempt" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}" + r.args = args + r.count = 1 + return r, true + default: + return + } } switch elem[0] { - case 'a': // Prefix: "answers" + case '/': // Prefix: "/" - if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "POST": - r.name = SubmitMyAssessmentAnswerOperation - r.summary = "Answer the current item or submit a practice of an assessment attempt." - r.operationID = "SubmitMyAssessmentAnswer" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/answers" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - case 'f': // Prefix: "finalize" - - if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "POST": - r.name = FinalizeMyAssessmentAttemptOperation - r.summary = "Ask for the grade decision of an assessment attempt." - r.operationID = "FinalizeMyAssessmentAttempt" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/finalize" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - case 'r': // Prefix: "result" - - if l := len("result"); len(elem) >= l && elem[0:l] == "result" { - elem = elem[l:] - } else { - break - } - - if len(elem) == 0 { - // Leaf node. - switch method { - case "GET": - r.name = GetMyAssessmentResultOperation - r.summary = "Read the result of an assessment attempt of the current candidate." - r.operationID = "GetMyAssessmentResult" - r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/result" - r.args = args - r.count = 1 - return r, true - default: - return - } - } - - case 's': // Prefix: "s" - - if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + if l := len("/"); len(elem) >= l && elem[0:l] == "/" { elem = elem[l:] } else { break @@ -2507,9 +2501,9 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { break } switch elem[0] { - case 'e': // Prefix: "essions" + case 'a': // Prefix: "answers" - if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" { + if l := len("answers"); len(elem) >= l && elem[0:l] == "answers" { elem = elem[l:] } else { break @@ -2519,11 +2513,11 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { // Leaf node. switch method { case "POST": - r.name = StartMyAssessmentAttemptSessionOperation - r.summary = "Start or resume a work session for the current candidate's attempt." - r.operationID = "StartMyAssessmentAttemptSession" + r.name = SubmitMyAssessmentAnswerOperation + r.summary = "Answer the current item or submit a practice of an assessment attempt." + r.operationID = "SubmitMyAssessmentAnswer" r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/answers" r.args = args r.count = 1 return r, true @@ -2532,9 +2526,9 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } - case 'i': // Prefix: "ignals" + case 'f': // Prefix: "finalize" - if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" { + if l := len("finalize"); len(elem) >= l && elem[0:l] == "finalize" { elem = elem[l:] } else { break @@ -2544,11 +2538,11 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { // Leaf node. switch method { case "POST": - r.name = RecordMyAssessmentAttemptSignalsOperation - r.summary = "Store a bounded batch of client-reported assessment signals." - r.operationID = "RecordMyAssessmentAttemptSignals" + r.name = FinalizeMyAssessmentAttemptOperation + r.summary = "Ask for the grade decision of an assessment attempt." + r.operationID = "FinalizeMyAssessmentAttempt" r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/signals" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/finalize" r.args = args r.count = 1 return r, true @@ -2557,17 +2551,131 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } } + case 'r': // Prefix: "result" + + if l := len("result"); len(elem) >= l && elem[0:l] == "result" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentResultOperation + r.summary = "Read the result of an assessment attempt of the current candidate." + r.operationID = "GetMyAssessmentResult" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/result" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 's': // Prefix: "s" + + if l := len("s"); len(elem) >= l && elem[0:l] == "s" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + break + } + switch elem[0] { + case 'e': // Prefix: "essions" + + if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = StartMyAssessmentAttemptSessionOperation + r.summary = "Start or resume a work session for the current candidate's attempt." + r.operationID = "StartMyAssessmentAttemptSession" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + case 'i': // Prefix: "ignals" + + if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = RecordMyAssessmentAttemptSignalsOperation + r.summary = "Store a bounded batch of client-reported assessment signals." + r.operationID = "RecordMyAssessmentAttemptSignals" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/signals" + r.args = args + r.count = 1 + return r, true + default: + return + } + } + + } + } } } + case 'v': // Prefix: "vailability" + + if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentAvailabilityOperation + r.summary = "Read which assessment attempts the current candidate can start." + r.operationID = "GetMyAssessmentAvailability" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-availability" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + } - case 'v': // Prefix: "vailability" + case 'r': // Prefix: "results" - if l := len("vailability"); len(elem) >= l && elem[0:l] == "vailability" { + if l := len("results"); len(elem) >= l && elem[0:l] == "results" { elem = elem[l:] } else { break @@ -2577,11 +2685,45 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { // Leaf node. switch method { case "GET": - r.name = GetMyAssessmentAvailabilityOperation - r.summary = "Read which assessment attempts the current candidate can start." - r.operationID = "GetMyAssessmentAvailability" + r.name = ListMyAssessmentResultsOperation + r.summary = "List immutable real assessment results of the current candidate." + r.operationID = "ListMyAssessmentResults" r.operationGroup = "" - r.pathPattern = "/api/v1/me/assessment-availability" + r.pathPattern = "/api/v1/me/assessment-results" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + case 's': // Prefix: "signal-notice" + + if l := len("signal-notice"); len(elem) >= l && elem[0:l] == "signal-notice" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "GET": + r.name = GetMyAssessmentSignalNoticeOperation + r.summary = "Read whether the current candidate acknowledged the signal notice." + r.operationID = "GetMyAssessmentSignalNotice" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-signal-notice" + r.args = args + r.count = 0 + return r, true + case "PUT": + r.name = AcknowledgeMyAssessmentSignalNoticeOperation + r.summary = "Record that the current candidate read the signal notice." + r.operationID = "AcknowledgeMyAssessmentSignalNotice" + r.operationGroup = "" + r.pathPattern = "/api/v1/me/assessment-signal-notice" r.args = args r.count = 0 return r, true diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 5f49879..3caa745 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -191,6 +191,22 @@ func (s *AccountScenario) UnmarshalText(data []byte) error { } } +type AcknowledgeMyAssessmentSignalNoticeBadRequest Problem + +func (*AcknowledgeMyAssessmentSignalNoticeBadRequest) acknowledgeMyAssessmentSignalNoticeRes() {} + +type AcknowledgeMyAssessmentSignalNoticeConflict Problem + +func (*AcknowledgeMyAssessmentSignalNoticeConflict) acknowledgeMyAssessmentSignalNoticeRes() {} + +type AcknowledgeMyAssessmentSignalNoticeForbidden Problem + +func (*AcknowledgeMyAssessmentSignalNoticeForbidden) acknowledgeMyAssessmentSignalNoticeRes() {} + +type AcknowledgeMyAssessmentSignalNoticeUnauthorized Problem + +func (*AcknowledgeMyAssessmentSignalNoticeUnauthorized) acknowledgeMyAssessmentSignalNoticeRes() {} + // 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 @@ -1021,12 +1037,213 @@ func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability) func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {} +// 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. +// Ref: #/components/schemas/AssessmentCategoryDecisionView +type AssessmentCategoryDecisionView struct { + Status AssessmentCategoryDecisionViewStatus `json:"status"` + PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + CurrentConfirmedGrade NilGradeCode `json:"current_confirmed_grade"` + Method NilAssessmentCategoryDecisionViewMethod `json:"method"` + Source NilAssessmentCategoryDecisionViewSource `json:"source"` + CalibrationStatus NilCalibrationStatus `json:"calibration_status"` +} + +// GetStatus returns the value of Status. +func (s *AssessmentCategoryDecisionView) GetStatus() AssessmentCategoryDecisionViewStatus { + return s.Status +} + +// GetPreviousConfirmedGrade returns the value of PreviousConfirmedGrade. +func (s *AssessmentCategoryDecisionView) GetPreviousConfirmedGrade() NilGradeCode { + return s.PreviousConfirmedGrade +} + +// GetCurrentConfirmedGrade returns the value of CurrentConfirmedGrade. +func (s *AssessmentCategoryDecisionView) GetCurrentConfirmedGrade() NilGradeCode { + return s.CurrentConfirmedGrade +} + +// GetMethod returns the value of Method. +func (s *AssessmentCategoryDecisionView) GetMethod() NilAssessmentCategoryDecisionViewMethod { + return s.Method +} + +// GetSource returns the value of Source. +func (s *AssessmentCategoryDecisionView) GetSource() NilAssessmentCategoryDecisionViewSource { + return s.Source +} + +// GetCalibrationStatus returns the value of CalibrationStatus. +func (s *AssessmentCategoryDecisionView) GetCalibrationStatus() NilCalibrationStatus { + return s.CalibrationStatus +} + +// SetStatus sets the value of Status. +func (s *AssessmentCategoryDecisionView) SetStatus(val AssessmentCategoryDecisionViewStatus) { + s.Status = val +} + +// SetPreviousConfirmedGrade sets the value of PreviousConfirmedGrade. +func (s *AssessmentCategoryDecisionView) SetPreviousConfirmedGrade(val NilGradeCode) { + s.PreviousConfirmedGrade = val +} + +// SetCurrentConfirmedGrade sets the value of CurrentConfirmedGrade. +func (s *AssessmentCategoryDecisionView) SetCurrentConfirmedGrade(val NilGradeCode) { + s.CurrentConfirmedGrade = val +} + +// SetMethod sets the value of Method. +func (s *AssessmentCategoryDecisionView) SetMethod(val NilAssessmentCategoryDecisionViewMethod) { + s.Method = val +} + +// SetSource sets the value of Source. +func (s *AssessmentCategoryDecisionView) SetSource(val NilAssessmentCategoryDecisionViewSource) { + s.Source = val +} + +// SetCalibrationStatus sets the value of CalibrationStatus. +func (s *AssessmentCategoryDecisionView) SetCalibrationStatus(val NilCalibrationStatus) { + s.CalibrationStatus = val +} + +type AssessmentCategoryDecisionViewMethod string + +const ( + AssessmentCategoryDecisionViewMethodDemoBasicPassMark AssessmentCategoryDecisionViewMethod = "demo_basic_pass_mark" +) + +// AllValues returns all AssessmentCategoryDecisionViewMethod values. +func (AssessmentCategoryDecisionViewMethod) AllValues() []AssessmentCategoryDecisionViewMethod { + return []AssessmentCategoryDecisionViewMethod{ + AssessmentCategoryDecisionViewMethodDemoBasicPassMark, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCategoryDecisionViewMethod) MarshalText() ([]byte, error) { + switch s { + case AssessmentCategoryDecisionViewMethodDemoBasicPassMark: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCategoryDecisionViewMethod) UnmarshalText(data []byte) error { + switch AssessmentCategoryDecisionViewMethod(data) { + case AssessmentCategoryDecisionViewMethodDemoBasicPassMark: + *s = AssessmentCategoryDecisionViewMethodDemoBasicPassMark + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentCategoryDecisionViewSource string + +const ( + AssessmentCategoryDecisionViewSourceSyntheticDemo AssessmentCategoryDecisionViewSource = "synthetic_demo" +) + +// AllValues returns all AssessmentCategoryDecisionViewSource values. +func (AssessmentCategoryDecisionViewSource) AllValues() []AssessmentCategoryDecisionViewSource { + return []AssessmentCategoryDecisionViewSource{ + AssessmentCategoryDecisionViewSourceSyntheticDemo, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCategoryDecisionViewSource) MarshalText() ([]byte, error) { + switch s { + case AssessmentCategoryDecisionViewSourceSyntheticDemo: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCategoryDecisionViewSource) UnmarshalText(data []byte) error { + switch AssessmentCategoryDecisionViewSource(data) { + case AssessmentCategoryDecisionViewSourceSyntheticDemo: + *s = AssessmentCategoryDecisionViewSourceSyntheticDemo + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + +type AssessmentCategoryDecisionViewStatus string + +const ( + AssessmentCategoryDecisionViewStatusNotEligible AssessmentCategoryDecisionViewStatus = "not_eligible" + AssessmentCategoryDecisionViewStatusNotConfirmed AssessmentCategoryDecisionViewStatus = "not_confirmed" + AssessmentCategoryDecisionViewStatusAssigned AssessmentCategoryDecisionViewStatus = "assigned" + AssessmentCategoryDecisionViewStatusUnchanged AssessmentCategoryDecisionViewStatus = "unchanged" +) + +// AllValues returns all AssessmentCategoryDecisionViewStatus values. +func (AssessmentCategoryDecisionViewStatus) AllValues() []AssessmentCategoryDecisionViewStatus { + return []AssessmentCategoryDecisionViewStatus{ + AssessmentCategoryDecisionViewStatusNotEligible, + AssessmentCategoryDecisionViewStatusNotConfirmed, + AssessmentCategoryDecisionViewStatusAssigned, + AssessmentCategoryDecisionViewStatusUnchanged, + } +} + +// MarshalText implements encoding.TextMarshaler. +func (s AssessmentCategoryDecisionViewStatus) MarshalText() ([]byte, error) { + switch s { + case AssessmentCategoryDecisionViewStatusNotEligible: + return []byte(s), nil + case AssessmentCategoryDecisionViewStatusNotConfirmed: + return []byte(s), nil + case AssessmentCategoryDecisionViewStatusAssigned: + return []byte(s), nil + case AssessmentCategoryDecisionViewStatusUnchanged: + return []byte(s), nil + default: + return nil, errors.Errorf("invalid value: %q", s) + } +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (s *AssessmentCategoryDecisionViewStatus) UnmarshalText(data []byte) error { + switch AssessmentCategoryDecisionViewStatus(data) { + case AssessmentCategoryDecisionViewStatusNotEligible: + *s = AssessmentCategoryDecisionViewStatusNotEligible + return nil + case AssessmentCategoryDecisionViewStatusNotConfirmed: + *s = AssessmentCategoryDecisionViewStatusNotConfirmed + return nil + case AssessmentCategoryDecisionViewStatusAssigned: + *s = AssessmentCategoryDecisionViewStatusAssigned + return nil + case AssessmentCategoryDecisionViewStatusUnchanged: + *s = AssessmentCategoryDecisionViewStatusUnchanged + return nil + default: + return errors.Errorf("invalid value: %q", data) + } +} + // Ref: #/components/schemas/AssessmentClipboardSignal type AssessmentClipboardSignal struct { Kind AssessmentClipboardSignalKind `json:"kind"` ItemInstanceID AssessmentItemId `json:"item_instance_id"` OccurredAt Timestamp `json:"occurred_at"` - // Byte count only. Clipboard or selection contents are not transmitted or retained. + // 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. SizeBytes int32 `json:"size_bytes"` } @@ -1538,7 +1755,8 @@ type AssessmentCorrectiveResult struct { ConfirmedGrade NilGradeCode `json:"confirmed_grade"` // Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed // nothing, this grade stays in force. - PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + CategoryDecision OptAssessmentCategoryDecisionView `json:"category_decision"` // Strength of an adaptive confirmation, otherwise null. Strength NilAssessmentStrength `json:"strength"` CalibrationStatus CalibrationStatus `json:"calibration_status"` @@ -1622,6 +1840,11 @@ func (s *AssessmentCorrectiveResult) GetPreviousConfirmedGrade() NilGradeCode { return s.PreviousConfirmedGrade } +// GetCategoryDecision returns the value of CategoryDecision. +func (s *AssessmentCorrectiveResult) GetCategoryDecision() OptAssessmentCategoryDecisionView { + return s.CategoryDecision +} + // GetStrength returns the value of Strength. func (s *AssessmentCorrectiveResult) GetStrength() NilAssessmentStrength { return s.Strength @@ -1737,6 +1960,11 @@ func (s *AssessmentCorrectiveResult) SetPreviousConfirmedGrade(val NilGradeCode) s.PreviousConfirmedGrade = val } +// SetCategoryDecision sets the value of CategoryDecision. +func (s *AssessmentCorrectiveResult) SetCategoryDecision(val OptAssessmentCategoryDecisionView) { + s.CategoryDecision = val +} + // SetStrength sets the value of Strength. func (s *AssessmentCorrectiveResult) SetStrength(val NilAssessmentStrength) { s.Strength = val @@ -4131,7 +4359,8 @@ type AssessmentQualifiedResult struct { ConfirmedGrade NilGradeCode `json:"confirmed_grade"` // Confirmed grade of the specialization before this attempt, or null. When the attempt confirmed // nothing, this grade stays in force. - PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + PreviousConfirmedGrade NilGradeCode `json:"previous_confirmed_grade"` + CategoryDecision OptAssessmentCategoryDecisionView `json:"category_decision"` // Strength of an adaptive confirmation, otherwise null. Strength NilAssessmentStrength `json:"strength"` CalibrationStatus CalibrationStatus `json:"calibration_status"` @@ -4215,6 +4444,11 @@ func (s *AssessmentQualifiedResult) GetPreviousConfirmedGrade() NilGradeCode { return s.PreviousConfirmedGrade } +// GetCategoryDecision returns the value of CategoryDecision. +func (s *AssessmentQualifiedResult) GetCategoryDecision() OptAssessmentCategoryDecisionView { + return s.CategoryDecision +} + // GetStrength returns the value of Strength. func (s *AssessmentQualifiedResult) GetStrength() NilAssessmentStrength { return s.Strength @@ -4330,6 +4564,11 @@ func (s *AssessmentQualifiedResult) SetPreviousConfirmedGrade(val NilGradeCode) s.PreviousConfirmedGrade = val } +// SetCategoryDecision sets the value of CategoryDecision. +func (s *AssessmentQualifiedResult) SetCategoryDecision(val OptAssessmentCategoryDecisionView) { + s.CategoryDecision = val +} + // SetStrength sets the value of Strength. func (s *AssessmentQualifiedResult) SetStrength(val NilAssessmentStrength) { s.Strength = val @@ -4499,6 +4738,78 @@ func (s *AssessmentRealMode) UnmarshalText(data []byte) error { } } +// A completed root or corrective result. Training-only demo_express results are excluded from +// qualification history. +// Ref: #/components/schemas/AssessmentRealResult +// AssessmentRealResult represents sum type. +type AssessmentRealResult struct { + // Type selects the active sum variant, switch on this field. + Type AssessmentRealResultType + AssessmentQualifiedResult AssessmentQualifiedResult + AssessmentCorrectiveResult AssessmentCorrectiveResult +} + +// AssessmentRealResultType is oneOf type of AssessmentRealResult. +type AssessmentRealResultType string + +// Possible values for AssessmentRealResultType. +const ( + AssessmentQualifiedResultAssessmentRealResult AssessmentRealResultType = "root" + AssessmentCorrectiveResultAssessmentRealResult AssessmentRealResultType = "corrective" +) + +// IsAssessmentQualifiedResult reports whether AssessmentRealResult is AssessmentQualifiedResult. +func (s AssessmentRealResult) IsAssessmentQualifiedResult() bool { + return s.Type == AssessmentQualifiedResultAssessmentRealResult +} + +// IsAssessmentCorrectiveResult reports whether AssessmentRealResult is AssessmentCorrectiveResult. +func (s AssessmentRealResult) IsAssessmentCorrectiveResult() bool { + return s.Type == AssessmentCorrectiveResultAssessmentRealResult +} + +// SetAssessmentQualifiedResult sets AssessmentRealResult to AssessmentQualifiedResult. +func (s *AssessmentRealResult) SetAssessmentQualifiedResult(v AssessmentQualifiedResult) { + s.Type = AssessmentQualifiedResultAssessmentRealResult + s.AssessmentQualifiedResult = v +} + +// GetAssessmentQualifiedResult returns AssessmentQualifiedResult and true boolean if AssessmentRealResult is AssessmentQualifiedResult. +func (s AssessmentRealResult) GetAssessmentQualifiedResult() (v AssessmentQualifiedResult, ok bool) { + if !s.IsAssessmentQualifiedResult() { + return v, false + } + return s.AssessmentQualifiedResult, true +} + +// NewAssessmentQualifiedResultAssessmentRealResult returns new AssessmentRealResult from AssessmentQualifiedResult. +func NewAssessmentQualifiedResultAssessmentRealResult(v AssessmentQualifiedResult) AssessmentRealResult { + var s AssessmentRealResult + s.SetAssessmentQualifiedResult(v) + return s +} + +// SetAssessmentCorrectiveResult sets AssessmentRealResult to AssessmentCorrectiveResult. +func (s *AssessmentRealResult) SetAssessmentCorrectiveResult(v AssessmentCorrectiveResult) { + s.Type = AssessmentCorrectiveResultAssessmentRealResult + s.AssessmentCorrectiveResult = v +} + +// GetAssessmentCorrectiveResult returns AssessmentCorrectiveResult and true boolean if AssessmentRealResult is AssessmentCorrectiveResult. +func (s AssessmentRealResult) GetAssessmentCorrectiveResult() (v AssessmentCorrectiveResult, ok bool) { + if !s.IsAssessmentCorrectiveResult() { + return v, false + } + return s.AssessmentCorrectiveResult, true +} + +// NewAssessmentCorrectiveResultAssessmentRealResult returns new AssessmentRealResult from AssessmentCorrectiveResult. +func NewAssessmentCorrectiveResultAssessmentRealResult(v AssessmentCorrectiveResult) AssessmentRealResult { + var s AssessmentRealResult + s.SetAssessmentCorrectiveResult(v) + return s +} + // Immutable result of a terminal assessment attempt. The result shape distinguishes real grade // decisions from demo_express training output. // Ref: #/components/schemas/AssessmentResult @@ -4627,6 +4938,62 @@ func (s *AssessmentResultHeaders) SetResponse(val AssessmentResult) { func (*AssessmentResultHeaders) getMyAssessmentResultRes() {} +// Owner-only immutable root and corrective results ordered by decided_at and attempt_id descending. +// Legacy v1 results omit category_decision. +// Ref: #/components/schemas/AssessmentResultHistoryPage +type AssessmentResultHistoryPage struct { + Items []AssessmentRealResult `json:"items"` + Page PageInfo `json:"page"` +} + +// GetItems returns the value of Items. +func (s *AssessmentResultHistoryPage) GetItems() []AssessmentRealResult { + return s.Items +} + +// GetPage returns the value of Page. +func (s *AssessmentResultHistoryPage) GetPage() PageInfo { + return s.Page +} + +// SetItems sets the value of Items. +func (s *AssessmentResultHistoryPage) SetItems(val []AssessmentRealResult) { + s.Items = val +} + +// SetPage sets the value of Page. +func (s *AssessmentResultHistoryPage) SetPage(val PageInfo) { + s.Page = val +} + +// AssessmentResultHistoryPageHeaders wraps AssessmentResultHistoryPage with response headers. +type AssessmentResultHistoryPageHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentResultHistoryPage +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentResultHistoryPageHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentResultHistoryPageHeaders) GetResponse() AssessmentResultHistoryPage { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentResultHistoryPageHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentResultHistoryPageHeaders) SetResponse(val AssessmentResultHistoryPage) { + s.Response = val +} + +func (*AssessmentResultHistoryPageHeaders) listMyAssessmentResultsRes() {} + // Work sessions of the attempt, as the policy version limits them, for example two sessions within the // time limit. // @@ -4817,6 +5184,97 @@ func NewAssessmentFullscreenExitSignalAssessmentSignalEvent(v AssessmentFullscre return s } +// 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. +// Ref: #/components/schemas/AssessmentSignalNotice +type AssessmentSignalNotice struct { + // The version the server currently requires the candidate to acknowledge. + NoticeVersion AssessmentSignalNoticeVersion `json:"notice_version"` + // True when the candidate acknowledged `notice_version`. + Acknowledged bool `json:"acknowledged"` + // Server time of the first acknowledgement of this version, or null. + AcknowledgedAt NilTimestamp `json:"acknowledged_at"` +} + +// GetNoticeVersion returns the value of NoticeVersion. +func (s *AssessmentSignalNotice) GetNoticeVersion() AssessmentSignalNoticeVersion { + return s.NoticeVersion +} + +// GetAcknowledged returns the value of Acknowledged. +func (s *AssessmentSignalNotice) GetAcknowledged() bool { + return s.Acknowledged +} + +// GetAcknowledgedAt returns the value of AcknowledgedAt. +func (s *AssessmentSignalNotice) GetAcknowledgedAt() NilTimestamp { + return s.AcknowledgedAt +} + +// SetNoticeVersion sets the value of NoticeVersion. +func (s *AssessmentSignalNotice) SetNoticeVersion(val AssessmentSignalNoticeVersion) { + s.NoticeVersion = val +} + +// SetAcknowledged sets the value of Acknowledged. +func (s *AssessmentSignalNotice) SetAcknowledged(val bool) { + s.Acknowledged = val +} + +// SetAcknowledgedAt sets the value of AcknowledgedAt. +func (s *AssessmentSignalNotice) SetAcknowledgedAt(val NilTimestamp) { + s.AcknowledgedAt = val +} + +// The notice version the candidate was shown and acknowledged. +// Ref: #/components/schemas/AssessmentSignalNoticeAcknowledgement +type AssessmentSignalNoticeAcknowledgement struct { + NoticeVersion AssessmentSignalNoticeVersion `json:"notice_version"` +} + +// GetNoticeVersion returns the value of NoticeVersion. +func (s *AssessmentSignalNoticeAcknowledgement) GetNoticeVersion() AssessmentSignalNoticeVersion { + return s.NoticeVersion +} + +// SetNoticeVersion sets the value of NoticeVersion. +func (s *AssessmentSignalNoticeAcknowledgement) SetNoticeVersion(val AssessmentSignalNoticeVersion) { + s.NoticeVersion = val +} + +// AssessmentSignalNoticeHeaders wraps AssessmentSignalNotice with response headers. +type AssessmentSignalNoticeHeaders struct { + CacheControl CacheControlNoStore + Response AssessmentSignalNotice +} + +// GetCacheControl returns the value of CacheControl. +func (s *AssessmentSignalNoticeHeaders) GetCacheControl() CacheControlNoStore { + return s.CacheControl +} + +// GetResponse returns the value of Response. +func (s *AssessmentSignalNoticeHeaders) GetResponse() AssessmentSignalNotice { + return s.Response +} + +// SetCacheControl sets the value of CacheControl. +func (s *AssessmentSignalNoticeHeaders) SetCacheControl(val CacheControlNoStore) { + s.CacheControl = val +} + +// SetResponse sets the value of Response. +func (s *AssessmentSignalNoticeHeaders) SetResponse(val AssessmentSignalNotice) { + s.Response = val +} + +func (*AssessmentSignalNoticeHeaders) acknowledgeMyAssessmentSignalNoticeRes() {} +func (*AssessmentSignalNoticeHeaders) getMyAssessmentSignalNoticeRes() {} + +type AssessmentSignalNoticeVersion int32 + // Receipt for the submitted batch. It contains no signal details, score, review decision, threshold, // or result band. // Ref: #/components/schemas/AssessmentSignalReceipt @@ -9452,6 +9910,14 @@ type GetMyAssessmentResultUnauthorized Problem func (*GetMyAssessmentResultUnauthorized) getMyAssessmentResultRes() {} +type GetMyAssessmentSignalNoticeForbidden Problem + +func (*GetMyAssessmentSignalNoticeForbidden) getMyAssessmentSignalNoticeRes() {} + +type GetMyAssessmentSignalNoticeUnauthorized Problem + +func (*GetMyAssessmentSignalNoticeUnauthorized) getMyAssessmentSignalNoticeRes() {} + type GetMyCardPreviewForbidden Problem func (*GetMyCardPreviewForbidden) getMyCardPreviewRes() {} @@ -11413,6 +11879,18 @@ func NewPracticeItemContentItemContent(v PracticeItemContent) ItemContent { return s } +type ListMyAssessmentResultsBadRequest Problem + +func (*ListMyAssessmentResultsBadRequest) listMyAssessmentResultsRes() {} + +type ListMyAssessmentResultsForbidden Problem + +func (*ListMyAssessmentResultsForbidden) listMyAssessmentResultsRes() {} + +type ListMyAssessmentResultsUnauthorized Problem + +func (*ListMyAssessmentResultsUnauthorized) listMyAssessmentResultsRes() {} + type ListMyCardAccessHistoryBadRequest Problem func (*ListMyCardAccessHistoryBadRequest) listMyCardAccessHistoryRes() {} @@ -15727,6 +16205,96 @@ func (o NilAnonymousCardContent) Or(d AnonymousCardContent) AnonymousCardContent return d } +// NewNilAssessmentCategoryDecisionViewMethod returns new NilAssessmentCategoryDecisionViewMethod with value set to v. +func NewNilAssessmentCategoryDecisionViewMethod(v AssessmentCategoryDecisionViewMethod) NilAssessmentCategoryDecisionViewMethod { + return NilAssessmentCategoryDecisionViewMethod{ + Value: v, + } +} + +// NilAssessmentCategoryDecisionViewMethod is nullable AssessmentCategoryDecisionViewMethod. +type NilAssessmentCategoryDecisionViewMethod struct { + Value AssessmentCategoryDecisionViewMethod + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentCategoryDecisionViewMethod) SetTo(v AssessmentCategoryDecisionViewMethod) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentCategoryDecisionViewMethod) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentCategoryDecisionViewMethod) SetToNull() { + o.Null = true + var v AssessmentCategoryDecisionViewMethod + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentCategoryDecisionViewMethod) Get() (v AssessmentCategoryDecisionViewMethod, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentCategoryDecisionViewMethod) Or(d AssessmentCategoryDecisionViewMethod) AssessmentCategoryDecisionViewMethod { + if v, ok := o.Get(); ok { + return v + } + return d +} + +// NewNilAssessmentCategoryDecisionViewSource returns new NilAssessmentCategoryDecisionViewSource with value set to v. +func NewNilAssessmentCategoryDecisionViewSource(v AssessmentCategoryDecisionViewSource) NilAssessmentCategoryDecisionViewSource { + return NilAssessmentCategoryDecisionViewSource{ + Value: v, + } +} + +// NilAssessmentCategoryDecisionViewSource is nullable AssessmentCategoryDecisionViewSource. +type NilAssessmentCategoryDecisionViewSource struct { + Value AssessmentCategoryDecisionViewSource + Null bool +} + +// SetTo sets value to v. +func (o *NilAssessmentCategoryDecisionViewSource) SetTo(v AssessmentCategoryDecisionViewSource) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilAssessmentCategoryDecisionViewSource) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilAssessmentCategoryDecisionViewSource) SetToNull() { + o.Null = true + var v AssessmentCategoryDecisionViewSource + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilAssessmentCategoryDecisionViewSource) Get() (v AssessmentCategoryDecisionViewSource, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilAssessmentCategoryDecisionViewSource) Or(d AssessmentCategoryDecisionViewSource) AssessmentCategoryDecisionViewSource { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilAssessmentItem returns new NilAssessmentItem with value set to v. func NewNilAssessmentItem(v AssessmentItem) NilAssessmentItem { return NilAssessmentItem{ @@ -16087,6 +16655,51 @@ func (o NilBool) Or(d bool) bool { return d } +// NewNilCalibrationStatus returns new NilCalibrationStatus with value set to v. +func NewNilCalibrationStatus(v CalibrationStatus) NilCalibrationStatus { + return NilCalibrationStatus{ + Value: v, + } +} + +// NilCalibrationStatus is nullable CalibrationStatus. +type NilCalibrationStatus struct { + Value CalibrationStatus + Null bool +} + +// SetTo sets value to v. +func (o *NilCalibrationStatus) SetTo(v CalibrationStatus) { + o.Null = false + o.Value = v +} + +// IsNull returns true if value is Null. +func (o NilCalibrationStatus) IsNull() bool { return o.Null } + +// SetToNull sets value to null. +func (o *NilCalibrationStatus) SetToNull() { + o.Null = true + var v CalibrationStatus + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o NilCalibrationStatus) Get() (v CalibrationStatus, ok bool) { + if o.Null { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o NilCalibrationStatus) Or(d CalibrationStatus) CalibrationStatus { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewNilCandidateExperience returns new NilCandidateExperience with value set to v. func NewNilCandidateExperience(v CandidateExperience) NilCandidateExperience { return NilCandidateExperience{ @@ -19356,6 +19969,52 @@ func (s *OnboardingStep) UnmarshalText(data []byte) error { } } +// NewOptAssessmentCategoryDecisionView returns new OptAssessmentCategoryDecisionView with value set to v. +func NewOptAssessmentCategoryDecisionView(v AssessmentCategoryDecisionView) OptAssessmentCategoryDecisionView { + return OptAssessmentCategoryDecisionView{ + Value: v, + Set: true, + } +} + +// OptAssessmentCategoryDecisionView is optional AssessmentCategoryDecisionView. +type OptAssessmentCategoryDecisionView struct { + Value AssessmentCategoryDecisionView + Set bool +} + +// IsSet returns true if OptAssessmentCategoryDecisionView was set. +func (o OptAssessmentCategoryDecisionView) IsSet() bool { return o.Set } + +// Reset unsets value. +func (o *OptAssessmentCategoryDecisionView) Reset() { + var v AssessmentCategoryDecisionView + o.Value = v + o.Set = false +} + +// SetTo sets value to v. +func (o *OptAssessmentCategoryDecisionView) SetTo(v AssessmentCategoryDecisionView) { + o.Set = true + o.Value = v +} + +// Get returns value and boolean that denotes whether value was set. +func (o OptAssessmentCategoryDecisionView) Get() (v AssessmentCategoryDecisionView, ok bool) { + if !o.Set { + return v, false + } + return o.Value, true +} + +// Or returns value if set, or given parameter if does not. +func (o OptAssessmentCategoryDecisionView) Or(d AssessmentCategoryDecisionView) AssessmentCategoryDecisionView { + if v, ok := o.Get(); ok { + return v + } + return d +} + // NewOptCandidateSalaryCompatibility returns new OptCandidateSalaryCompatibility with value set to v. func NewOptCandidateSalaryCompatibility(v CandidateSalaryCompatibility) OptCandidateSalaryCompatibility { return OptCandidateSalaryCompatibility{ diff --git a/backend/internal/adapter/primary/http/api/oas_security_gen.go b/backend/internal/adapter/primary/http/api/oas_security_gen.go index 7bd1ea0..ce685fe 100644 --- a/backend/internal/adapter/primary/http/api/oas_security_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_security_gen.go @@ -56,63 +56,66 @@ func findAuthorization(h http.Header, prefix string) (string, bool) { // operationRolesSessionCookie is a private map storing roles per operation. var operationRolesSessionCookie = map[string][]string{ - AcceptMyInvitationOperation: []string{}, - CancelMyInvitationOperation: []string{}, - CreateMyAssessmentAttemptOperation: []string{}, - CreateMySupportCaseOperation: []string{}, - CreateOrganizationOperation: []string{}, - CreateOrganizationInvitationOperation: []string{}, - CreateOrganizationNeedOperation: []string{}, - DeclineMyInvitationOperation: []string{}, - FinalizeMyAssessmentAttemptOperation: []string{}, - GetCurrentAccountOperation: []string{}, - GetCurrentSessionOperation: []string{}, - GetMyAssessmentAttemptOperation: []string{}, - GetMyAssessmentAvailabilityOperation: []string{}, - GetMyAssessmentResultOperation: []string{}, - GetMyCardPreviewOperation: []string{}, - GetMyConsentTextOperation: []string{}, - GetMyInvitationOperation: []string{}, - GetMyPrivacySettingsOperation: []string{}, - GetMyProfileOperation: []string{}, - GetMyQuestionnaireOperation: []string{}, - GetMySupportCaseOperation: []string{}, - GetOrganizationOperation: []string{}, - GetOrganizationCandidateCardOperation: []string{}, - GetOrganizationInvitationOperation: []string{}, - GetOrganizationInvitationContactsOperation: []string{}, - GetOrganizationNeedOperation: []string{}, - GrantMyConsentOperation: []string{}, - HideOrganizationOperation: []string{}, - ListMyCardAccessHistoryOperation: []string{}, - ListMyConsentsOperation: []string{}, - ListMyHiddenOrganizationsOperation: []string{}, - ListMyInvitationsOperation: []string{}, - ListMyOrganizationsOperation: []string{}, - ListMyPrivacyHistoryOperation: []string{}, - ListMySupportCasesOperation: []string{}, - ListOrganizationInvitationsOperation: []string{}, - ListOrganizationNeedsOperation: []string{}, - LogoutOperation: []string{}, - RaiseOrganizationInvitationSalaryOperation: []string{}, - RecordMyAssessmentAttemptSignalsOperation: []string{}, - RequestMyAccountDeletionOperation: []string{}, - RevokeMyConsentOperation: []string{}, - RevokeMyOrganizationContactConsentOperation: []string{}, - SaveMyProfileOperation: []string{}, - SaveMyQuestionnaireOperation: []string{}, - SearchOrganizationMatchesOperation: []string{}, - SendOrganizationInvitationOperation: []string{}, - SetMyPublicationOperation: []string{}, - SetMySearchStatusOperation: []string{}, - StartMyAssessmentAttemptSessionOperation: []string{}, - SubmitMyAssessmentAnswerOperation: []string{}, - UnhideOrganizationOperation: []string{}, - UpdateOrganizationOperation: []string{}, - UpdateOrganizationInvitationOperation: []string{}, - UpdateOrganizationNeedOperation: []string{}, - ViewMyInvitationOperation: []string{}, - WithdrawOrganizationInvitationOperation: []string{}, + AcceptMyInvitationOperation: []string{}, + AcknowledgeMyAssessmentSignalNoticeOperation: []string{}, + CancelMyInvitationOperation: []string{}, + CreateMyAssessmentAttemptOperation: []string{}, + CreateMySupportCaseOperation: []string{}, + CreateOrganizationOperation: []string{}, + CreateOrganizationInvitationOperation: []string{}, + CreateOrganizationNeedOperation: []string{}, + DeclineMyInvitationOperation: []string{}, + FinalizeMyAssessmentAttemptOperation: []string{}, + GetCurrentAccountOperation: []string{}, + GetCurrentSessionOperation: []string{}, + GetMyAssessmentAttemptOperation: []string{}, + GetMyAssessmentAvailabilityOperation: []string{}, + GetMyAssessmentResultOperation: []string{}, + GetMyAssessmentSignalNoticeOperation: []string{}, + GetMyCardPreviewOperation: []string{}, + GetMyConsentTextOperation: []string{}, + GetMyInvitationOperation: []string{}, + GetMyPrivacySettingsOperation: []string{}, + GetMyProfileOperation: []string{}, + GetMyQuestionnaireOperation: []string{}, + GetMySupportCaseOperation: []string{}, + GetOrganizationOperation: []string{}, + GetOrganizationCandidateCardOperation: []string{}, + GetOrganizationInvitationOperation: []string{}, + GetOrganizationInvitationContactsOperation: []string{}, + GetOrganizationNeedOperation: []string{}, + GrantMyConsentOperation: []string{}, + HideOrganizationOperation: []string{}, + ListMyAssessmentResultsOperation: []string{}, + ListMyCardAccessHistoryOperation: []string{}, + ListMyConsentsOperation: []string{}, + ListMyHiddenOrganizationsOperation: []string{}, + ListMyInvitationsOperation: []string{}, + ListMyOrganizationsOperation: []string{}, + ListMyPrivacyHistoryOperation: []string{}, + ListMySupportCasesOperation: []string{}, + ListOrganizationInvitationsOperation: []string{}, + ListOrganizationNeedsOperation: []string{}, + LogoutOperation: []string{}, + RaiseOrganizationInvitationSalaryOperation: []string{}, + RecordMyAssessmentAttemptSignalsOperation: []string{}, + RequestMyAccountDeletionOperation: []string{}, + RevokeMyConsentOperation: []string{}, + RevokeMyOrganizationContactConsentOperation: []string{}, + SaveMyProfileOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, + SearchOrganizationMatchesOperation: []string{}, + SendOrganizationInvitationOperation: []string{}, + SetMyPublicationOperation: []string{}, + SetMySearchStatusOperation: []string{}, + StartMyAssessmentAttemptSessionOperation: []string{}, + SubmitMyAssessmentAnswerOperation: []string{}, + UnhideOrganizationOperation: []string{}, + UpdateOrganizationOperation: []string{}, + UpdateOrganizationInvitationOperation: []string{}, + UpdateOrganizationNeedOperation: []string{}, + ViewMyInvitationOperation: []string{}, + WithdrawOrganizationInvitationOperation: []string{}, } // GetRolesForSessionCookie returns the required roles for the given operation. @@ -138,37 +141,38 @@ func GetRolesForSessionCookie(operation string) []string { // operationRolesSessionCsrf is a private map storing roles per operation. var operationRolesSessionCsrf = map[string][]string{ - AcceptMyInvitationOperation: []string{}, - CancelMyInvitationOperation: []string{}, - CreateMyAssessmentAttemptOperation: []string{}, - CreateMySupportCaseOperation: []string{}, - CreateOrganizationOperation: []string{}, - CreateOrganizationInvitationOperation: []string{}, - CreateOrganizationNeedOperation: []string{}, - DeclineMyInvitationOperation: []string{}, - FinalizeMyAssessmentAttemptOperation: []string{}, - GrantMyConsentOperation: []string{}, - HideOrganizationOperation: []string{}, - LogoutOperation: []string{}, - RaiseOrganizationInvitationSalaryOperation: []string{}, - RecordMyAssessmentAttemptSignalsOperation: []string{}, - RequestMyAccountDeletionOperation: []string{}, - RevokeMyConsentOperation: []string{}, - RevokeMyOrganizationContactConsentOperation: []string{}, - SaveMyProfileOperation: []string{}, - SaveMyQuestionnaireOperation: []string{}, - SearchOrganizationMatchesOperation: []string{}, - SendOrganizationInvitationOperation: []string{}, - SetMyPublicationOperation: []string{}, - SetMySearchStatusOperation: []string{}, - StartMyAssessmentAttemptSessionOperation: []string{}, - SubmitMyAssessmentAnswerOperation: []string{}, - UnhideOrganizationOperation: []string{}, - UpdateOrganizationOperation: []string{}, - UpdateOrganizationInvitationOperation: []string{}, - UpdateOrganizationNeedOperation: []string{}, - ViewMyInvitationOperation: []string{}, - WithdrawOrganizationInvitationOperation: []string{}, + AcceptMyInvitationOperation: []string{}, + AcknowledgeMyAssessmentSignalNoticeOperation: []string{}, + CancelMyInvitationOperation: []string{}, + CreateMyAssessmentAttemptOperation: []string{}, + CreateMySupportCaseOperation: []string{}, + CreateOrganizationOperation: []string{}, + CreateOrganizationInvitationOperation: []string{}, + CreateOrganizationNeedOperation: []string{}, + DeclineMyInvitationOperation: []string{}, + FinalizeMyAssessmentAttemptOperation: []string{}, + GrantMyConsentOperation: []string{}, + HideOrganizationOperation: []string{}, + LogoutOperation: []string{}, + RaiseOrganizationInvitationSalaryOperation: []string{}, + RecordMyAssessmentAttemptSignalsOperation: []string{}, + RequestMyAccountDeletionOperation: []string{}, + RevokeMyConsentOperation: []string{}, + RevokeMyOrganizationContactConsentOperation: []string{}, + SaveMyProfileOperation: []string{}, + SaveMyQuestionnaireOperation: []string{}, + SearchOrganizationMatchesOperation: []string{}, + SendOrganizationInvitationOperation: []string{}, + SetMyPublicationOperation: []string{}, + SetMySearchStatusOperation: []string{}, + StartMyAssessmentAttemptSessionOperation: []string{}, + SubmitMyAssessmentAnswerOperation: []string{}, + UnhideOrganizationOperation: []string{}, + UpdateOrganizationOperation: []string{}, + UpdateOrganizationInvitationOperation: []string{}, + UpdateOrganizationNeedOperation: []string{}, + ViewMyInvitationOperation: []string{}, + WithdrawOrganizationInvitationOperation: []string{}, } // GetRolesForSessionCsrf returns the required roles for the given operation. diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index dcc939d..d95379e 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -64,6 +64,27 @@ type Handler interface { // // POST /api/v1/me/invitations/{invitation_id}/accept AcceptMyInvitation(ctx context.Context, req *InvitationAcceptance, params AcceptMyInvitationParams) (AcceptMyInvitationRes, error) + // AcknowledgeMyAssessmentSignalNotice implements AcknowledgeMyAssessmentSignalNotice operation. + // + // 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). + // + // PUT /api/v1/me/assessment-signal-notice + AcknowledgeMyAssessmentSignalNotice(ctx context.Context, req *AssessmentSignalNoticeAcknowledgement) (AcknowledgeMyAssessmentSignalNoticeRes, error) // CancelMyInvitation implements CancelMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -599,6 +620,30 @@ type Handler interface { // // GET /api/v1/me/assessment-attempts/{attempt_id}/result GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error) + // GetMyAssessmentSignalNotice implements GetMyAssessmentSignalNotice operation. + // + // 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 client shows it 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. 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. + // + // GET /api/v1/me/assessment-signal-notice + GetMyAssessmentSignalNotice(ctx context.Context) (GetMyAssessmentSignalNoticeRes, error) // GetMyCardPreview implements GetMyCardPreview operation. // // Requires the session cookie of a candidate account. Returns a private preview of the permitted @@ -956,6 +1001,21 @@ type Handler interface { // // PUT /api/v1/me/privacy/hidden-organizations/{org_id} HideOrganization(ctx context.Context, params HideOrganizationParams) (HideOrganizationRes, error) + // ListMyAssessmentResults implements ListMyAssessmentResults operation. + // + // 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. + // + // GET /api/v1/me/assessment-results + ListMyAssessmentResults(ctx context.Context, params ListMyAssessmentResultsParams) (ListMyAssessmentResultsRes, error) // ListMyCardAccessHistory implements ListMyCardAccessHistory operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, so the diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 49105a4..6c87553 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -72,6 +72,30 @@ func (UnimplementedHandler) AcceptMyInvitation(ctx context.Context, req *Invitat return r, ht.ErrNotImplemented } +// AcknowledgeMyAssessmentSignalNotice implements AcknowledgeMyAssessmentSignalNotice operation. +// +// 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). +// +// PUT /api/v1/me/assessment-signal-notice +func (UnimplementedHandler) AcknowledgeMyAssessmentSignalNotice(ctx context.Context, req *AssessmentSignalNoticeAcknowledgement) (r AcknowledgeMyAssessmentSignalNoticeRes, _ error) { + return r, ht.ErrNotImplemented +} + // CancelMyInvitation implements CancelMyInvitation operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, @@ -655,6 +679,33 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge return r, ht.ErrNotImplemented } +// GetMyAssessmentSignalNotice implements GetMyAssessmentSignalNotice operation. +// +// 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 client shows it 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. 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. +// +// GET /api/v1/me/assessment-signal-notice +func (UnimplementedHandler) GetMyAssessmentSignalNotice(ctx context.Context) (r GetMyAssessmentSignalNoticeRes, _ error) { + return r, ht.ErrNotImplemented +} + // GetMyCardPreview implements GetMyCardPreview operation. // // Requires the session cookie of a candidate account. Returns a private preview of the permitted @@ -1057,6 +1108,24 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg return r, ht.ErrNotImplemented } +// ListMyAssessmentResults implements ListMyAssessmentResults operation. +// +// 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. +// +// GET /api/v1/me/assessment-results +func (UnimplementedHandler) ListMyAssessmentResults(ctx context.Context, params ListMyAssessmentResultsParams) (r ListMyAssessmentResultsRes, _ error) { + return r, ht.ErrNotImplemented +} + // ListMyCardAccessHistory implements ListMyCardAccessHistory operation. // // Requires the session cookie of a candidate account. The candidate comes from the session, so the diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index 5a9f384..d66093a 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -155,6 +155,38 @@ func (s AccountScenario) Validate() error { } } +func (s *AcknowledgeMyAssessmentSignalNoticeBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcknowledgeMyAssessmentSignalNoticeConflict) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcknowledgeMyAssessmentSignalNoticeForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *AcknowledgeMyAssessmentSignalNoticeUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *AnonymousCardContent) Validate() error { if s == nil { return validate.ErrNilPointer @@ -717,6 +749,152 @@ func (s *AssessmentAvailabilityHeaders) Validate() error { return nil } +func (s *AssessmentCategoryDecisionView) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Status.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "status", + Error: err, + }) + } + if err := func() error { + if value, ok := s.PreviousConfirmedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "previous_confirmed_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.CurrentConfirmedGrade.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "current_confirmed_grade", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Method.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "method", + Error: err, + }) + } + if err := func() error { + if value, ok := s.Source.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "source", + Error: err, + }) + } + if err := func() error { + if value, ok := s.CalibrationStatus.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "calibration_status", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentCategoryDecisionViewMethod) Validate() error { + switch s { + case "demo_basic_pass_mark": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentCategoryDecisionViewSource) Validate() error { + switch s { + case "synthetic_demo": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + +func (s AssessmentCategoryDecisionViewStatus) Validate() error { + switch s { + case "not_eligible": + return nil + case "not_confirmed": + return nil + case "assigned": + return nil + case "unchanged": + return nil + default: + return errors.Errorf("invalid value: %v", s) + } +} + func (s *AssessmentClipboardSignal) Validate() error { if s == nil { return validate.ErrNilPointer @@ -1214,6 +1392,24 @@ func (s *AssessmentCorrectiveResult) Validate() error { Error: err, }) } + if err := func() error { + if value, ok := s.CategoryDecision.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "category_decision", + Error: err, + }) + } if err := func() error { if value, ok := s.Strength.Get(); ok { if err := func() error { @@ -3470,6 +3666,24 @@ func (s *AssessmentQualifiedResult) Validate() error { Error: err, }) } + if err := func() error { + if value, ok := s.CategoryDecision.Get(); ok { + if err := func() error { + if err := value.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "category_decision", + Error: err, + }) + } if err := func() error { if value, ok := s.Strength.Get(); ok { if err := func() error { @@ -3730,6 +3944,23 @@ func (s AssessmentRealMode) Validate() error { } } +func (s AssessmentRealResult) Validate() error { + switch s.Type { + case AssessmentQualifiedResultAssessmentRealResult: + if err := s.AssessmentQualifiedResult.Validate(); err != nil { + return err + } + return nil + case AssessmentCorrectiveResultAssessmentRealResult: + if err := s.AssessmentCorrectiveResult.Validate(); err != nil { + return err + } + return nil + default: + return errors.Errorf("invalid type %q", s.Type) + } +} + func (s AssessmentResult) Validate() error { switch s.Type { case AssessmentQualifiedResultAssessmentResult: @@ -3786,6 +4017,99 @@ func (s *AssessmentResultHeaders) Validate() error { return nil } +func (s *AssessmentResultHistoryPage) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if s.Items == nil { + return errors.New("nil is invalid value") + } + if err := (validate.Array{ + MinLength: 0, + MinLengthSet: false, + MaxLength: 50, + MaxLengthSet: true, + }).ValidateLength(len(s.Items)); err != nil { + return errors.Wrap(err, "array") + } + var failures []validate.FieldError + for i, elem := range s.Items { + if err := func() error { + if err := elem.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: fmt.Sprintf("[%d]", i), + Error: err, + }) + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "items", + Error: err, + }) + } + if err := func() error { + if err := s.Page.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "page", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentResultHistoryPageHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *AssessmentSessions) Validate() error { if s == nil { return validate.ErrNilPointer @@ -3931,6 +4255,104 @@ func (s AssessmentSignalEvent) Validate() error { } } +func (s *AssessmentSignalNotice) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.NoticeVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "notice_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentSignalNoticeAcknowledgement) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.NoticeVersion.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "notice_version", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s *AssessmentSignalNoticeHeaders) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.CacheControl.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "CacheControl", + Error: err, + }) + } + if err := func() error { + if err := s.Response.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "Response", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + +func (s AssessmentSignalNoticeVersion) Validate() error { + alias := (int32)(s) + if err := (validate.Int{ + MinSet: true, + Min: 1, + MaxSet: true, + Max: 2147483647, + MinExclusive: false, + MaxExclusive: false, + MultipleOfSet: false, + MultipleOf: 0, + Pattern: nil, + }).Validate(int64(alias)); err != nil { + return errors.Wrap(err, "int") + } + return nil +} + func (s *AssessmentSignalReceipt) Validate() error { if s == nil { return validate.ErrNilPointer @@ -8765,6 +9187,22 @@ func (s *GetMyAssessmentResultUnauthorized) Validate() error { return nil } +func (s *GetMyAssessmentSignalNoticeForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *GetMyAssessmentSignalNoticeUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *GetMyCardPreviewForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -10412,6 +10850,30 @@ func (s ItemContent) Validate() error { } } +func (s *ListMyAssessmentResultsBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyAssessmentResultsForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ListMyAssessmentResultsUnauthorized) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ListMyCardAccessHistoryBadRequest) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { diff --git a/backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go b/backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go new file mode 100644 index 0000000..2cea607 --- /dev/null +++ b/backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go @@ -0,0 +1,127 @@ +package httpadapter + +import ( + "slices" + "strings" + "testing" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// reviewBandTerms are fragments of the names that would carry the manual-review +// band, its reasons, or the facts behind it. The band is read by an operator +// command only; no HTTP operation, whoever calls it, may declare any of them. +var reviewBandTerms = []string{ + "review_band", "integrity", "signal_review", "attempt_review", "reviewband", "answer_fingerprint", + "fingerprint", "duplicate_answer", "duplicate_evidence", "matched_integer", "matched_sequence", + "parallel_session", "parallel_alternation", "address_change", "fast_answers", "deviating_answers", + "origin_mark", "network_digest", "session_digest", "evidence_bits", +} + +// declaredPropertyNames collects the names under every "properties" key of a +// decoded contract value. +func declaredPropertyNames(value any, found map[string]bool) { + switch typed := value.(type) { + case map[string]any: + for key, child := range typed { + if properties, ok := child.(map[string]any); ok && key == "properties" { + for name := range properties { + found[name] = true + } + } + declaredPropertyNames(child, found) + } + case []any: + for _, child := range typed { + declaredPropertyNames(child, found) + } + } +} + +// declaredEnumValues collects every string in an "enum" array. +func declaredEnumValues(value any, found map[string]bool) { + switch typed := value.(type) { + case map[string]any: + for key, child := range typed { + if values, ok := child.([]any); ok && key == "enum" { + for _, entry := range values { + if text, ok := entry.(string); ok { + found[text] = true + } + } + } + declaredEnumValues(child, found) + } + case []any: + for _, child := range typed { + declaredEnumValues(child, found) + } + } +} + +// No operation reaches the review band. Candidate reads, employer reads, and +// every other operation are walked through all references: request bodies, +// responses, parameters, and headers. The band stays server-side until staff +// roles exist; the operator command is the only reader. +func TestNoOperationReachesTheAssessmentReviewBand(t *testing.T) { + spec := parsePublicContract(t) + index := componentsIndex(t, spec) + if len(spec.Paths) == 0 { + t.Fatal("the contract declares no path") + } + operations := 0 + for path, item := range spec.Paths { + operations++ + value := mustJSONValue(t, item) + properties, enums := map[string]bool{}, map[string]bool{} + declaredPropertyNames(value, properties) + declaredEnumValues(value, enums) + for name := range reachableSchemas(index, value) { + lowered := strings.ToLower(name) + for _, term := range []string{"reviewband", "signalreview", "attemptreview", "assessmentreview", "fingerprint", "originmark"} { + if strings.Contains(lowered, term) { + t.Errorf("%s reaches the schema %s", path, name) + } + } + component := mustJSONValue(t, index["#/components/schemas/"+name]) + declaredPropertyNames(component, properties) + declaredEnumValues(component, enums) + } + for name := range properties { + for _, term := range reviewBandTerms { + if strings.Contains(strings.ToLower(name), term) { + t.Errorf("%s declares the property %q", path, name) + } + } + if name == "band" || name == "reasons" { + t.Errorf("%s declares the property %q", path, name) + } + } + if enums["attention"] && enums["review"] { + t.Errorf("%s declares the band values attention and review", path) + } + } + if operations < 10 { + t.Fatalf("walked only %d paths, want the whole contract", operations) + } +} + +// The walk is not vacuous: it reaches the signal receipt, which carries +// counts and a status and nothing of the band. +func TestSignalReceiptDeclaresNoBandAndIsReachable(t *testing.T) { + spec := parsePublicContract(t) + index := componentsIndex(t, spec) + operation := operationByID(t, spec, "RecordMyAssessmentAttemptSignals") + reached := reachableSchemas(index, mustJSONValue(t, operation)) + if !reached["AssessmentSignalReceipt"] { + t.Fatalf("the signal operation reaches %v, want AssessmentSignalReceipt", reached) + } + receipt := spec.Components.Schemas["AssessmentSignalReceipt"] + if got, want := propertyNames(receipt), []string{"accepted_events", "received_at", "status"}; !slices.Equal(got, want) { + t.Errorf("AssessmentSignalReceipt properties = %v, want %v", got, want) + } + if receipt.AdditionalProperties.Bool == nil || *receipt.AdditionalProperties.Bool { + t.Error("AssessmentSignalReceipt accepts unknown properties") + } + assertNoJSONFields(t, api.AssessmentSignalReceipt{}, []string{"band", "review", "reasons", "attention"}) +} diff --git a/backend/internal/adapter/primary/http/v1/assessment.go b/backend/internal/adapter/primary/http/v1/assessment.go index 6f141c6..52f0cbf 100644 --- a/backend/internal/adapter/primary/http/v1/assessment.go +++ b/backend/internal/adapter/primary/http/v1/assessment.go @@ -208,7 +208,7 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer( result, err := operations.SubmitAnswer(ctx, assessmentusecase.SubmitAttemptAnswerCommand{ ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID), ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion), - IdempotencyKey: params.IdempotencyKey, Answer: answer, + IdempotencyKey: params.IdempotencyKey, Answer: answer, Origin: assessmentRequestOrigin(ctx), }) if err != nil { return assessmentAnswerFailure(ctx, err) diff --git a/backend/internal/adapter/primary/http/v1/assessment_origin.go b/backend/internal/adapter/primary/http/v1/assessment_origin.go new file mode 100644 index 0000000..b364c72 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_origin.go @@ -0,0 +1,18 @@ +package v1 + +import ( + "context" + + assessmentusecase "lincodex/backend/internal/usecase/assessment" +) + +// assessmentRequestOrigin hands the authenticated session and the limiter key +// of the client address to the server signals. The usecase turns them into +// keyed digests; neither value is stored or logged. +func assessmentRequestOrigin(ctx context.Context) assessmentusecase.RequestOrigin { + session, ok := sessionFromContext(ctx) + if !ok { + return assessmentusecase.RequestOrigin{} + } + return assessmentusecase.RequestOrigin{SessionID: session.SessionID, ClientKey: clientKey(ctx)} +} diff --git a/backend/internal/adapter/primary/http/v1/assessment_signal.go b/backend/internal/adapter/primary/http/v1/assessment_signal.go index a3d7971..08d23d3 100644 --- a/backend/internal/adapter/primary/http/v1/assessment_signal.go +++ b/backend/internal/adapter/primary/http/v1/assessment_signal.go @@ -23,6 +23,7 @@ type AssessmentSignalOperations interface { // It never logs or returns event details. type AssessmentSignalHandler struct { operations AssessmentSignalOperations + notice AssessmentSignalNoticeOperations } func NewAssessmentSignalHandler(operations AssessmentSignalOperations) *AssessmentSignalHandler { @@ -61,7 +62,7 @@ func (handler *AssessmentSignalHandler) RecordMyAssessmentAttemptSignals( } receipt, err := handler.operations.RecordSignals(ctx, assessmentusecase.RecordSignalsCommand{ ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID), - IdempotencyKey: params.IdempotencyKey, Events: events, + IdempotencyKey: params.IdempotencyKey, Events: events, Origin: assessmentRequestOrigin(ctx), }) if err != nil { return signalFailure(ctx, err) diff --git a/backend/internal/adapter/primary/http/v1/assessment_signal_notice.go b/backend/internal/adapter/primary/http/v1/assessment_signal_notice.go new file mode 100644 index 0000000..8f27323 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_signal_notice.go @@ -0,0 +1,103 @@ +package v1 + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + assessmentusecase "lincodex/backend/internal/usecase/assessment" +) + +// AssessmentSignalNoticeOperations reads and records the acknowledgement of the +// notice about collected assessment signals. +type AssessmentSignalNoticeOperations interface { + GetSignalNotice(ctx context.Context, actorID uuid.UUID) (assessmentusecase.SignalNoticeState, error) + AcknowledgeSignalNotice(ctx context.Context, actorID uuid.UUID, version int32) (assessmentusecase.SignalNoticeState, error) +} + +// WithNotice serves the signal notice operations next to the signal batches. +// Without it those operations answer as not implemented. +func (handler *AssessmentSignalHandler) WithNotice(operations AssessmentSignalNoticeOperations) *AssessmentSignalHandler { + if operations == nil { + panic("v1.AssessmentSignalHandler.WithNotice - notice operations must not be nil") + } + handler.notice = operations + return handler +} + +func (handler *Handler) GetMyAssessmentSignalNotice(ctx context.Context) (api.GetMyAssessmentSignalNoticeRes, error) { + if handler.assessmentSignals == nil || handler.assessmentSignals.notice == nil { + return handler.UnimplementedHandler.GetMyAssessmentSignalNotice(ctx) + } + return handler.assessmentSignals.GetMyAssessmentSignalNotice(ctx) +} + +func (handler *Handler) AcknowledgeMyAssessmentSignalNotice( + ctx context.Context, + request *api.AssessmentSignalNoticeAcknowledgement, +) (api.AcknowledgeMyAssessmentSignalNoticeRes, error) { + if handler.assessmentSignals == nil || handler.assessmentSignals.notice == nil { + return handler.UnimplementedHandler.AcknowledgeMyAssessmentSignalNotice(ctx, request) + } + return handler.assessmentSignals.AcknowledgeMyAssessmentSignalNotice(ctx, request) +} + +func (handler *AssessmentSignalHandler) GetMyAssessmentSignalNotice(ctx context.Context) (api.GetMyAssessmentSignalNoticeRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.GetMyAssessmentSignalNoticeUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + state, err := handler.notice.GetSignalNotice(ctx, principal.UserID) + if err != nil { + if isSignalNoticeForbidden(err) { + return (*api.GetMyAssessmentSignalNoticeForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + } + return nil, err + } + return signalNoticeResponse(state), nil +} + +func (handler *AssessmentSignalHandler) AcknowledgeMyAssessmentSignalNotice( + ctx context.Context, + request *api.AssessmentSignalNoticeAcknowledgement, +) (api.AcknowledgeMyAssessmentSignalNoticeRes, error) { + principal, ok := PrincipalFromContext(ctx) + if !ok { + return (*api.AcknowledgeMyAssessmentSignalNoticeUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil + } + if request == nil { + return (*api.AcknowledgeMyAssessmentSignalNoticeBadRequest)( + &problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response, + ), nil + } + state, err := handler.notice.AcknowledgeSignalNotice(ctx, principal.UserID, int32(request.NoticeVersion)) + switch { + case err == nil: + return signalNoticeResponse(state), nil + case isSignalNoticeForbidden(err): + return (*api.AcknowledgeMyAssessmentSignalNoticeForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil + case errors.Is(err, assessmentusecase.ErrSignalNoticeVersionMismatch): + return (*api.AcknowledgeMyAssessmentSignalNoticeConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil + default: + return nil, err + } +} + +func isSignalNoticeForbidden(err error) bool { + return errors.Is(err, assessmentusecase.ErrAttemptForbidden) || errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified) +} + +func signalNoticeResponse(state assessmentusecase.SignalNoticeState) *api.AssessmentSignalNoticeHeaders { + notice := api.AssessmentSignalNotice{ + NoticeVersion: api.AssessmentSignalNoticeVersion(state.Version), Acknowledged: state.Acknowledged, + } + notice.AcknowledgedAt.SetToNull() + if state.Acknowledged { + notice.AcknowledgedAt.SetTo(api.Timestamp(state.AcknowledgedAt.UTC().Truncate(time.Microsecond))) + } + return &api.AssessmentSignalNoticeHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: notice} +} diff --git a/backend/internal/adapter/primary/http/v1/assessment_signal_notice_test.go b/backend/internal/adapter/primary/http/v1/assessment_signal_notice_test.go new file mode 100644 index 0000000..9b9ba90 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/assessment_signal_notice_test.go @@ -0,0 +1,102 @@ +package v1 + +import ( + "context" + "fmt" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/adapter/primary/http/api" + assessmentusecase "lincodex/backend/internal/usecase/assessment" +) + +type signalNoticeStub struct { + state assessmentusecase.SignalNoticeState + err error + version int32 + calls int +} + +func (stub *signalNoticeStub) GetSignalNotice(context.Context, uuid.UUID) (assessmentusecase.SignalNoticeState, error) { + stub.calls++ + return stub.state, stub.err +} + +func (stub *signalNoticeStub) AcknowledgeSignalNotice( + _ context.Context, + _ uuid.UUID, + version int32, +) (assessmentusecase.SignalNoticeState, error) { + stub.calls++ + stub.version = version + return stub.state, stub.err +} + +func TestSignalNoticeHandlerReturnsNullTimeUntilAcknowledged(t *testing.T) { + stub := &signalNoticeStub{state: assessmentusecase.SignalNoticeState{Version: 1}} + handler := NewAssessmentSignalHandler(&assessmentSignalOperationsStub{}).WithNotice(stub) + result, err := handler.GetMyAssessmentSignalNotice(principalForTest(uuid.New())) + if err != nil { + t.Fatalf("GetMyAssessmentSignalNotice() error = %v", err) + } + response, ok := result.(*api.AssessmentSignalNoticeHeaders) + if !ok { + t.Fatalf("result = %T, want notice headers", result) + } + if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.Acknowledged || + !response.Response.AcknowledgedAt.Null || response.Response.NoticeVersion != 1 { + t.Fatalf("notice response = %+v", response) + } +} + +func TestSignalNoticeHandlerAcknowledgesTheSentVersion(t *testing.T) { + at := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC) + stub := &signalNoticeStub{state: assessmentusecase.SignalNoticeState{Version: 1, Acknowledged: true, AcknowledgedAt: at}} + handler := NewAssessmentSignalHandler(&assessmentSignalOperationsStub{}).WithNotice(stub) + result, err := handler.AcknowledgeMyAssessmentSignalNotice( + principalForTest(uuid.New()), &api.AssessmentSignalNoticeAcknowledgement{NoticeVersion: 1}, + ) + if err != nil { + t.Fatalf("AcknowledgeMyAssessmentSignalNotice() error = %v", err) + } + response, ok := result.(*api.AssessmentSignalNoticeHeaders) + if !ok || !response.Response.Acknowledged || response.Response.AcknowledgedAt.Null || + !time.Time(response.Response.AcknowledgedAt.Value).Equal(at) || stub.version != 1 { + t.Fatalf("result = %#v, sent version %d", result, stub.version) + } +} + +func TestSignalNoticeHandlerMapsFailuresWithoutLeakingDetails(t *testing.T) { + cases := []struct { + name string + err error + want any + }{ + {"version", assessmentusecase.ErrSignalNoticeVersionMismatch, &api.AcknowledgeMyAssessmentSignalNoticeConflict{}}, + {"employer", assessmentusecase.ErrAttemptForbidden, &api.AcknowledgeMyAssessmentSignalNoticeForbidden{}}, + {"unverified", assessmentusecase.ErrAttemptEmailNotVerified, &api.AcknowledgeMyAssessmentSignalNoticeForbidden{}}, + } + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + handler := NewAssessmentSignalHandler(&assessmentSignalOperationsStub{}).WithNotice(&signalNoticeStub{err: testCase.err}) + result, err := handler.AcknowledgeMyAssessmentSignalNotice( + principalForTest(uuid.New()), &api.AssessmentSignalNoticeAcknowledgement{NoticeVersion: 1}, + ) + if err != nil { + t.Fatalf("error = %v, want a typed problem response", err) + } + if gotType, wantType := fmt.Sprintf("%T", result), fmt.Sprintf("%T", testCase.want); gotType != wantType { + t.Fatalf("result type = %s, want %s", gotType, wantType) + } + }) + } +} + +func TestSignalNoticeIsNotImplementedWithoutOperations(t *testing.T) { + handler := &Handler{assessmentSignals: NewAssessmentSignalHandler(&assessmentSignalOperationsStub{})} + if _, err := handler.GetMyAssessmentSignalNotice(principalForTest(uuid.New())); err == nil { + t.Fatal("GetMyAssessmentSignalNotice() without notice operations must not answer as implemented") + } +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_signal_notice.go b/backend/internal/adapter/secondary/postgres/assessment_signal_notice.go new file mode 100644 index 0000000..f004795 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_signal_notice.go @@ -0,0 +1,74 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgtype" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/port/outbound" +) + +var ( + _ outbound.AssessmentSignalNoticeRepositories = (*UnitOfWork)(nil) + _ outbound.AssessmentSignalNoticeRepository = assessmentSignalNoticeRepository{} +) + +func (unit *UnitOfWork) AssessmentSignalNotices() outbound.AssessmentSignalNoticeRepository { + return assessmentSignalNoticeRepository{queries: unit.queries} +} + +type assessmentSignalNoticeRepository struct { + queries *sqlc.Queries +} + +func (repository assessmentSignalNoticeRepository) Get( + ctx context.Context, + userID uuid.UUID, + version int32, +) (time.Time, error) { + const location = "assessmentSignalNoticeRepository.Get" + if userID == uuid.Nil || version < 1 { + return time.Time{}, fmt.Errorf("%s - user and notice version are required", location) + } + stored, err := repository.queries.GetAssessmentSignalNoticeAcknowledgement(ctx, sqlc.GetAssessmentSignalNoticeAcknowledgementParams{ + UserID: pgUUID(userID), NoticeVersion: version, + }) + if errors.Is(err, pgx.ErrNoRows) { + return time.Time{}, fmt.Errorf("%s - read acknowledgement: %w", location, outbound.ErrAssessmentSignalNoticeNotAcknowledged) + } + if err != nil { + return time.Time{}, fmt.Errorf("%s - read acknowledgement: %w", location, mapAssessmentError(err)) + } + return acknowledgementTime(location, stored) +} + +func (repository assessmentSignalNoticeRepository) Acknowledge( + ctx context.Context, + userID uuid.UUID, + version int32, + at time.Time, +) (time.Time, error) { + const location = "assessmentSignalNoticeRepository.Acknowledge" + if userID == uuid.Nil || version < 1 || at.IsZero() { + return time.Time{}, fmt.Errorf("%s - user, notice version, and time are required", location) + } + if err := repository.queries.InsertAssessmentSignalNoticeAcknowledgement(ctx, sqlc.InsertAssessmentSignalNoticeAcknowledgementParams{ + UserID: pgUUID(userID), NoticeVersion: version, AcknowledgedAt: pgTime(at), + }); err != nil { + return time.Time{}, fmt.Errorf("%s - insert acknowledgement: %w", location, mapAssessmentError(err)) + } + return repository.Get(ctx, userID, version) +} + +func acknowledgementTime(location string, stored pgtype.Timestamptz) (time.Time, error) { + if !stored.Valid || stored.Time.IsZero() { + return time.Time{}, fmt.Errorf("%s - stored acknowledgement time is missing", location) + } + return stored.Time.UTC(), nil +} diff --git a/backend/internal/adapter/secondary/postgres/assessment_signal_review.go b/backend/internal/adapter/secondary/postgres/assessment_signal_review.go new file mode 100644 index 0000000..0fb1fde --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/assessment_signal_review.go @@ -0,0 +1,299 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +func (repository assessmentSignalRepository) SaveAnswerObservation( + ctx context.Context, + observation domain.AssessmentAnswerObservation, +) error { + const location = "assessmentSignalRepository.SaveAnswerObservation" + if err := observation.Validate(); err != nil { + return fmt.Errorf("%s - observation is invalid: %w", location, err) + } + if err := repository.queries.InsertAssessmentAnswerObservation(ctx, sqlc.InsertAssessmentAnswerObservationParams{ + AttemptID: pgUUID(observation.AttemptID.UUID()), ItemInstanceID: pgUUID(observation.ItemInstanceID), + UserID: pgUUID(observation.UserID), FamilyID: pgUUID(uuid.UUID(observation.FamilyID)), + // The seed is stored as the two's-complement image of the uint64, which + // keeps equality and inequality exact. + VariantSeed: int64(observation.Seed), //nolint:gosec // The two's-complement image of the seed keeps equality exact. + AnswerFormat: observation.AnswerFormat, + AnswerFingerprint: observation.Fingerprint[:], KeyVersion: observation.KeyVersion, + ElapsedMs: observation.ElapsedMS, MeasuredFromAnswer: observation.MeasuredFromAnswer, + ObservedAt: pgTime(observation.ObservedAt), + }); err != nil { + return fmt.Errorf("%s - insert observation: %w", location, mapAssessmentError(err)) + } + return nil +} + +func (repository assessmentSignalRepository) SaveOriginMark(ctx context.Context, mark domain.AssessmentOriginMark) error { + const location = "assessmentSignalRepository.SaveOriginMark" + if err := mark.Validate(); err != nil { + return fmt.Errorf("%s - mark is invalid: %w", location, err) + } + var network []byte + if !mark.NetworkDigest.IsZero() { + network = mark.NetworkDigest[:] + } + if err := repository.queries.InsertAssessmentOriginMark(ctx, sqlc.InsertAssessmentOriginMarkParams{ + ID: pgUUID(mark.ID), AttemptID: pgUUID(mark.AttemptID.UUID()), Source: string(mark.Source), + ObservedAt: pgTime(mark.ObservedAt), SessionDigest: mark.SessionDigest[:], NetworkDigest: network, + KeyVersion: mark.KeyVersion, + }); err != nil { + return fmt.Errorf("%s - insert origin mark: %w", location, mapAssessmentError(err)) + } + return nil +} + +func (repository assessmentSignalRepository) LastOriginMark( + ctx context.Context, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentOriginMark, bool, error) { + const location = "assessmentSignalRepository.LastOriginMark" + if attemptID.IsZero() { + return domain.AssessmentOriginMark{}, false, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) + } + row, err := repository.queries.GetLastAssessmentOriginMark(ctx, pgUUID(attemptID.UUID())) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentOriginMark{}, false, nil + } + if err != nil { + return domain.AssessmentOriginMark{}, false, fmt.Errorf("%s - read last mark: %w", location, mapAssessmentError(err)) + } + mark, err := restoreAssessmentOriginMark(row) + if err != nil { + return domain.AssessmentOriginMark{}, false, fmt.Errorf("%s - restore mark: %w", location, err) + } + return mark, true, nil +} + +func (repository assessmentSignalRepository) ReviewInputs( + ctx context.Context, + attemptID domain.AssessmentAttemptID, +) (outbound.AssessmentReviewInputs, error) { + const location = "assessmentSignalRepository.ReviewInputs" + if attemptID.IsZero() { + return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) + } + id := pgUUID(attemptID.UUID()) + times, err := repository.queries.ListAssessmentAnswerTimes(ctx, id) + if err != nil { + return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - list answer times: %w", location, mapAssessmentError(err)) + } + marks, err := repository.queries.ListAssessmentOriginMarks(ctx, id) + if err != nil { + return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - list origin marks: %w", location, mapAssessmentError(err)) + } + totals, err := repository.queries.GetAssessmentClientSignalTotals(ctx, id) + if err != nil { + return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - total client signals: %w", location, mapAssessmentError(err)) + } + inputs := outbound.AssessmentReviewInputs{ + ClientFocusLossMS: totals.FocusLossMs, ClientClipboardCount: totals.ClipboardEvents, + ClientFullscreenExit: totals.FullscreenExits, + } + for _, row := range times { + inputs.Answers = append(inputs.Answers, domain.AssessmentResponseSample{ + AnswerFormat: row.AnswerFormat, ElapsedMS: row.ElapsedMs, MeasuredFromAnswer: row.MeasuredFromAnswer, + }) + } + for _, row := range marks { + mark, err := restoreAssessmentOriginMark(row) + if err != nil { + return outbound.AssessmentReviewInputs{}, fmt.Errorf("%s - restore origin mark: %w", location, err) + } + inputs.Marks = append(inputs.Marks, mark) + } + return inputs, nil +} + +func restoreAssessmentOriginMark(row sqlc.AssessmentAttemptOriginMark) (domain.AssessmentOriginMark, error) { + if !row.ID.Valid || !row.AttemptID.Valid || !row.ObservedAt.Valid || len(row.SessionDigest) != len(domain.AssessmentDigest{}) || + len(row.NetworkDigest) != 0 && len(row.NetworkDigest) != len(domain.AssessmentDigest{}) { + return domain.AssessmentOriginMark{}, domain.ErrInvalidAssessmentReview + } + mark := domain.AssessmentOriginMark{ + ID: uuid.UUID(row.ID.Bytes), AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), + Source: domain.AssessmentOriginSource(row.Source), ObservedAt: row.ObservedAt.Time.UTC(), + KeyVersion: row.KeyVersion, + } + copy(mark.SessionDigest[:], row.SessionDigest) + copy(mark.NetworkDigest[:], row.NetworkDigest) + if err := mark.Validate(); err != nil { + return domain.AssessmentOriginMark{}, err + } + return mark, nil +} + +func (repository assessmentSignalRepository) DuplicatePairs( + ctx context.Context, + attemptID domain.AssessmentAttemptID, + query outbound.AssessmentDuplicateQuery, +) ([]outbound.AssessmentDuplicatePair, error) { + const location = "assessmentSignalRepository.DuplicatePairs" + if attemptID.IsZero() || query.Limit < 1 || query.IntegerCapBits < 1 || query.SequenceCapBits < 1 || query.MinBits < 0 || + query.EndedOnly && query.Now.IsZero() { + return nil, fmt.Errorf("%s - attempt, caps, and bounds are required: %w", location, domain.ErrInvalidAssessmentReview) + } + rows, err := repository.queries.ListAssessmentDuplicatePairs(ctx, sqlc.ListAssessmentDuplicatePairsParams{ + AttemptID: pgUUID(attemptID.UUID()), IntegerCapBits: float64(query.IntegerCapBits), + SequenceCapBits: float64(query.SequenceCapBits), MinBits: float64(query.MinBits), + EndedOnly: query.EndedOnly, Now: pgTime(query.Now), RowLimit: query.Limit, + }) + if err != nil { + return nil, fmt.Errorf("%s - list pairs: %w", location, mapAssessmentError(err)) + } + pairs := make([]outbound.AssessmentDuplicatePair, 0, len(rows)) + for _, row := range rows { + if !row.OtherAttemptID.Valid || !row.ProductPolicyVersionID.Valid || row.EvidenceBits < 0 { + return nil, fmt.Errorf("%s - stored pair is incomplete: %w", location, domain.ErrInvalidAssessmentReview) + } + pairs = append(pairs, outbound.AssessmentDuplicatePair{ + AttemptID: domain.AssessmentAttemptID(row.OtherAttemptID.Bytes), + PolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes), + EvidenceBits: row.EvidenceBits, IntegerItems: row.IntegerItems, SequenceItems: row.SequenceItems, + }) + } + return pairs, nil +} + +func (repository assessmentSignalRepository) ReviewSubject( + ctx context.Context, + attemptID domain.AssessmentAttemptID, +) (domain.PolicyVersionID, bool, error) { + const location = "assessmentSignalRepository.ReviewSubject" + if attemptID.IsZero() { + return domain.PolicyVersionID{}, false, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) + } + policyID, err := repository.queries.GetAssessmentReviewSubject(ctx, pgUUID(attemptID.UUID())) + if errors.Is(err, pgx.ErrNoRows) { + return domain.PolicyVersionID{}, false, nil + } + if err != nil { + return domain.PolicyVersionID{}, false, fmt.Errorf("%s - read attempt: %w", location, mapAssessmentError(err)) + } + if !policyID.Valid { + return domain.PolicyVersionID{}, false, fmt.Errorf("%s - stored policy is missing: %w", location, domain.ErrInvalidAssessmentReview) + } + return domain.PolicyVersionID(policyID.Bytes), true, nil +} + +func (repository assessmentSignalRepository) LockReview(ctx context.Context, attemptID domain.AssessmentAttemptID) error { + const location = "assessmentSignalRepository.LockReview" + if attemptID.IsZero() { + return fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) + } + if err := repository.queries.LockAssessmentReview(ctx, attemptID.String()); err != nil { + return fmt.Errorf("%s - take advisory lock: %w", location, mapAssessmentError(err)) + } + return nil +} + +func (repository assessmentSignalRepository) SaveReview(ctx context.Context, review domain.AssessmentAttemptReview) error { + const location = "assessmentSignalRepository.SaveReview" + if err := review.Validate(); err != nil { + return fmt.Errorf("%s - review is invalid: %w", location, err) + } + measures := review.Measures + reasons := make([]string, 0, len(review.Outcome.Reasons)) + for _, reason := range review.Outcome.Reasons { + reasons = append(reasons, string(reason)) + } + if err := repository.queries.UpsertAssessmentAttemptReview(ctx, sqlc.UpsertAssessmentAttemptReviewParams{ + AttemptID: pgUUID(review.AttemptID.UUID()), PolicyVersionID: pgUUID(uuid.UUID(review.PolicyVersionID)), + Band: string(review.Outcome.Band), Reasons: reasons, AnsweredItems: measures.AnsweredItems, + FastAnswers: measures.FastAnswers, DeviatingAnswers: measures.DeviatingAnswers, + ParallelAlternations: measures.ParallelAlternations, ExtraNetworks: measures.ExtraNetworks, + MatchedIntegerItems: measures.MatchedIntegerItems, MatchedSequenceItems: measures.MatchedSequenceItems, + DuplicateEvidenceBits: measures.DuplicateEvidenceBits, ClientFocusLossMs: measures.ClientFocusLossMS, + ClientClipboardEvents: measures.ClientClipboardEvents, ClientFullscreenExits: measures.ClientFullscreenExits, + }); err != nil { + return fmt.Errorf("%s - upsert review: %w", location, mapAssessmentError(err)) + } + return nil +} + +func (repository assessmentSignalRepository) GetReview( + ctx context.Context, + attemptID domain.AssessmentAttemptID, +) (domain.AssessmentAttemptReview, error) { + const location = "assessmentSignalRepository.GetReview" + if attemptID.IsZero() { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) + } + row, err := repository.queries.GetAssessmentAttemptReview(ctx, pgUUID(attemptID.UUID())) + if errors.Is(err, pgx.ErrNoRows) { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - review does not exist: %w", location, outbound.ErrAssessmentReviewNotFound) + } + if err != nil { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - read review: %w", location, mapAssessmentError(err)) + } + review, err := restoreAssessmentAttemptReview(row) + if err != nil { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - restore review: %w", location, err) + } + return review, nil +} + +func restoreAssessmentAttemptReview(row sqlc.GetAssessmentAttemptReviewRow) (domain.AssessmentAttemptReview, error) { + if !row.AttemptID.Valid || !row.PolicyVersionID.Valid || !row.EvaluatedAt.Valid || !row.UpdatedAt.Valid { + return domain.AssessmentAttemptReview{}, domain.ErrInvalidAssessmentReview + } + reasons := make([]domain.AssessmentReviewReason, 0, len(row.Reasons)) + for _, reason := range row.Reasons { + reasons = append(reasons, domain.AssessmentReviewReason(reason)) + } + review := domain.AssessmentAttemptReview{ + AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), + PolicyVersionID: domain.PolicyVersionID(row.PolicyVersionID.Bytes), + PolicyVersion: row.PolicyVersion, + Measures: domain.AssessmentReviewMeasures{ + AnsweredItems: row.AnsweredItems, FastAnswers: row.FastAnswers, DeviatingAnswers: row.DeviatingAnswers, + ParallelAlternations: row.ParallelAlternations, ExtraNetworks: row.ExtraNetworks, + MatchedIntegerItems: row.MatchedIntegerItems, MatchedSequenceItems: row.MatchedSequenceItems, + DuplicateEvidenceBits: row.DuplicateEvidenceBits, + ClientFocusLossMS: row.ClientFocusLossMs, ClientClipboardEvents: row.ClientClipboardEvents, + ClientFullscreenExits: row.ClientFullscreenExits, + }, + Outcome: domain.AssessmentReviewOutcome{ + Band: domain.AssessmentReviewBand(row.Band), Reasons: reasons, + }, + EvaluatedAt: row.EvaluatedAt.Time.UTC(), UpdatedAt: row.UpdatedAt.Time.UTC(), + } + if err := review.Validate(); err != nil { + return domain.AssessmentAttemptReview{}, err + } + return review, nil +} + +func (repository assessmentSignalRepository) RecordReviewRead( + ctx context.Context, + id uuid.UUID, + attemptID domain.AssessmentAttemptID, + actor domain.AssessmentReviewActor, + found bool, + at time.Time, +) error { + const location = "assessmentSignalRepository.RecordReviewRead" + if id == uuid.Nil || attemptID.IsZero() || actor == "" || at.IsZero() { + return fmt.Errorf("%s - record identifiers, attempt, actor, and time are required: %w", location, domain.ErrInvalidAssessmentReview) + } + if err := repository.queries.InsertAssessmentReviewRead(ctx, sqlc.InsertAssessmentReviewReadParams{ + ID: pgUUID(id), AttemptID: pgUUID(attemptID.UUID()), Actor: string(actor), Found: found, ReadAt: pgTime(at), + }); err != nil { + return fmt.Errorf("%s - insert read record: %w", location, mapAssessmentError(err)) + } + return nil +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_notice.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_notice.sql.go new file mode 100644 index 0000000..95f65fd --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_notice.sql.go @@ -0,0 +1,53 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: assessment_signal_notice.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getAssessmentSignalNoticeAcknowledgement = `-- name: GetAssessmentSignalNoticeAcknowledgement :one +SELECT acknowledged_at +FROM assessment_signal_notice_acknowledgements +WHERE + user_id = $1 + AND notice_version = $2 +` + +type GetAssessmentSignalNoticeAcknowledgementParams struct { + UserID pgtype.UUID + NoticeVersion int32 +} + +// The caller has already checked that the user is a candidate. A missing row +// means the notice version was not acknowledged. +func (q *Queries) GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error) { + row := q.db.QueryRow(ctx, getAssessmentSignalNoticeAcknowledgement, arg.UserID, arg.NoticeVersion) + var acknowledged_at pgtype.Timestamptz + err := row.Scan(&acknowledged_at) + return acknowledged_at, err +} + +const insertAssessmentSignalNoticeAcknowledgement = `-- name: InsertAssessmentSignalNoticeAcknowledgement :exec +INSERT INTO assessment_signal_notice_acknowledgements (user_id, notice_version, acknowledged_at) +VALUES ($1, $2, $3) +ON CONFLICT (user_id, notice_version) DO NOTHING +` + +type InsertAssessmentSignalNoticeAcknowledgementParams struct { + UserID pgtype.UUID + NoticeVersion int32 + AcknowledgedAt pgtype.Timestamptz +} + +// The first acknowledgement wins; a repeat keeps the stored time and inserts +// nothing. The caller reads the stored row afterwards in the same transaction. +func (q *Queries) InsertAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg InsertAssessmentSignalNoticeAcknowledgementParams) error { + _, err := q.db.Exec(ctx, insertAssessmentSignalNoticeAcknowledgement, arg.UserID, arg.NoticeVersion, arg.AcknowledgedAt) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_review.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_review.sql.go new file mode 100644 index 0000000..3aa4341 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_review.sql.go @@ -0,0 +1,577 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: assessment_signal_review.sql + +package sqlc + +import ( + "context" + + "github.com/jackc/pgx/v5/pgtype" +) + +const getAssessmentAttemptReview = `-- 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.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 = $1 +` + +type GetAssessmentAttemptReviewRow struct { + AttemptID pgtype.UUID + PolicyVersionID pgtype.UUID + PolicyVersion int32 + Band string + Reasons []string + AnsweredItems int32 + FastAnswers int32 + DeviatingAnswers int32 + ParallelAlternations int32 + ExtraNetworks int32 + MatchedIntegerItems int32 + MatchedSequenceItems int32 + DuplicateEvidenceBits int32 + ClientFocusLossMs int64 + ClientClipboardEvents int32 + ClientFullscreenExits int32 + EvaluatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +func (q *Queries) GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error) { + row := q.db.QueryRow(ctx, getAssessmentAttemptReview, attemptID) + var i GetAssessmentAttemptReviewRow + err := row.Scan( + &i.AttemptID, + &i.PolicyVersionID, + &i.PolicyVersion, + &i.Band, + &i.Reasons, + &i.AnsweredItems, + &i.FastAnswers, + &i.DeviatingAnswers, + &i.ParallelAlternations, + &i.ExtraNetworks, + &i.MatchedIntegerItems, + &i.MatchedSequenceItems, + &i.DuplicateEvidenceBits, + &i.ClientFocusLossMs, + &i.ClientClipboardEvents, + &i.ClientFullscreenExits, + &i.EvaluatedAt, + &i.UpdatedAt, + ) + return i, err +} + +const getAssessmentClientSignalTotals = `-- 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 +FROM assessment_signal_events +WHERE attempt_id = $1 +` + +type GetAssessmentClientSignalTotalsRow struct { + FocusLossMs int64 + ClipboardEvents int32 + FullscreenExits int32 +} + +func (q *Queries) GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) { + row := q.db.QueryRow(ctx, getAssessmentClientSignalTotals, attemptID) + var i GetAssessmentClientSignalTotalsRow + err := row.Scan(&i.FocusLossMs, &i.ClipboardEvents, &i.FullscreenExits) + return i, err +} + +const getAssessmentReviewSubject = `-- name: GetAssessmentReviewSubject :one +SELECT product_policy_version_id +FROM assessment_attempts +WHERE id = $1 AND kind IN ('root', 'corrective') +` + +// The attempt a review job works on: real attempts only. +func (q *Queries) GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error) { + row := q.db.QueryRow(ctx, getAssessmentReviewSubject, attemptID) + var product_policy_version_id pgtype.UUID + err := row.Scan(&product_policy_version_id) + return product_policy_version_id, err +} + +const getLastAssessmentOriginMark = `-- name: GetLastAssessmentOriginMark :one +SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version +FROM assessment_attempt_origin_marks +WHERE attempt_id = $1 +ORDER BY observed_at DESC, id DESC +LIMIT 1 +` + +// The caller holds the attempt row lock, so the last mark is stable. +func (q *Queries) GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error) { + row := q.db.QueryRow(ctx, getLastAssessmentOriginMark, attemptID) + var i AssessmentAttemptOriginMark + err := row.Scan( + &i.ID, + &i.AttemptID, + &i.Source, + &i.ObservedAt, + &i.SessionDigest, + &i.NetworkDigest, + &i.KeyVersion, + ) + return i, err +} + +const insertAssessmentAnswerObservation = `-- 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 ( + $1, + $2, + $3, + $4, + $5, + $6, + $7, + $8, + $9, + $10, + $11 +) +` + +type InsertAssessmentAnswerObservationParams struct { + AttemptID pgtype.UUID + ItemInstanceID pgtype.UUID + UserID pgtype.UUID + FamilyID pgtype.UUID + VariantSeed int64 + AnswerFormat string + AnswerFingerprint []byte + KeyVersion int16 + ElapsedMs int32 + MeasuredFromAnswer bool + ObservedAt pgtype.Timestamptz +} + +func (q *Queries) InsertAssessmentAnswerObservation(ctx context.Context, arg InsertAssessmentAnswerObservationParams) error { + _, err := q.db.Exec(ctx, insertAssessmentAnswerObservation, + arg.AttemptID, + arg.ItemInstanceID, + arg.UserID, + arg.FamilyID, + arg.VariantSeed, + arg.AnswerFormat, + arg.AnswerFingerprint, + arg.KeyVersion, + arg.ElapsedMs, + arg.MeasuredFromAnswer, + arg.ObservedAt, + ) + return err +} + +const insertAssessmentOriginMark = `-- name: InsertAssessmentOriginMark :exec +INSERT INTO assessment_attempt_origin_marks ( + id, + attempt_id, + source, + observed_at, + session_digest, + network_digest, + key_version +) VALUES ( + $1, + $2, + $3, + $4, + $5, + $6, + $7 +) +` + +type InsertAssessmentOriginMarkParams struct { + ID pgtype.UUID + AttemptID pgtype.UUID + Source string + ObservedAt pgtype.Timestamptz + SessionDigest []byte + NetworkDigest []byte + KeyVersion int16 +} + +func (q *Queries) InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error { + _, err := q.db.Exec(ctx, insertAssessmentOriginMark, + arg.ID, + arg.AttemptID, + arg.Source, + arg.ObservedAt, + arg.SessionDigest, + arg.NetworkDigest, + arg.KeyVersion, + ) + return err +} + +const insertAssessmentReviewRead = `-- name: InsertAssessmentReviewRead :exec +INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at) +VALUES ($1, $2, $3, $4, $5) +` + +type InsertAssessmentReviewReadParams struct { + ID pgtype.UUID + AttemptID pgtype.UUID + Actor string + Found bool + ReadAt pgtype.Timestamptz +} + +func (q *Queries) InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error { + _, err := q.db.Exec(ctx, insertAssessmentReviewRead, + arg.ID, + arg.AttemptID, + arg.Actor, + arg.Found, + arg.ReadAt, + ) + return err +} + +const listAssessmentAnswerTimes = `-- name: ListAssessmentAnswerTimes :many +SELECT answer_format, elapsed_ms, measured_from_answer +FROM assessment_answer_observations +WHERE attempt_id = $1 +ORDER BY observed_at, item_instance_id +LIMIT 220 +` + +type ListAssessmentAnswerTimesRow struct { + AnswerFormat string + ElapsedMs int32 + MeasuredFromAnswer bool +} + +// An attempt holds at most 220 items, so the list is bounded by the attempt. +func (q *Queries) ListAssessmentAnswerTimes(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAnswerTimesRow, error) { + rows, err := q.db.Query(ctx, listAssessmentAnswerTimes, attemptID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAssessmentAnswerTimesRow + for rows.Next() { + var i ListAssessmentAnswerTimesRow + if err := rows.Scan(&i.AnswerFormat, &i.ElapsedMs, &i.MeasuredFromAnswer); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAssessmentDuplicatePairs = `-- 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 = $5 +), + +pair_items AS ( + SELECT + other.attempt_id AS other_attempt_id, + mine.answer_format, + least( + CASE + WHEN mine.answer_format = 'integer' THEN $6::float8 + ELSE $7::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 $1::boolean + OR other_attempt.state IN ('completed', 'expired', 'insufficient_bank') + OR other_attempt.expires_at <= $2::timestamptz +GROUP BY pair_items.other_attempt_id, other_attempt.product_policy_version_id +HAVING floor(sum(pair_items.bits)) >= $3::float8 +ORDER BY evidence_bits DESC, pair_items.other_attempt_id +LIMIT $4 +` + +type ListAssessmentDuplicatePairsParams struct { + EndedOnly bool + Now pgtype.Timestamptz + MinBits float64 + RowLimit int32 + AttemptID pgtype.UUID + IntegerCapBits float64 + SequenceCapBits float64 +} + +type ListAssessmentDuplicatePairsRow struct { + OtherAttemptID pgtype.UUID + ProductPolicyVersionID pgtype.UUID + EvidenceBits int32 + IntegerItems int32 + SequenceItems int32 +} + +// 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. +func (q *Queries) ListAssessmentDuplicatePairs(ctx context.Context, arg ListAssessmentDuplicatePairsParams) ([]ListAssessmentDuplicatePairsRow, error) { + rows, err := q.db.Query(ctx, listAssessmentDuplicatePairs, + arg.EndedOnly, + arg.Now, + arg.MinBits, + arg.RowLimit, + arg.AttemptID, + arg.IntegerCapBits, + arg.SequenceCapBits, + ) + if err != nil { + return nil, err + } + defer rows.Close() + var items []ListAssessmentDuplicatePairsRow + for rows.Next() { + var i ListAssessmentDuplicatePairsRow + if err := rows.Scan( + &i.OtherAttemptID, + &i.ProductPolicyVersionID, + &i.EvidenceBits, + &i.IntegerItems, + &i.SequenceItems, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listAssessmentOriginMarks = `-- name: ListAssessmentOriginMarks :many +SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version +FROM assessment_attempt_origin_marks +WHERE attempt_id = $1 +ORDER BY observed_at, id +LIMIT 5000 +` + +// 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. +func (q *Queries) ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error) { + rows, err := q.db.Query(ctx, listAssessmentOriginMarks, attemptID) + if err != nil { + return nil, err + } + defer rows.Close() + var items []AssessmentAttemptOriginMark + for rows.Next() { + var i AssessmentAttemptOriginMark + if err := rows.Scan( + &i.ID, + &i.AttemptID, + &i.Source, + &i.ObservedAt, + &i.SessionDigest, + &i.NetworkDigest, + &i.KeyVersion, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const lockAssessmentReview = `-- name: LockAssessmentReview :exec +SELECT pg_advisory_xact_lock(hashtextextended( + 'lincodex.assessment.signal_review:' || $1::text, + 0 +)) +` + +// 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. +func (q *Queries) LockAssessmentReview(ctx context.Context, attemptID string) error { + _, err := q.db.Exec(ctx, lockAssessmentReview, attemptID) + return err +} + +const upsertAssessmentAttemptReview = `-- 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, + evaluated_at, + updated_at +) VALUES ( + $1, + $2, + $3, + $4::text[], + $5, + $6, + $7, + $8, + $9, + $10, + $11, + $12, + $13, + $14, + $15, + 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, + updated_at = greatest( + clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at + ) +` + +type UpsertAssessmentAttemptReviewParams struct { + AttemptID pgtype.UUID + PolicyVersionID pgtype.UUID + Band string + Reasons []string + AnsweredItems int32 + FastAnswers int32 + DeviatingAnswers int32 + ParallelAlternations int32 + ExtraNetworks int32 + MatchedIntegerItems int32 + MatchedSequenceItems int32 + DuplicateEvidenceBits int32 + ClientFocusLossMs int64 + ClientClipboardEvents int32 + ClientFullscreenExits int32 +} + +// 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. +func (q *Queries) UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertAssessmentAttemptReviewParams) error { + _, err := q.db.Exec(ctx, upsertAssessmentAttemptReview, + arg.AttemptID, + arg.PolicyVersionID, + arg.Band, + arg.Reasons, + arg.AnsweredItems, + arg.FastAnswers, + arg.DeviatingAnswers, + arg.ParallelAlternations, + arg.ExtraNetworks, + arg.MatchedIntegerItems, + arg.MatchedSequenceItems, + arg.DuplicateEvidenceBits, + arg.ClientFocusLossMs, + arg.ClientClipboardEvents, + arg.ClientFullscreenExits, + ) + return err +} diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index d572434..f330009 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -16,6 +16,33 @@ type AccountDeletionRequest struct { CompletedAt pgtype.Timestamptz } +type AssessmentAnswerFamilyTotal struct { + FamilyID pgtype.UUID + KeyVersion int16 + AnswerCount int32 +} + +type AssessmentAnswerFingerprintHolder struct { + FamilyID pgtype.UUID + KeyVersion int16 + AnswerFingerprint []byte + Holders int32 +} + +type AssessmentAnswerObservation struct { + AttemptID pgtype.UUID + ItemInstanceID pgtype.UUID + UserID pgtype.UUID + FamilyID pgtype.UUID + VariantSeed int64 + AnswerFormat string + AnswerFingerprint []byte + KeyVersion int16 + ElapsedMs int32 + MeasuredFromAnswer bool + ObservedAt pgtype.Timestamptz +} + type AssessmentAttempt struct { ID pgtype.UUID UserID pgtype.UUID @@ -74,6 +101,16 @@ type AssessmentAttemptItem struct { AnsweredAt pgtype.Timestamptz } +type AssessmentAttemptOriginMark struct { + ID pgtype.UUID + AttemptID pgtype.UUID + Source string + ObservedAt pgtype.Timestamptz + SessionDigest []byte + NetworkDigest []byte + KeyVersion int16 +} + type AssessmentAttemptResult struct { AttemptID pgtype.UUID UserID pgtype.UUID @@ -99,6 +136,26 @@ type AssessmentAttemptResult struct { DecidedAt pgtype.Timestamptz } +type AssessmentAttemptReview struct { + AttemptID pgtype.UUID + PolicyVersionID pgtype.UUID + Band string + Reasons []string + AnsweredItems int32 + FastAnswers int32 + DeviatingAnswers int32 + ParallelAlternations int32 + ExtraNetworks int32 + MatchedIntegerItems int32 + MatchedSequenceItems int32 + DuplicateEvidenceBits int32 + ClientFocusLossMs int64 + ClientClipboardEvents int32 + ClientFullscreenExits int32 + EvaluatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + type AssessmentCategoryCatalogBinding struct { OpeningID pgtype.UUID Specialization string @@ -143,6 +200,14 @@ type AssessmentFamily struct { RetiredBy pgtype.Text } +type AssessmentReviewRead struct { + ID pgtype.UUID + AttemptID pgtype.UUID + Actor string + Found bool + ReadAt pgtype.Timestamptz +} + type AssessmentSignalBatch struct { ID pgtype.UUID AttemptID pgtype.UUID @@ -169,6 +234,12 @@ type AssessmentSignalIdempotencyOutcome struct { ReceivedAt pgtype.Timestamptz } +type AssessmentSignalNoticeAcknowledgement struct { + UserID pgtype.UUID + NoticeVersion int32 + AcknowledgedAt pgtype.Timestamptz +} + type AssessmentTrainingBankBinding struct { ID pgtype.UUID Category string diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index dfc53da..54d20e9 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -227,15 +227,22 @@ type Querier interface { GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error) // Reads a result only for the owning candidate. GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error) + GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error) // Reads an active real attempt without taking the write lock used by create. // The availability GET never expires or otherwise mutates this row. GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error) + GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error) GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error) + // The attempt a review job works on: real attempts only. + GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error) // 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. GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error) + // The caller has already checked that the user is a candidate. A missing row + // means the notice version was not acknowledged. + GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error) // Read only the receipt associated with the reserved idempotency scope. GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error) // Reads one hiding of the candidate with the current name of the @@ -272,6 +279,8 @@ type Querier interface { GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) + // The caller holds the attempt row lock, so the last mark is stable. + GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error) GetLatestAssessmentFamily(ctx context.Context, familyKey string) (AssessmentFamily, error) // 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 @@ -328,6 +337,7 @@ type Querier interface { GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error) GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error) GetUserByID(ctx context.Context, id pgtype.UUID) (User, error) + InsertAssessmentAnswerObservation(ctx context.Context, arg InsertAssessmentAnswerObservationParams) error // Inserts the attempt header. The database guard rechecks the current policy, // opening or disjoint training binding, and immutable pins. InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error @@ -351,12 +361,17 @@ type Querier interface { // returns no row instead of an error, so a conflict does not abort the // surrounding transaction. InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error) + InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error + InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error // 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. InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error // Each inserted event is checked by the database guard against attempt state // and the aggregate capacity as a second line of defense. InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error + // The first acknowledgement wins; a repeat keeps the stored time and inserts + // nothing. The caller reads the stored row afterwards in the same transaction. + InsertAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg InsertAssessmentSignalNoticeAcknowledgementParams) error // Save exactly one immutable response receipt for each live idempotency scope. InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error // Records a successfully authorized view after visibility and quota checks. @@ -473,6 +488,8 @@ type Querier interface { // Read the latest serialized event so a temporarily regressing application // clock cannot make the next request fall before an event already counted. LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) + // An attempt holds at most 220 items, so the list is bounded by the attempt. + ListAssessmentAnswerTimes(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAnswerTimesRow, error) // Reads chain headers in creation order. The use case verifies root eligibility // and descending target grades in the domain before it creates a correction. ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error) @@ -488,10 +505,22 @@ type Querier interface { // Counting the first unanswered item after expiry is conservative when the // final response was lost, while frozen future items remain excluded. ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error) + // 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. + ListAssessmentDuplicatePairs(ctx context.Context, arg ListAssessmentDuplicatePairsParams) ([]ListAssessmentDuplicatePairsRow, error) // 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. ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error) + // 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. + ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error) // Reads the exact family membership pinned by a training binding. ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error) // Lists only the current candidate's own access history. It deliberately @@ -566,6 +595,10 @@ type Querier interface { // published or open the category, until the transaction ends. The key is // namespaced, so it cannot collide with another use of advisory locks. LockAssessmentCategory(ctx context.Context, category string) error + // 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. + LockAssessmentReview(ctx context.Context, attemptID string) error // 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 @@ -895,6 +928,11 @@ type Querier interface { // registrant never stands for the new one; the new registration records its // own C1 in the same transaction. A version conflict deletes nothing. UpdateUserRegistration(ctx context.Context, arg UpdateUserRegistrationParams) (UpdateUserRegistrationRow, error) + // 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. + UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertAssessmentAttemptReviewParams) error } var _ Querier = (*Queries)(nil) diff --git a/backend/internal/bootstrap/assessment.go b/backend/internal/bootstrap/assessment.go index 7d31566..a2ac606 100644 --- a/backend/internal/bootstrap/assessment.go +++ b/backend/internal/bootstrap/assessment.go @@ -46,5 +46,11 @@ func newAssessmentHandler( pool.Close() return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create service: %w", err) } + observer, err := newSignalObserver(keyring) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create signal observer: %w", err) + } + service.WithSignalObserver(observer) return v1.NewAssessmentHandler(service), pool.Close, nil } diff --git a/backend/internal/bootstrap/assessment_signal.go b/backend/internal/bootstrap/assessment_signal.go index 0205da5..8e80f08 100644 --- a/backend/internal/bootstrap/assessment_signal.go +++ b/backend/internal/bootstrap/assessment_signal.go @@ -35,5 +35,11 @@ func newAssessmentSignalHandler( pool.Close() return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - create service: %w", err) } - return v1.NewAssessmentSignalHandler(service), pool.Close, nil + observer, err := newSignalObserver(keyring) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - create signal observer: %w", err) + } + service.WithSignalObserver(observer) + return v1.NewAssessmentSignalHandler(service).WithNotice(service), pool.Close, nil } diff --git a/backend/internal/bootstrap/assessment_signal_observer.go b/backend/internal/bootstrap/assessment_signal_observer.go new file mode 100644 index 0000000..47941b0 --- /dev/null +++ b/backend/internal/bootstrap/assessment_signal_observer.go @@ -0,0 +1,19 @@ +package bootstrap + +import ( + "fmt" + + "lincodex/backend/internal/usecase/assessment" + "lincodex/backend/internal/usecase/identity" +) + +// newSignalObserver derives the answer, session, and network digests of the +// server signals from the identity keyring, so no separate secret is needed and +// the digests change with IDENTITY_KEY_SECRET. +func newSignalObserver(keyring *identity.Keyring) (*assessment.SignalObserver, error) { + observer, err := assessment.NewSignalObserver(keyring) + if err != nil { + return nil, fmt.Errorf("bootstrap.newSignalObserver - create observer: %w", err) + } + return observer, nil +} diff --git a/backend/internal/bootstrap/jobs.go b/backend/internal/bootstrap/jobs.go index 83a8a9e..be52974 100644 --- a/backend/internal/bootstrap/jobs.go +++ b/backend/internal/bootstrap/jobs.go @@ -10,6 +10,7 @@ import ( "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/usecase/assessment" "lincodex/backend/internal/worker/jobrunner" "lincodex/backend/internal/worker/retry" ) @@ -29,11 +30,12 @@ const ( var _ jobrunner.Metrics = (*prometheus.Metrics)(nil) // jobHandlers lists the scheduled job handlers, one per kind. A product -// module adds its handler here, for example the invitation response -// deadline, and the worker then claims jobs of that kind with the next -// deployment. Jobs of a kind without a handler wait in the database. -func jobHandlers() []inbound.JobHandler { - return []inbound.JobHandler{} +// module adds its handler here, and the worker then claims jobs of that kind +// with the next deployment. Jobs of a kind without a handler wait in the +// database. The only kind now is the computation of the assessment review +// band, which can never block or change a result. +func jobHandlers(logger *slog.Logger) []inbound.JobHandler { + return []inbound.JobHandler{assessment.NewSignalReviewJob(logger)} } func newJobWorker( @@ -42,7 +44,7 @@ func newJobWorker( logger *slog.Logger, metrics *prometheus.Metrics, ) (*jobrunner.Worker, func(), error) { - return buildJobWorker(ctx, settings, logger, metrics, jobHandlers()) + return buildJobWorker(ctx, settings, logger, metrics, jobHandlers(logger.With(slog.String("component", "assessment_review")))) } // buildJobWorker builds the scheduled job worker and the PostgreSQL pool it diff --git a/backend/internal/bootstrap/jobs_test.go b/backend/internal/bootstrap/jobs_test.go index 8334ba6..4137a67 100644 --- a/backend/internal/bootstrap/jobs_test.go +++ b/backend/internal/bootstrap/jobs_test.go @@ -55,8 +55,9 @@ func TestBuildJobWorkerSkipsWithoutWork(t *testing.T) { } } -func TestBootstrapRegistersNoJobKindYet(t *testing.T) { - if handlers := jobHandlers(); len(handlers) != 0 { +func TestBootstrapRegistersTheReviewJobKind(t *testing.T) { + handlers := jobHandlers(slog.New(slog.DiscardHandler)) + if len(handlers) != 1 || handlers[0].JobKind() != "assessment.signal_review" { t.Fatalf("jobHandlers() = %v; update the documentation when the registered job kinds change", handlers) } } diff --git a/backend/internal/domain/assessment_signal_policy.go b/backend/internal/domain/assessment_signal_policy.go new file mode 100644 index 0000000..7601caa --- /dev/null +++ b/backend/internal/domain/assessment_signal_policy.go @@ -0,0 +1,137 @@ +package domain + +// AssessmentSignalPolicy holds the versioned thresholds that turn the server +// observations of an attempt into a review band. The band is a hint for a +// manual check: it never changes a result, a category, or a quota. The section +// is optional; a policy version without it makes no band, and an absent +// section never acquires defaults. +// +// Counts are numbers of items or events, durations carry their unit in the +// field name, and the duplicate thresholds are evidence bits: a matched answer +// adds the number of bits that the policy assumes for its format, and a pair of +// candidates that coincides by chance reaches N bits with a probability of +// about 2^-N when every matched answer is independent. +type AssessmentSignalPolicy struct { + // FastFloorIntegerMS and FastFloorSequenceMS are the shortest server time + // from the previous answer or session start to the answer that is still + // plausible for the answer format. A shorter time is a fast answer. + FastFloorIntegerMS int32 + FastFloorSequenceMS int32 + // FastAnswersAttention and FastAnswersReview are the numbers of fast + // answers that raise the band. + FastAnswersAttention int32 + FastAnswersReview int32 + + // DeviationRatio is the factor by which an answer time may differ from the + // median answer time of the same attempt, in both directions, before it is + // an anomalous deviation. 50000 means five times. It applies only to an + // attempt with at least DeviationMinAnswers answers. + DeviationRatio BasisPoints + DeviationMinAnswers int32 + DeviatingAnswersAttention int32 + DeviatingAnswersReview int32 + ParallelAlternationsAttention int32 + ParallelAlternationsReview int32 + // ExtraNetworks counts the distinct client networks of the attempt beyond + // the first. Going from one network to another and back adds one, however + // often it happens. + ExtraNetworksAttention int32 + ExtraNetworksReview int32 + + // A matched answer carries -log2 of the share of attempts that hold the + // same fingerprint for the family version, so a popular value, such as the + // correct answer of a variant, carries little. DuplicateIntegerCapBits and + // DuplicateSequenceCapBits cap what one answer of the format can carry; an + // integer answer has a small answer space and is capped lower. The bits of + // the matched answers of one pair of attempts add up, and the highest pair + // decides: an attempt is compared with every other one, not with the whole + // population at once. + DuplicateIntegerCapBits int32 + DuplicateSequenceCapBits int32 + DuplicateAttentionBits int32 + DuplicateReviewBits int32 + + // The client thresholds can raise a normal band to attention only, because + // a browser reports them and anyone can forge or suppress them. + ClientFocusLossAttentionMS int32 + ClientClipboardEventsAttention int32 + ClientFullscreenExitsAttention int32 +} + +// Sanity bounds of the signal section. They reject a value in the wrong unit; +// the demo values themselves are recorded in DemoAssessmentSignalPolicy. +const ( + minSignalFloorMS = 1000 + maxSignalFloorMS = 10 * 60 * 1000 + maxSignalCount = 1000 + minSignalDeviationRatio = BasisPoints(20000) + maxSignalDeviationRatio = BasisPoints(1000000) + minSignalDeviationAnswers = 3 + maxSignalDeviationAnswers = maxAssessmentAttemptItems + maxSignalEvidenceBits = 64 + maxSignalThresholdBits = 4096 + minSignalClientFocusLossMS = 1000 + maxSignalClientFocusLossMS = 24 * 60 * 60 * 1000 +) + +// DemoAssessmentSignalPolicy returns the initial thresholds. They are agreed +// starting values for verifying the flow, not measured results: no study of +// real candidates supports them, and a calibrated policy must replace them. +func DemoAssessmentSignalPolicy() AssessmentSignalPolicy { + return AssessmentSignalPolicy{ + FastFloorIntegerMS: 5000, + FastFloorSequenceMS: 8000, + FastAnswersAttention: 3, + FastAnswersReview: 6, + DeviationRatio: 50000, + DeviationMinAnswers: 5, + DeviatingAnswersAttention: 3, + DeviatingAnswersReview: 6, + ParallelAlternationsAttention: 2, + ParallelAlternationsReview: 6, + ExtraNetworksAttention: 2, ExtraNetworksReview: 5, + DuplicateIntegerCapBits: 8, DuplicateSequenceCapBits: 12, + DuplicateAttentionBits: 48, + DuplicateReviewBits: 64, + ClientFocusLossAttentionMS: 120000, + ClientClipboardEventsAttention: 3, + ClientFullscreenExitsAttention: 3, + } +} + +// Validate rejects a zero, out-of-range, or inconsistent section. +func (policy AssessmentSignalPolicy) Validate() error { + const location = "AssessmentSignalPolicy.Validate" + if err := firstError( + checkRange(location, "assessment.signals.fast_floor_integer_ms", policy.FastFloorIntegerMS, minSignalFloorMS, maxSignalFloorMS), + checkRange(location, "assessment.signals.fast_floor_sequence_ms", policy.FastFloorSequenceMS, minSignalFloorMS, maxSignalFloorMS), + checkRange(location, "assessment.signals.deviation_ratio_bp", policy.DeviationRatio, minSignalDeviationRatio, maxSignalDeviationRatio), + checkRange(location, "assessment.signals.deviation_min_answers", policy.DeviationMinAnswers, minSignalDeviationAnswers, maxSignalDeviationAnswers), + checkRange(location, "assessment.signals.duplicate_integer_cap_bits", policy.DuplicateIntegerCapBits, 1, maxSignalEvidenceBits), + checkRange(location, "assessment.signals.duplicate_sequence_cap_bits", policy.DuplicateSequenceCapBits, 1, maxSignalEvidenceBits), + checkRange(location, "assessment.signals.client_focus_loss_attention_ms", policy.ClientFocusLossAttentionMS, minSignalClientFocusLossMS, maxSignalClientFocusLossMS), + checkRange(location, "assessment.signals.client_clipboard_events_attention", policy.ClientClipboardEventsAttention, 1, maxSignalCount), + checkRange(location, "assessment.signals.client_fullscreen_exits_attention", policy.ClientFullscreenExitsAttention, 1, maxSignalCount), + ); err != nil { + return err + } + for _, pair := range []struct { + field string + attention, review int32 + maximum int32 + }{ + {"fast_answers", policy.FastAnswersAttention, policy.FastAnswersReview, maxSignalCount}, + {"deviating_answers", policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview, maxSignalCount}, + {"parallel_alternations", policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview, maxSignalCount}, + {"extra_networks", policy.ExtraNetworksAttention, policy.ExtraNetworksReview, maxSignalCount}, + {"duplicate_bits", policy.DuplicateAttentionBits, policy.DuplicateReviewBits, maxSignalThresholdBits}, + } { + if err := checkRange(location, "assessment.signals."+pair.field+"_attention", pair.attention, 1, pair.maximum); err != nil { + return err + } + if err := checkRange(location, "assessment.signals."+pair.field+"_review", pair.review, pair.attention, pair.maximum); err != nil { + return err + } + } + return nil +} diff --git a/backend/internal/domain/assessment_signal_policy_test.go b/backend/internal/domain/assessment_signal_policy_test.go new file mode 100644 index 0000000..6968c35 --- /dev/null +++ b/backend/internal/domain/assessment_signal_policy_test.go @@ -0,0 +1,80 @@ +package domain + +import ( + "errors" + "testing" +) + +func TestDemoSignalPolicyIsValidAndRoundTripsThroughTheDocument(t *testing.T) { + policy := DemoProductPolicyV3() + if err := policy.Validate(); err != nil { + t.Fatalf("DemoProductPolicyV3().Validate() error = %v", err) + } + encoded, _, err := encodeProductPolicy(policy) + if err != nil { + t.Fatalf("encodeProductPolicy() error = %v", err) + } + decoded, err := decodeProductPolicy(encoded) + if err != nil { + t.Fatalf("decodeProductPolicy() error = %v", err) + } + if decoded.Assessment.Signals == nil || *decoded.Assessment.Signals != DemoAssessmentSignalPolicy() { + t.Fatalf("decoded signals = %+v, want the demo values", decoded.Assessment.Signals) + } + if DemoProductPolicyV2().Assessment.Signals != nil { + t.Fatal("DemoProductPolicyV2 gained a signal section; a stored version must not change") + } +} + +func TestSignalSectionAloneIsASchemaTwoExtensionAndNeverAcquiresDefaults(t *testing.T) { + signals := DemoAssessmentSignalPolicy() + policy := DemoProductPolicyV1() + policy.Assessment.Signals = &signals + encoded, _, err := encodeProductPolicy(policy) + if err != nil { + t.Fatalf("encodeProductPolicy() error = %v", err) + } + decoded, err := decodeProductPolicy(encoded) + if err != nil || decoded.Assessment.Signals == nil || decoded.Assessment.Attempt != nil || decoded.Support != nil { + t.Fatalf("decode signals-only schema 2 = %+v, error %v", decoded.Assessment, err) + } + + legacy := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) { + policySection(t, document, "assessment")["signals"] = nil + }) + if _, err := decodeProductPolicy(legacy); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("decodeProductPolicy(schema 1 with a signals key) error = %v, want ErrInvalidPolicy", err) + } + + missingField := editPolicySchemaDocument(t, encoded, func(document map[string]any) { + delete(policySection(t, policySection(t, document, "assessment"), "signals"), "fast_floor_integer_ms") + }) + if _, err := decodeProductPolicy(missingField); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("decodeProductPolicy(missing signal field) error = %v, want ErrInvalidPolicy", err) + } +} + +func TestSignalPolicyRejectsOutOfRangeAndInconsistentValues(t *testing.T) { + tests := []struct { + name string + change func(*AssessmentSignalPolicy) + }{ + {"zero section", func(policy *AssessmentSignalPolicy) { *policy = AssessmentSignalPolicy{} }}, + {"floor in seconds instead of milliseconds", func(policy *AssessmentSignalPolicy) { policy.FastFloorIntegerMS = 5 }}, + {"review below attention", func(policy *AssessmentSignalPolicy) { policy.FastAnswersReview = policy.FastAnswersAttention - 1 }}, + {"duplicate review below attention", func(policy *AssessmentSignalPolicy) { policy.DuplicateReviewBits = policy.DuplicateAttentionBits - 1 }}, + {"deviation ratio below two", func(policy *AssessmentSignalPolicy) { policy.DeviationRatio = 15000 }}, + {"deviation needs several answers", func(policy *AssessmentSignalPolicy) { policy.DeviationMinAnswers = 2 }}, + {"evidence bits beyond a hash", func(policy *AssessmentSignalPolicy) { policy.DuplicateSequenceCapBits = 65 }}, + {"client threshold zero", func(policy *AssessmentSignalPolicy) { policy.ClientClipboardEventsAttention = 0 }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + policy := DemoAssessmentSignalPolicy() + test.change(&policy) + if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) { + t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err) + } + }) + } +} diff --git a/backend/internal/domain/assessment_signal_review.go b/backend/internal/domain/assessment_signal_review.go new file mode 100644 index 0000000..c326237 --- /dev/null +++ b/backend/internal/domain/assessment_signal_review.go @@ -0,0 +1,387 @@ +package domain + +import ( + "crypto/sha256" + "errors" + "fmt" + "slices" + "time" + + "github.com/google/uuid" +) + +// ErrInvalidAssessmentReview reports a malformed server observation or review. +// Its text never includes an answer, an address, or a session identifier. +var ErrInvalidAssessmentReview = errors.New("invalid assessment review") + +// AssessmentReviewBand is the manual-check hint of one attempt. It is stored +// for an operator only. It has no effect on the result, the category, or a +// quota, and no candidate or employer read carries it. +type AssessmentReviewBand string + +const ( + AssessmentReviewBandNormal AssessmentReviewBand = "normal" + AssessmentReviewBandAttention AssessmentReviewBand = "attention" + AssessmentReviewBandReview AssessmentReviewBand = "review" +) + +func (band AssessmentReviewBand) rank() int { + switch band { + case AssessmentReviewBandNormal: + return 0 + case AssessmentReviewBandAttention: + return 1 + case AssessmentReviewBandReview: + return 2 + default: + return -1 + } +} + +// IsKnown reports whether the band is one of the three stored values. +func (band AssessmentReviewBand) IsKnown() bool { return band.rank() >= 0 } + +// AssessmentReviewReason names a signal group that raised the band. +type AssessmentReviewReason string + +const ( + AssessmentReviewReasonFastAnswers AssessmentReviewReason = "fast_answers" + AssessmentReviewReasonDeviatingAnswers AssessmentReviewReason = "deviating_answers" + AssessmentReviewReasonParallelSessions AssessmentReviewReason = "parallel_sessions" + AssessmentReviewReasonExtraNetworks AssessmentReviewReason = "extra_networks" + AssessmentReviewReasonDuplicateAnswers AssessmentReviewReason = "duplicate_answers" + AssessmentReviewReasonClientSignals AssessmentReviewReason = "client_signals" +) + +// IsKnown reports whether the reason is a stored value. +func (reason AssessmentReviewReason) IsKnown() bool { + switch reason { + case AssessmentReviewReasonFastAnswers, AssessmentReviewReasonDeviatingAnswers, + AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks, + AssessmentReviewReasonDuplicateAnswers, AssessmentReviewReasonClientSignals: + return true + default: + return false + } +} + +// AssessmentDigest is a keyed 32-byte digest. It stands for an answer, a +// session, or a network address without carrying any of them. +type AssessmentDigest [sha256.Size]byte + +// IsZero reports an unset digest. +func (digest AssessmentDigest) IsZero() bool { return digest == AssessmentDigest{} } + +// AssessmentAnswerObservation is the server-side record of one accepted +// answer: how long it took, and a keyed fingerprint of the normalized answer +// that allows comparing answers of different candidates without storing them. +type AssessmentAnswerObservation struct { + AttemptID AssessmentAttemptID + UserID uuid.UUID + ItemInstanceID uuid.UUID + FamilyID AssessmentFamilyID + FamilyVersion int32 + Seed VariantSeed + AnswerFormat string + Fingerprint AssessmentDigest + // KeyVersion names the key generation of Fingerprint, so a rotation is + // explicit and fingerprints of different generations are never compared. + KeyVersion int16 + ElapsedMS int32 + // MeasuredFromAnswer is true when ElapsedMS starts at the previous answer, + // which is when this item was shown. The first item of a work session starts + // at the session start, which is only an upper bound of the time the item + // was on screen, so such a time is not used for the speed signals. + MeasuredFromAnswer bool + ObservedAt time.Time +} + +// Validate checks that the observation can be stored. +func (observation AssessmentAnswerObservation) Validate() error { + const location = "AssessmentAnswerObservation.Validate" + switch { + case observation.AttemptID.IsZero(), observation.UserID == uuid.Nil, observation.ItemInstanceID == uuid.Nil, + uuid.UUID(observation.FamilyID) == uuid.Nil, observation.FamilyVersion < 1: + return fmt.Errorf("%s - identifiers are required: %w", location, ErrInvalidAssessmentReview) + case observation.AnswerFormat != AnswerFormatInteger && observation.AnswerFormat != AnswerFormatIntegerSequence: + return fmt.Errorf("%s - answer format is unsupported: %w", location, ErrInvalidAssessmentReview) + case observation.Fingerprint.IsZero(), observation.KeyVersion < 1: + return fmt.Errorf("%s - fingerprint and its key version are required: %w", location, ErrInvalidAssessmentReview) + case observation.ElapsedMS < 0, observation.ObservedAt.IsZero(): + return fmt.Errorf("%s - elapsed time and observation time are required: %w", location, ErrInvalidAssessmentReview) + } + return nil +} + +// AssessmentOriginSource says which request produced an origin mark. +type AssessmentOriginSource string + +const ( + AssessmentOriginAnswer AssessmentOriginSource = "answer" + AssessmentOriginSignals AssessmentOriginSource = "signals" +) + +// AssessmentOriginMark records, for one accepted request, keyed digests of the +// authenticated session and of the client network. The digests are bound to +// the attempt, so they cannot be correlated between attempts, and they are +// useless without the server secret. NetworkDigest is absent when the client +// address could not be resolved. +type AssessmentOriginMark struct { + ID uuid.UUID + AttemptID AssessmentAttemptID + Source AssessmentOriginSource + ObservedAt time.Time + SessionDigest AssessmentDigest + NetworkDigest AssessmentDigest + KeyVersion int16 +} + +// Validate checks that the mark can be stored. +func (mark AssessmentOriginMark) Validate() error { + const location = "AssessmentOriginMark.Validate" + if mark.ID == uuid.Nil || mark.AttemptID.IsZero() || mark.ObservedAt.IsZero() || mark.SessionDigest.IsZero() || mark.KeyVersion < 1 { + return fmt.Errorf("%s - identifiers, time, session digest, and key version are required: %w", location, ErrInvalidAssessmentReview) + } + if mark.Source != AssessmentOriginAnswer && mark.Source != AssessmentOriginSignals { + return fmt.Errorf("%s - source is unknown: %w", location, ErrInvalidAssessmentReview) + } + return nil +} + +// AssessmentResponseSample is the server time of one answer. +type AssessmentResponseSample struct { + AnswerFormat string + ElapsedMS int32 + MeasuredFromAnswer bool +} + +// AssessmentResponseTimes counts the answers and the answers that the policy +// calls fast or anomalously fast. Only server time is used: the client may +// report durations of its own, but they never replace it. +type AssessmentResponseTimes struct { + Answered int32 + Fast int32 + Deviating int32 +} + +// ClassifyResponseTimes applies the fast floors and the median deviation of +// the policy. Only answers measured from the previous answer count. The +// deviation is computed within one answer format, so a slow format does not +// make a quick one look anomalous, and only on the fast side: a slow answer is +// not suspicious by itself. One answer contributes to at most one counter: an +// answer under its floor is fast and is not counted again as a deviation. +func (policy AssessmentSignalPolicy) ClassifyResponseTimes(samples []AssessmentResponseSample) AssessmentResponseTimes { + result := AssessmentResponseTimes{Answered: int32(min(len(samples), maxAssessmentAttemptItems))} + byFormat := map[string][]int64{} + for _, sample := range samples { + if !sample.MeasuredFromAnswer { + continue + } + floor := policy.fastFloor(sample.AnswerFormat) + if sample.ElapsedMS < floor { + result.Fast++ + // Kept for the median, but marked so it is not a deviation too. + byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], -int64(sample.ElapsedMS)-1) + continue + } + byFormat[sample.AnswerFormat] = append(byFormat[sample.AnswerFormat], int64(sample.ElapsedMS)) + } + ratio := int64(policy.DeviationRatio) + for _, marked := range byFormat { + if len(marked) < int(policy.DeviationMinAnswers) { + continue + } + elapsed := make([]int64, len(marked)) + for index, value := range marked { + elapsed[index] = value + if value < 0 { + elapsed[index] = -value - 1 + } + } + slices.Sort(elapsed) + median := elapsed[len(elapsed)/2] + if len(elapsed)%2 == 0 { + median = (elapsed[len(elapsed)/2-1] + elapsed[len(elapsed)/2]) / 2 + } + median = max(median, 1) + for _, value := range marked { + // value is more than ratio times below the median, in basis points. + if value >= 0 && max(value, 1)*ratio < median*int64(basisPointsPerUnit) { + result.Deviating++ + } + } + } + return result +} + +func (policy AssessmentSignalPolicy) fastFloor(format string) int32 { + if format == AnswerFormatIntegerSequence { + return policy.FastFloorSequenceMS + } + return policy.FastFloorIntegerMS +} + +// AssessmentOriginAnomalies counts the origin changes of an attempt. +type AssessmentOriginAnomalies struct { + // ParallelAlternations counts requests that came back to an earlier + // session after another session had been used, as when two logged-in + // sessions work on one attempt in turn. A single move from one session to + // another is not counted. + ParallelAlternations int32 + // ExtraNetworks counts the distinct network digests beyond the first. A + // move to another network and back is one extra network. + ExtraNetworks int32 +} + +// CountOriginAnomalies orders the marks by time and then by ID and counts +// alternations between sessions and distinct client networks. +func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalies { + ordered := slices.Clone(marks) + slices.SortStableFunc(ordered, func(left, right AssessmentOriginMark) int { + if byTime := left.ObservedAt.Compare(right.ObservedAt); byTime != 0 { + return byTime + } + return slices.Compare(left.ID[:], right.ID[:]) + }) + var anomalies AssessmentOriginAnomalies + seenSessions := map[AssessmentDigest]struct{}{} + networks := map[AssessmentDigest]struct{}{} + var previousSession AssessmentDigest + for _, mark := range ordered { + _, seen := seenSessions[mark.SessionDigest] + if seen && mark.SessionDigest != previousSession { + anomalies.ParallelAlternations++ + } + seenSessions[mark.SessionDigest] = struct{}{} + previousSession = mark.SessionDigest + if !mark.NetworkDigest.IsZero() { + networks[mark.NetworkDigest] = struct{}{} + } + } + anomalies.ExtraNetworks = int32(max(len(networks)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list. + return anomalies +} + +// AssessmentReviewMeasures is everything the band is computed from. Every +// field is a count or a duration; none of them holds an answer or an address. +// The duplicate fields describe the pair of attempts with the most evidence. +type AssessmentReviewMeasures struct { + AnsweredItems int32 + FastAnswers int32 + DeviatingAnswers int32 + ParallelAlternations int32 + ExtraNetworks int32 + MatchedIntegerItems int32 + MatchedSequenceItems int32 + DuplicateEvidenceBits int32 + ClientFocusLossMS int64 + ClientClipboardEvents int32 + ClientFullscreenExits int32 +} + +// AssessmentReviewOutcome is the computed band with the groups behind it. +type AssessmentReviewOutcome struct { + Band AssessmentReviewBand + Reasons []AssessmentReviewReason +} + +// Evaluate computes the band. Server signals decide it. Parallel sessions and +// extra networks are weak and correlated (a phone and a laptop produce both), so +// they are one group: alone it reaches attention at most, and review only +// together with a strong signal (fast answers, deviating answers, or duplicate +// answers) at attention or above. Client signals can only raise a normal band +// to attention, because a browser reports them. +func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures) AssessmentReviewOutcome { + type signal struct { + reason AssessmentReviewReason + band AssessmentReviewBand + weak bool + } + signals := []signal{ + {AssessmentReviewReasonFastAnswers, signalLevel(measures.FastAnswers, policy.FastAnswersAttention, policy.FastAnswersReview), false}, + {AssessmentReviewReasonDeviatingAnswers, signalLevel(measures.DeviatingAnswers, policy.DeviatingAnswersAttention, policy.DeviatingAnswersReview), false}, + {AssessmentReviewReasonParallelSessions, signalLevel(measures.ParallelAlternations, policy.ParallelAlternationsAttention, policy.ParallelAlternationsReview), true}, + {AssessmentReviewReasonExtraNetworks, signalLevel(measures.ExtraNetworks, policy.ExtraNetworksAttention, policy.ExtraNetworksReview), true}, + {AssessmentReviewReasonDuplicateAnswers, signalLevel(measures.DuplicateEvidenceBits, policy.DuplicateAttentionBits, policy.DuplicateReviewBits), false}, + } + strongRaised := false + for _, entry := range signals { + if !entry.weak && entry.band.rank() > 0 { + strongRaised = true + } + } + outcome := AssessmentReviewOutcome{Band: AssessmentReviewBandNormal} + for _, entry := range signals { + band := entry.band + if entry.weak && band == AssessmentReviewBandReview && !strongRaised { + band = AssessmentReviewBandAttention + } + if band.rank() == 0 { + continue + } + outcome.Reasons = append(outcome.Reasons, entry.reason) + if band.rank() > outcome.Band.rank() { + outcome.Band = band + } + } + if measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) || + measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention || + measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention { + outcome.Reasons = append(outcome.Reasons, AssessmentReviewReasonClientSignals) + if outcome.Band == AssessmentReviewBandNormal { + outcome.Band = AssessmentReviewBandAttention + } + } + return outcome +} + +func signalLevel(value, attention, review int32) AssessmentReviewBand { + switch { + case value >= review: + return AssessmentReviewBandReview + case value >= attention: + return AssessmentReviewBandAttention + default: + return AssessmentReviewBandNormal + } +} + +// AssessmentAttemptReview is the stored review of an attempt. PolicyVersionID +// pins the policy version that computed it, which is the version the attempt +// itself is pinned to. +type AssessmentAttemptReview struct { + AttemptID AssessmentAttemptID + PolicyVersionID PolicyVersionID + PolicyVersion int32 + Measures AssessmentReviewMeasures + Outcome AssessmentReviewOutcome + EvaluatedAt time.Time + UpdatedAt time.Time +} + +// Validate checks that the review can be stored. +func (review AssessmentAttemptReview) Validate() error { + const location = "AssessmentAttemptReview.Validate" + if review.AttemptID.IsZero() || review.PolicyVersionID.IsZero() || !review.Outcome.Band.IsKnown() || + review.EvaluatedAt.IsZero() || review.UpdatedAt.IsZero() { + return fmt.Errorf("%s - attempt, policy, band, and times are required: %w", location, ErrInvalidAssessmentReview) + } + for _, reason := range review.Outcome.Reasons { + if !reason.IsKnown() { + return fmt.Errorf("%s - reason is unknown: %w", location, ErrInvalidAssessmentReview) + } + } + return nil +} + +// AssessmentReviewActor is the audit handle of an operator who reads a +// review, written as operator:. It is not authentication. +type AssessmentReviewActor string + +// ParseAssessmentReviewActor accepts operator:. +func ParseAssessmentReviewActor(value string) (AssessmentReviewActor, error) { + if len(value) > 128 || !assessmentOperatorPattern.MatchString(value) { + return "", fmt.Errorf("domain.ParseAssessmentReviewActor - actor must be operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-': %w", ErrInvalidAssessmentReview) + } + return AssessmentReviewActor(value), nil +} diff --git a/backend/internal/domain/assessment_signal_review_test.go b/backend/internal/domain/assessment_signal_review_test.go new file mode 100644 index 0000000..6095c1a --- /dev/null +++ b/backend/internal/domain/assessment_signal_review_test.go @@ -0,0 +1,167 @@ +package domain + +import ( + "slices" + "testing" + "time" + + "github.com/google/uuid" +) + +func answerSample(format string, elapsedMS int32, fromAnswer bool) AssessmentResponseSample { + return AssessmentResponseSample{AnswerFormat: format, ElapsedMS: elapsedMS, MeasuredFromAnswer: fromAnswer} +} + +func TestClassifyResponseTimesUsesFloorsPerFormat(t *testing.T) { + policy := DemoAssessmentSignalPolicy() + samples := []AssessmentResponseSample{ + answerSample(AnswerFormatInteger, 4999, true), + answerSample(AnswerFormatInteger, 5000, true), + answerSample(AnswerFormatIntegerSequence, 7999, true), + answerSample(AnswerFormatIntegerSequence, 8000, true), + // The first item of a work session is measured from the session start, + // when the item was not necessarily on screen, so it is not counted. + answerSample(AnswerFormatInteger, 10, false), + } + got := policy.ClassifyResponseTimes(samples) + if got.Answered != 5 || got.Fast != 2 || got.Deviating != 0 { + t.Fatalf("ClassifyResponseTimes(floors) = %+v, want 5 answers, 2 fast, and no deviation below the minimum count", got) + } +} + +func TestClassifyResponseTimesDeviatesOnTheFastSideWithinOneFormat(t *testing.T) { + policy := DemoAssessmentSignalPolicy() + steady := func(count int, elapsed int32) []AssessmentResponseSample { + samples := make([]AssessmentResponseSample, 0, count+1) + for range count { + samples = append(samples, answerSample(AnswerFormatInteger, elapsed, true)) + } + return samples + } + if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 11999, true))); got.Deviating != 1 || got.Fast != 0 { + t.Fatalf("ClassifyResponseTimes(fast outlier) = %+v, want one deviation below a fifth of the median", got) + } + if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 12001, true))); got.Deviating != 0 { + t.Fatalf("ClassifyResponseTimes(inside the ratio) = %+v, want no deviation", got) + } + if got := policy.ClassifyResponseTimes(append(steady(6, 60000), answerSample(AnswerFormatInteger, 900000, true))); got.Deviating != 0 { + t.Fatalf("ClassifyResponseTimes(slow outlier) = %+v, want no deviation: a slow answer is not suspicious", got) + } + // Another format has its own median and its own minimum count: five slow + // orders do not make a quick integer answer deviate, and the integer + // answers alone are too few. + mixed := append(steady(3, 60000), answerSample(AnswerFormatIntegerSequence, 70000, true), answerSample(AnswerFormatIntegerSequence, 70000, true)) + mixed = append(mixed, answerSample(AnswerFormatInteger, 9000, true)) + if got := policy.ClassifyResponseTimes(mixed); got.Deviating != 0 { + t.Fatalf("ClassifyResponseTimes(mixed formats) = %+v, want no deviation: each format has fewer than %d answers", got, policy.DeviationMinAnswers) + } + // Answers measured from a session start are left out of the median too. + withStart := append(steady(5, 60000), answerSample(AnswerFormatInteger, 60000, false), answerSample(AnswerFormatInteger, 1, false)) + if got := policy.ClassifyResponseTimes(withStart); got.Deviating != 0 || got.Fast != 0 { + t.Fatalf("ClassifyResponseTimes(session start items) = %+v, want them excluded", got) + } +} + +func TestClassifyResponseTimesCountsAnAnswerOnce(t *testing.T) { + policy := DemoAssessmentSignalPolicy() + samples := make([]AssessmentResponseSample, 0, 7) + for range 6 { + samples = append(samples, answerSample(AnswerFormatInteger, 60000, true)) + } + // Under the floor and far below the median: fast, and not a deviation too. + samples = append(samples, answerSample(AnswerFormatInteger, 1000, true)) + got := policy.ClassifyResponseTimes(samples) + if got.Fast != 1 || got.Deviating != 0 { + t.Fatalf("ClassifyResponseTimes() = %+v, want the answer counted as fast only", got) + } +} + +func originMark(second int, session, network byte) AssessmentOriginMark { + mark := AssessmentOriginMark{ + ID: uuid.New(), AttemptID: AssessmentAttemptID(uuid.New()), Source: AssessmentOriginAnswer, + ObservedAt: time.Date(2026, time.October, 1, 12, 0, second, 0, time.UTC), + SessionDigest: AssessmentDigest{session}, KeyVersion: 1, + } + if network != 0 { + mark.NetworkDigest = AssessmentDigest{network} + } + return mark +} + +func TestCountOriginAnomalies(t *testing.T) { + tests := []struct { + name string + marks []AssessmentOriginMark + want AssessmentOriginAnomalies + }{ + {"one session and one network", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 1), originMark(3, 1, 1)}, AssessmentOriginAnomalies{}}, + {"moving once to another session is not parallel", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 2, 1), originMark(3, 2, 1)}, AssessmentOriginAnomalies{}}, + {"turns between two sessions", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 2, 1), originMark(3, 1, 1), originMark(4, 2, 1)}, AssessmentOriginAnomalies{ParallelAlternations: 2}}, + {"unknown addresses are skipped and a return is not a new network", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 0), originMark(3, 1, 2), originMark(4, 1, 2), originMark(5, 1, 1)}, AssessmentOriginAnomalies{ExtraNetworks: 1}}, + {"three networks", []AssessmentOriginMark{originMark(1, 1, 1), originMark(2, 1, 2), originMark(3, 1, 3), originMark(4, 1, 1)}, AssessmentOriginAnomalies{ExtraNetworks: 2}}, + {"order follows time and not the slice", []AssessmentOriginMark{originMark(4, 2, 1), originMark(1, 1, 1), originMark(3, 1, 1), originMark(2, 2, 1)}, AssessmentOriginAnomalies{ParallelAlternations: 2}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := CountOriginAnomalies(test.marks); got != test.want { + t.Fatalf("CountOriginAnomalies() = %+v, want %+v", got, test.want) + } + }) + } +} + +func TestEvaluateBandFollowsThePolicyAndClientSignalsOnlyRaiseToAttention(t *testing.T) { + policy := DemoAssessmentSignalPolicy() + tests := []struct { + name string + measures AssessmentReviewMeasures + wantBand AssessmentReviewBand + wantReasons []AssessmentReviewReason + }{ + {"nothing observed", AssessmentReviewMeasures{AnsweredItems: 8}, AssessmentReviewBandNormal, nil}, + {"fast answers reach attention", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers}}, + {"fast answers reach review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersReview}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers}}, + {"a weak signal alone stops at attention", AssessmentReviewMeasures{ExtraNetworks: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraNetworks}}, + {"parallel sessions alone stop at attention", AssessmentReviewMeasures{ParallelAlternations: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions}}, + {"two weak signals do not lift each other", AssessmentReviewMeasures{ParallelAlternations: 50, ExtraNetworks: 50}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks}}, + {"a weak signal reaches review beside a server signal", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ExtraNetworks: 50}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonExtraNetworks}}, + {"less duplicate evidence than the attention level is no flag", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateAttentionBits - 1}, AssessmentReviewBandNormal, nil}, + {"duplicate evidence at the attention level", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateAttentionBits}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonDuplicateAnswers}}, + {"duplicate evidence at the review level", AssessmentReviewMeasures{DuplicateEvidenceBits: policy.DuplicateReviewBits}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonDuplicateAnswers}}, + {"client signals alone raise a normal band to attention", AssessmentReviewMeasures{ClientFocusLossMS: int64(policy.ClientFocusLossAttentionMS)}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}}, + {"client signals never raise attention to review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ClientClipboardEvents: 1000, ClientFullscreenExits: 1000, ClientFocusLossMS: 1 << 40}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonClientSignals}}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := policy.Evaluate(test.measures) + if got.Band != test.wantBand || !slices.Equal(got.Reasons, test.wantReasons) { + t.Fatalf("Evaluate() = %+v, want band %s reasons %v", got, test.wantBand, test.wantReasons) + } + }) + } +} + +func TestEvaluateUsesTheThresholdsOfTheGivenPolicy(t *testing.T) { + measures := AssessmentReviewMeasures{FastAnswers: 4} + strict := DemoAssessmentSignalPolicy() + strict.FastAnswersAttention, strict.FastAnswersReview = 2, 4 + relaxed := DemoAssessmentSignalPolicy() + relaxed.FastAnswersAttention, relaxed.FastAnswersReview = 100, 200 + if got := strict.Evaluate(measures).Band; got != AssessmentReviewBandReview { + t.Fatalf("strict policy band = %s, want review", got) + } + if got := relaxed.Evaluate(measures).Band; got != AssessmentReviewBandNormal { + t.Fatalf("relaxed policy band = %s, want normal", got) + } +} + +func TestParseAssessmentReviewActorRequiresAnOperatorHandle(t *testing.T) { + if _, err := ParseAssessmentReviewActor("operator:night.shift-1"); err != nil { + t.Fatalf("ParseAssessmentReviewActor(valid) error = %v", err) + } + for _, invalid := range []string{"", "alice", "operator:", "operator:Alice", "operator:a@b.example", "system:cron"} { + if _, err := ParseAssessmentReviewActor(invalid); err == nil { + t.Errorf("ParseAssessmentReviewActor(%q) accepted an invalid actor", invalid) + } + } +} diff --git a/backend/internal/domain/policy.go b/backend/internal/domain/policy.go index dc1f957..89c69a5 100644 --- a/backend/internal/domain/policy.go +++ b/backend/internal/domain/policy.go @@ -130,6 +130,10 @@ func (policy ProductPolicy) clone() ProductPolicy { trainingCopy := *training copied.Assessment.Training = &trainingCopy } + if signals := policy.Assessment.Signals; signals != nil { + signalsCopy := *signals + copied.Assessment.Signals = &signalsCopy + } if support := policy.Support; support != nil { supportCopy := *support copied.Support = &supportCopy @@ -324,6 +328,10 @@ type AssessmentPolicy struct { // Training is an explicit non-qualification policy section. It is nil in // immutable legacy policies and never inherits real assessment settings. Training *AssessmentTrainingPolicy + // Signals holds the thresholds of the manual-review band. It is nil in + // policy versions that predate it; such a version computes no band and + // never inherits another version's thresholds. + Signals *AssessmentSignalPolicy } // AssessmentAttemptPolicy holds the versioned execution limits for a newly @@ -452,6 +460,11 @@ func (policy AssessmentPolicy) Validate() error { return err } } + if policy.Signals != nil { + if err := policy.Signals.Validate(); err != nil { + return err + } + } return nil } diff --git a/backend/internal/domain/policy_demo.go b/backend/internal/domain/policy_demo.go index a784303..e40aeb3 100644 --- a/backend/internal/domain/policy_demo.go +++ b/backend/internal/domain/policy_demo.go @@ -86,3 +86,13 @@ func DemoProductPolicyV2() ProductPolicy { policy.Support = &support return policy } + +// DemoProductPolicyV3 returns the demo policy with the manual-review band +// thresholds on top of DemoProductPolicyV2. It is published explicitly; a +// stored version is never rewritten, and startup seeding publishes V1 only. +func DemoProductPolicyV3() ProductPolicy { + policy := DemoProductPolicyV2() + signals := DemoAssessmentSignalPolicy() + policy.Assessment.Signals = &signals + return policy +} diff --git a/backend/internal/domain/policy_document.go b/backend/internal/domain/policy_document.go index a767e5e..eba35f5 100644 --- a/backend/internal/domain/policy_document.go +++ b/backend/internal/domain/policy_document.go @@ -88,6 +88,7 @@ type assessmentPolicyDocument struct { StopRule *assessmentStopDocument `json:"stop_rule"` Attempt *assessmentAttemptDocument `json:"attempt,omitempty"` Training *assessmentTrainingDocument `json:"training,omitempty"` + Signals *assessmentSignalsDocument `json:"signals,omitempty"` } type assessmentPolicyV1Document struct { @@ -111,6 +112,28 @@ type assessmentAttemptDocument struct { BasicPassMarkBP *BasisPoints `json:"basic_pass_mark_bp"` } +type assessmentSignalsDocument struct { + FastFloorIntegerMS *int32 `json:"fast_floor_integer_ms"` + FastFloorSequenceMS *int32 `json:"fast_floor_sequence_ms"` + FastAnswersAttention *int32 `json:"fast_answers_attention"` + FastAnswersReview *int32 `json:"fast_answers_review"` + DeviationRatioBP *BasisPoints `json:"deviation_ratio_bp"` + DeviationMinAnswers *int32 `json:"deviation_min_answers"` + DeviatingAnswersAttention *int32 `json:"deviating_answers_attention"` + DeviatingAnswersReview *int32 `json:"deviating_answers_review"` + ParallelAlternationsAttention *int32 `json:"parallel_alternations_attention"` + ParallelAlternationsReview *int32 `json:"parallel_alternations_review"` + ExtraNetworksAttention *int32 `json:"extra_networks_attention"` + ExtraNetworksReview *int32 `json:"extra_networks_review"` + DuplicateIntegerCapBits *int32 `json:"duplicate_integer_cap_bits"` + DuplicateSequenceCapBits *int32 `json:"duplicate_sequence_cap_bits"` + DuplicateBitsAttention *int32 `json:"duplicate_bits_attention"` + DuplicateBitsReview *int32 `json:"duplicate_bits_review"` + ClientFocusLossAttentionMS *int32 `json:"client_focus_loss_attention_ms"` + ClientClipboardEventsAttention *int32 `json:"client_clipboard_events_attention"` + ClientFullscreenExitsAttention *int32 `json:"client_fullscreen_exits_attention"` +} + type assessmentTrainingDocument struct { DemoExpressDurationSeconds *int32 `json:"demo_express_duration_seconds"` DemoExpressItemCount *int32 `json:"demo_express_item_count"` @@ -155,7 +178,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro } } schemaVersion := int32(productPolicySchemaVersionV1) - if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support != nil { + if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || policy.Support != nil { schemaVersion = productPolicySchemaVersionV2 } document := productPolicyDocument{ @@ -196,6 +219,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro }, Attempt: encodeAssessmentAttemptPolicy(assessment.Attempt), Training: encodeAssessmentTrainingPolicy(assessment.Training), + Signals: encodeAssessmentSignalPolicy(assessment.Signals), }, Identity: &identityPolicyDocument{ VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime), @@ -241,6 +265,33 @@ func encodeAssessmentTrainingPolicy(policy *AssessmentTrainingPolicy) *assessmen } } +func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSignalsDocument { + if policy == nil { + return nil + } + return &assessmentSignalsDocument{ + FastFloorIntegerMS: pointer(policy.FastFloorIntegerMS), + FastFloorSequenceMS: pointer(policy.FastFloorSequenceMS), + FastAnswersAttention: pointer(policy.FastAnswersAttention), + FastAnswersReview: pointer(policy.FastAnswersReview), + DeviationRatioBP: pointer(policy.DeviationRatio), + DeviationMinAnswers: pointer(policy.DeviationMinAnswers), + DeviatingAnswersAttention: pointer(policy.DeviatingAnswersAttention), + DeviatingAnswersReview: pointer(policy.DeviatingAnswersReview), + ParallelAlternationsAttention: pointer(policy.ParallelAlternationsAttention), + ParallelAlternationsReview: pointer(policy.ParallelAlternationsReview), + ExtraNetworksAttention: pointer(policy.ExtraNetworksAttention), + ExtraNetworksReview: pointer(policy.ExtraNetworksReview), + DuplicateIntegerCapBits: pointer(policy.DuplicateIntegerCapBits), + DuplicateSequenceCapBits: pointer(policy.DuplicateSequenceCapBits), + DuplicateBitsAttention: pointer(policy.DuplicateAttentionBits), + DuplicateBitsReview: pointer(policy.DuplicateReviewBits), + ClientFocusLossAttentionMS: pointer(policy.ClientFocusLossAttentionMS), + ClientClipboardEventsAttention: pointer(policy.ClientClipboardEventsAttention), + ClientFullscreenExitsAttention: pointer(policy.ClientFullscreenExitsAttention), + } +} + func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument { return &organizationTierQuotaDocument{ Active: pointer(quota.Active), @@ -295,7 +346,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) { return ProductPolicy{}, err } assessment := parsed.Assessment - hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil) + hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil) if !hasAssessmentExtension && parsed.Support == nil { return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension") } @@ -371,6 +422,31 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32 IdleTimeoutSeconds: require(&reader, "assessment.training.idle_timeout_seconds", training.IdleTimeoutSeconds), } } + var signalPolicy *AssessmentSignalPolicy + if assessment.Signals != nil { + signals := assessment.Signals + signalPolicy = &AssessmentSignalPolicy{ + FastFloorIntegerMS: require(&reader, "assessment.signals.fast_floor_integer_ms", signals.FastFloorIntegerMS), + FastFloorSequenceMS: require(&reader, "assessment.signals.fast_floor_sequence_ms", signals.FastFloorSequenceMS), + FastAnswersAttention: require(&reader, "assessment.signals.fast_answers_attention", signals.FastAnswersAttention), + FastAnswersReview: require(&reader, "assessment.signals.fast_answers_review", signals.FastAnswersReview), + DeviationRatio: require(&reader, "assessment.signals.deviation_ratio_bp", signals.DeviationRatioBP), + DeviationMinAnswers: require(&reader, "assessment.signals.deviation_min_answers", signals.DeviationMinAnswers), + DeviatingAnswersAttention: require(&reader, "assessment.signals.deviating_answers_attention", signals.DeviatingAnswersAttention), + DeviatingAnswersReview: require(&reader, "assessment.signals.deviating_answers_review", signals.DeviatingAnswersReview), + ParallelAlternationsAttention: require(&reader, "assessment.signals.parallel_alternations_attention", signals.ParallelAlternationsAttention), + ParallelAlternationsReview: require(&reader, "assessment.signals.parallel_alternations_review", signals.ParallelAlternationsReview), + ExtraNetworksAttention: require(&reader, "assessment.signals.extra_networks_attention", signals.ExtraNetworksAttention), + ExtraNetworksReview: require(&reader, "assessment.signals.extra_networks_review", signals.ExtraNetworksReview), + DuplicateIntegerCapBits: require(&reader, "assessment.signals.duplicate_integer_cap_bits", signals.DuplicateIntegerCapBits), + DuplicateSequenceCapBits: require(&reader, "assessment.signals.duplicate_sequence_cap_bits", signals.DuplicateSequenceCapBits), + DuplicateAttentionBits: require(&reader, "assessment.signals.duplicate_bits_attention", signals.DuplicateBitsAttention), + DuplicateReviewBits: require(&reader, "assessment.signals.duplicate_bits_review", signals.DuplicateBitsReview), + ClientFocusLossAttentionMS: require(&reader, "assessment.signals.client_focus_loss_attention_ms", signals.ClientFocusLossAttentionMS), + ClientClipboardEventsAttention: require(&reader, "assessment.signals.client_clipboard_events_attention", signals.ClientClipboardEventsAttention), + ClientFullscreenExitsAttention: require(&reader, "assessment.signals.client_fullscreen_exits_attention", signals.ClientFullscreenExitsAttention), + } + } policy := ProductPolicy{ Invitations: InvitationPolicy{ ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays), @@ -406,6 +482,7 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32 }, Attempt: attemptPolicy, Training: trainingPolicy, + Signals: signalPolicy, }, Identity: IdentityPolicy{ VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours), diff --git a/backend/internal/port/outbound/assessment_signal.go b/backend/internal/port/outbound/assessment_signal.go index b10918b..10646a4 100644 --- a/backend/internal/port/outbound/assessment_signal.go +++ b/backend/internal/port/outbound/assessment_signal.go @@ -5,10 +5,51 @@ import ( "errors" "time" + "github.com/google/uuid" + "lincodex/backend/internal/domain" ) -var ErrAssessmentSignalOutcomeNotFound = errors.New("assessment signal outcome not found") +var ( + ErrAssessmentSignalOutcomeNotFound = errors.New("assessment signal outcome not found") + ErrAssessmentReviewNotFound = errors.New("assessment attempt review not found") +) + +// AssessmentReviewInputs are the stored facts a review is computed from, apart +// from the comparison with other attempts. They hold no answer, address, or +// session identifier. +type AssessmentReviewInputs struct { + Answers []domain.AssessmentResponseSample + Marks []domain.AssessmentOriginMark + ClientFocusLossMS int64 + ClientClipboardCount int32 + ClientFullscreenExit int32 +} + +// AssessmentDuplicateQuery selects the pairs of attempts that share answers. +// The caps come from the policy of the attempt being evaluated. +type AssessmentDuplicateQuery struct { + IntegerCapBits int32 + SequenceCapBits int32 + // MinBits drops pairs with less evidence. + MinBits int32 + // EndedOnly keeps only attempts that are over at Now: terminal, or past + // their deadline. + EndedOnly bool + Now time.Time + Limit int32 +} + +// AssessmentDuplicatePair is one other attempt that shares answers with the +// evaluated one. It is used inside the usecase only: nothing that identifies +// the other attempt or its candidate leaves it. +type AssessmentDuplicatePair struct { + AttemptID domain.AssessmentAttemptID + PolicyVersionID domain.PolicyVersionID + EvidenceBits int32 + IntegerItems int32 + SequenceItems int32 +} type AssessmentSignalRepositories interface { AssessmentSignals() AssessmentSignalRepository @@ -23,4 +64,28 @@ type AssessmentSignalRepository interface { SaveOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, attemptID domain.AssessmentAttemptID, receipt domain.AssessmentSignalReceipt) error DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error GetOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentSignalReceipt, error) + + // SaveAnswerObservation and SaveOriginMark store server-side facts of an + // accepted request in the current unit of work. The caller holds the row + // lock of the attempt; no other lock is taken. + SaveAnswerObservation(ctx context.Context, observation domain.AssessmentAnswerObservation) error + SaveOriginMark(ctx context.Context, mark domain.AssessmentOriginMark) error + LastOriginMark(ctx context.Context, attemptID domain.AssessmentAttemptID) (domain.AssessmentOriginMark, bool, error) + + ReviewInputs(ctx context.Context, attemptID domain.AssessmentAttemptID) (AssessmentReviewInputs, error) + // DuplicatePairs lists the other attempts that share answers with the given + // one, strongest first and bounded by the query. + DuplicatePairs(ctx context.Context, attemptID domain.AssessmentAttemptID, query AssessmentDuplicateQuery) ([]AssessmentDuplicatePair, error) + // ReviewSubject returns the product policy version a real attempt is pinned + // to; found is false for an unknown or training attempt. + ReviewSubject(ctx context.Context, attemptID domain.AssessmentAttemptID) (domain.PolicyVersionID, bool, error) + // LockReview takes the transaction-scoped lock of one attempt's review. A + // job locks every review it will write, in ascending attempt order, before + // it reads any fact, so concurrent evaluations of one attempt run one after + // another and the later one reads what the earlier one committed. + LockReview(ctx context.Context, attemptID domain.AssessmentAttemptID) error + // SaveReview stores the review; the times come from the database clock. + SaveReview(ctx context.Context, review domain.AssessmentAttemptReview) error + GetReview(ctx context.Context, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptReview, error) + RecordReviewRead(ctx context.Context, id uuid.UUID, attemptID domain.AssessmentAttemptID, actor domain.AssessmentReviewActor, found bool, at time.Time) error } diff --git a/backend/internal/port/outbound/assessment_signal_notice.go b/backend/internal/port/outbound/assessment_signal_notice.go new file mode 100644 index 0000000..2f456aa --- /dev/null +++ b/backend/internal/port/outbound/assessment_signal_notice.go @@ -0,0 +1,29 @@ +package outbound + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" +) + +// ErrAssessmentSignalNoticeNotAcknowledged reports that the account has no +// acknowledgement for the requested notice version. +var ErrAssessmentSignalNoticeNotAcknowledged = errors.New("assessment signal notice is not acknowledged") + +type AssessmentSignalNoticeRepositories interface { + AssessmentSignalNotices() AssessmentSignalNoticeRepository +} + +// AssessmentSignalNoticeRepository stores the record that a candidate was shown +// the notice about collected assessment signals. The record is not a consent +// and no storage rule reads it. +type AssessmentSignalNoticeRepository interface { + // Get returns the time of the first acknowledgement of the version, or + // ErrAssessmentSignalNoticeNotAcknowledged. + Get(ctx context.Context, userID uuid.UUID, version int32) (time.Time, error) + // Acknowledge stores the acknowledgement when none exists for the version + // and keeps the earlier time otherwise. It returns the stored time. + Acknowledge(ctx context.Context, userID uuid.UUID, version int32, at time.Time) (time.Time, error) +} diff --git a/backend/internal/port/outbound/transaction.go b/backend/internal/port/outbound/transaction.go index 7d36883..5fe6f85 100644 --- a/backend/internal/port/outbound/transaction.go +++ b/backend/internal/port/outbound/transaction.go @@ -70,6 +70,7 @@ type UnitOfWork interface { AssessmentBankRepositories AssessmentAttemptRepositories AssessmentSignalRepositories + AssessmentSignalNoticeRepositories SupportCaseRepositories Policies() PolicyRepository Deliveries() DeliveryRepository diff --git a/backend/internal/usecase/assessment/answer.go b/backend/internal/usecase/assessment/answer.go index 00a6b93..27537e6 100644 --- a/backend/internal/usecase/assessment/answer.go +++ b/backend/internal/usecase/assessment/answer.go @@ -24,6 +24,9 @@ type SubmitAttemptAnswerCommand struct { ExpectedVersion int64 IdempotencyKey string Answer json.RawMessage + // Origin is the sender of the request. It feeds the server signals only and + // is not part of the idempotency fingerprint. + Origin RequestOrigin } type canonicalAttemptAnswerBody struct { @@ -132,7 +135,7 @@ func (service *AttemptService) submitNewAnswer( return fmt.Errorf("%s - read database time after consent and attempt locks: %w", location, err) } databaseTime = databaseTime.UTC().Truncate(time.Microsecond) - return service.persistSubmittedAnswer(ctx, repository, scope, command, current, databaseTime, result) + return service.persistSubmittedAnswer(ctx, unit, repository, scope, command, current, databaseTime, result) } func lockAttemptForAnswer( @@ -168,6 +171,7 @@ func lockAttemptForAnswer( func (service *AttemptService) persistSubmittedAnswer( ctx context.Context, + unit outbound.UnitOfWork, repository outbound.AssessmentAttemptRepository, scope outbound.AssessmentAttemptIdempotencyScope, command SubmitAttemptAnswerCommand, @@ -199,6 +203,11 @@ func (service *AttemptService) persistSubmittedAnswer( if err := repository.SaveAnswer(ctx, current, updated, command.ItemID); err != nil { return fmt.Errorf("%s - persist answer and attempt transition: %w", location, err) } + if err := service.signalObserver.observeAnswer( + ctx, unit, current, updated, command.ItemID, command.Origin, + ); err != nil { + return fmt.Errorf("%s - observe accepted answer: %w", location, err) + } } outcome := outbound.AssessmentAttemptCommandOutcome{StatusCode: 200, Response: updated.PublicSnapshot()} if err := repository.SaveAnswerOutcome(ctx, scope, outcome); err != nil { diff --git a/backend/internal/usecase/assessment/attempt.go b/backend/internal/usecase/assessment/attempt.go index a2dfe2c..df543e9 100644 --- a/backend/internal/usecase/assessment/attempt.go +++ b/backend/internal/usecase/assessment/attempt.go @@ -64,6 +64,7 @@ type AttemptService struct { keyring Keyring clock func() time.Time categoryDecisions AssessmentCategoryDecisionService + signalObserver *SignalObserver } // NewAttemptService fails at startup when a required dependency is missing. diff --git a/backend/internal/usecase/assessment/finalize.go b/backend/internal/usecase/assessment/finalize.go index 4d8fea0..08d61f3 100644 --- a/backend/internal/usecase/assessment/finalize.go +++ b/backend/internal/usecase/assessment/finalize.go @@ -244,7 +244,16 @@ func (service *AttemptService) finalizeActiveAttempt( } return fmt.Errorf("%s - calculate pinned decision: %w", location, finalizeErr) } - return service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result) + if err := service.persistFinalizedAttempt(ctx, repository, scope, command, current, updated, changed, decision, policy, result); err != nil { + return err + } + if !changed { + return nil + } + if err := service.signalObserver.scheduleEndedReview(ctx, unit, updated, databaseTime); err != nil { + return fmt.Errorf("%s - schedule review: %w", location, err) + } + return nil } func (service *AttemptService) persistFinalizedAttempt( diff --git a/backend/internal/usecase/assessment/signal.go b/backend/internal/usecase/assessment/signal.go index c31523f..5b32b10 100644 --- a/backend/internal/usecase/assessment/signal.go +++ b/backend/internal/usecase/assessment/signal.go @@ -51,6 +51,7 @@ type SignalService struct { transactor outbound.Transactor keyring Keyring clock func() time.Time + observer *SignalObserver } func NewSignalService(transactor outbound.Transactor, keyring Keyring, clock func() time.Time) (*SignalService, error) { @@ -65,6 +66,9 @@ type RecordSignalsCommand struct { AttemptID domain.AssessmentAttemptID IdempotencyKey string Events []domain.AssessmentSignalEvent + // Origin is the sender of the batch. It feeds the server signals only and + // is not part of the idempotency fingerprint. + Origin RequestOrigin } type canonicalSignalRequest struct { @@ -191,6 +195,11 @@ func (service *SignalService) recordNewSignals( if err != nil { return fmt.Errorf("%s - persist bounded event batch: %w", location, err) } + if status == domain.AssessmentSignalReceiptAccepted { + if err := service.observer.recordOrigin(ctx, repository, attempt.ID(), domain.AssessmentOriginSignals, databaseTime, command.Origin); err != nil { + return fmt.Errorf("%s - record request origin: %w", location, err) + } + } newReceipt, err := domain.NewAssessmentSignalReceipt(status, acceptedCount, databaseTime) if err != nil { return fmt.Errorf("%s - build receipt: %w", location, err) diff --git a/backend/internal/usecase/assessment/signal_notice.go b/backend/internal/usecase/assessment/signal_notice.go new file mode 100644 index 0000000..4a71af6 --- /dev/null +++ b/backend/internal/usecase/assessment/signal_notice.go @@ -0,0 +1,88 @@ +package assessment + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/port/outbound" +) + +// CurrentSignalNoticeVersion is the version of the notice text that lists the +// collected assessment signals. Change it together with the client text so that +// every candidate acknowledges the new wording. +const CurrentSignalNoticeVersion int32 = 1 + +// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice +// version other than the one the server requires. +var ErrSignalNoticeVersionMismatch = errors.New("assessment signal notice version is not current") + +// SignalNoticeState is the acknowledgement state of the current notice version. +type SignalNoticeState struct { + Version int32 + Acknowledged bool + AcknowledgedAt time.Time +} + +// GetSignalNotice reads whether the candidate acknowledged the current notice. +// The record is not a consent and does not influence signal storage. +func (service *SignalService) GetSignalNotice(ctx context.Context, actorID uuid.UUID) (SignalNoticeState, error) { + const location = "SignalService.GetSignalNotice" + state := SignalNoticeState{Version: CurrentSignalNoticeVersion} + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, actorID, location); err != nil { + return err + } + acknowledgedAt, err := unit.AssessmentSignalNotices().Get(ctx, actorID, CurrentSignalNoticeVersion) + if errors.Is(err, outbound.ErrAssessmentSignalNoticeNotAcknowledged) { + return nil + } + if err != nil { + return fmt.Errorf("%s - read acknowledgement: %w", location, err) + } + state.Acknowledged, state.AcknowledgedAt = true, acknowledgedAt + return nil + }) + if err != nil { + return SignalNoticeState{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return state, nil +} + +// AcknowledgeSignalNotice records the first acknowledgement of the current +// notice version. A repeat keeps the stored time, so a retry after a lost +// response succeeds. Another version is refused without storing anything. +func (service *SignalService) AcknowledgeSignalNotice( + ctx context.Context, + actorID uuid.UUID, + version int32, +) (SignalNoticeState, error) { + const location = "SignalService.AcknowledgeSignalNotice" + if version != CurrentSignalNoticeVersion { + return SignalNoticeState{}, fmt.Errorf("%s - compare version: %w", location, ErrSignalNoticeVersionMismatch) + } + state := SignalNoticeState{Version: CurrentSignalNoticeVersion, Acknowledged: true} + err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + if err := requireAttemptCandidate(ctx, unit, actorID, location); err != nil { + return err + } + now, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read database time: %w", location, err) + } + state.AcknowledgedAt, err = unit.AssessmentSignalNotices().Acknowledge( + ctx, actorID, CurrentSignalNoticeVersion, now.UTC().Truncate(time.Microsecond), + ) + if err != nil { + return fmt.Errorf("%s - store acknowledgement: %w", location, err) + } + return nil + }) + if err != nil { + return SignalNoticeState{}, fmt.Errorf("%s - transaction: %w", location, err) + } + return state, nil +} diff --git a/backend/internal/usecase/assessment/signal_review.go b/backend/internal/usecase/assessment/signal_review.go new file mode 100644 index 0000000..f7f01dd --- /dev/null +++ b/backend/internal/usecase/assessment/signal_review.go @@ -0,0 +1,491 @@ +package assessment + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "slices" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +// SignalDigester derives the keyed digests that stand for an answer, a login +// session, and a client network in the stored server signals. No digest can be +// turned back into what it stands for without the server secret. +type SignalDigester interface { + AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest + AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest + AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest + // AssessmentDigestKeyVersion is the key generation of the digests above. + AssessmentDigestKeyVersion() int16 +} + +// SignalReviewJobKind is the scheduled job kind that computes reviews. +const SignalReviewJobKind = "assessment.signal_review" + +const ( + // signalReviewPairLimit bounds the other attempts one job refreshes. + signalReviewPairLimit = 50 + // signalReviewDeadlineGrace moves the deadline job past the deadline, so an + // answer committed right at the deadline is in its facts. + signalReviewDeadlineGrace = time.Minute + signalReviewDeadlineKey = "deadline" + signalReviewEndedKey = "ended" +) + +// RequestOrigin is what the HTTP adapter knows about the sender of an answer or +// a signal batch: the authenticated session and the limiter key of the client +// address. It is used only to make digests and is never stored or logged. An +// empty ClientKey means the address could not be resolved. +type RequestOrigin struct { + SessionID uuid.UUID + ClientKey string +} + +// SignalObserver records server-side facts of real attempts and schedules the +// computation of the manual-review band. The band has no effect on the result, +// the category, or the quotas: it is written to its own tables by a scheduled +// job and read by no candidate or employer operation. +type SignalObserver struct { + digester SignalDigester +} + +// NewSignalObserver fails at startup when the digester is missing. +func NewSignalObserver(digester SignalDigester) (*SignalObserver, error) { + if digester == nil { + return nil, errors.New("assessment.NewSignalObserver - digester must be set") + } + return &SignalObserver{digester: digester}, nil +} + +// WithSignalObserver turns on the server signals of answers and the scheduling +// of reviews. Without it the service records nothing. +func (service *AttemptService) WithSignalObserver(observer *SignalObserver) *AttemptService { + service.signalObserver = observer + return service +} + +// WithSignalObserver turns on the origin marks of accepted signal batches. +func (service *SignalService) WithSignalObserver(observer *SignalObserver) *SignalService { + service.observer = observer + return service +} + +func isRealAttemptKind(kind domain.AssessmentAttemptKind) bool { + return kind == domain.AssessmentAttemptKindRoot || kind == domain.AssessmentAttemptKindCorrective +} + +// observeAnswer stores the server time and the keyed answer fingerprint of an +// answer that was just accepted and the origin of its request, and makes sure +// a review job is due when the attempt reaches its deadline. It takes no lock +// besides the attempt row the caller already holds. The time runs from the last +// activity of the attempt, which is the previous answer or the start of the +// current work session, to the answer. It is server time only. +func (observer *SignalObserver) observeAnswer( + ctx context.Context, + unit outbound.UnitOfWork, + before, after domain.AssessmentAttempt, + itemID uuid.UUID, + origin RequestOrigin, +) error { + const location = "SignalObserver.observeAnswer" + if observer == nil || !isRealAttemptKind(after.Kind()) { + return nil + } + snapshot := after.Snapshot() + previous := before.Snapshot() + for _, item := range snapshot.Items { + if item.ID != itemID { + continue + } + answeredAt := item.AnsweredAt + elapsed := answeredAt.Sub(previous.LastActivityAt).Milliseconds() + elapsed = max(0, min(elapsed, int64(1<<31-1))) + observation := domain.AssessmentAnswerObservation{ + AttemptID: snapshot.ID, UserID: snapshot.UserID, ItemInstanceID: item.ID, + FamilyID: item.Variant.FamilyID, FamilyVersion: item.Variant.FamilyVersion, Seed: item.Variant.Seed, + AnswerFormat: item.Variant.AnswerFormat, + Fingerprint: observer.digester.AssessmentAnswerFingerprint( + uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer, + ), + KeyVersion: observer.digester.AssessmentDigestKeyVersion(), + ElapsedMS: int32(elapsed), + // The last activity is the previous answer when an item was answered + // since the session started; then that answer is when this item was + // shown. Otherwise the item is the first of the session. + MeasuredFromAnswer: answeredSince(previous), + ObservedAt: answeredAt, + } + repository := unit.AssessmentSignals() + if err := repository.SaveAnswerObservation(ctx, observation); err != nil { + return fmt.Errorf("%s - store answer observation: %w", location, err) + } + if err := observer.recordOrigin(ctx, repository, snapshot.ID, domain.AssessmentOriginAnswer, answeredAt, origin); err != nil { + return fmt.Errorf("%s - record request origin: %w", location, err) + } + if err := scheduleSignalReview(ctx, unit, snapshot.ID, signalReviewDeadlineKey, snapshot.ExpiresAt.Add(signalReviewDeadlineGrace)); err != nil { + return fmt.Errorf("%s - schedule the review at the deadline: %w", location, err) + } + return nil + } + return fmt.Errorf("%s - item is not part of the attempt: %w", location, domain.ErrInvalidAssessmentReview) +} + +// answeredSince reports whether an item was answered at the last activity of +// the attempt. +func answeredSince(snapshot domain.AssessmentAttemptSnapshot) bool { + for _, item := range snapshot.Items { + if !item.AnsweredAt.IsZero() && item.AnsweredAt.Equal(snapshot.LastActivityAt) { + return true + } + } + return false +} + +// recordOrigin stores the session and network digests of an accepted request +// when they differ from the last stored mark, which is enough to count session +// alternations and distinct networks. A request without a session is not +// marked. The caller holds the attempt row lock, so the last mark is stable. +func (observer *SignalObserver) recordOrigin( + ctx context.Context, + repository outbound.AssessmentSignalRepository, + attemptID domain.AssessmentAttemptID, + source domain.AssessmentOriginSource, + at time.Time, + origin RequestOrigin, +) error { + const location = "SignalObserver.recordOrigin" + if observer == nil || origin.SessionID == uuid.Nil { + return nil + } + id, err := uuid.NewV7() + if err != nil { + return fmt.Errorf("%s - generate mark ID: %w", location, err) + } + mark := domain.AssessmentOriginMark{ + ID: id, AttemptID: attemptID, Source: source, ObservedAt: at, + SessionDigest: observer.digester.AssessmentSessionDigest(attemptID.UUID(), origin.SessionID), + KeyVersion: observer.digester.AssessmentDigestKeyVersion(), + } + if origin.ClientKey != "" { + mark.NetworkDigest = observer.digester.AssessmentNetworkDigest(attemptID.UUID(), origin.ClientKey) + } + last, found, err := repository.LastOriginMark(ctx, attemptID) + if err != nil { + return fmt.Errorf("%s - read last mark: %w", location, err) + } + if found && last.SessionDigest == mark.SessionDigest && last.NetworkDigest == mark.NetworkDigest && last.KeyVersion == mark.KeyVersion { + return nil + } + if err := repository.SaveOriginMark(ctx, mark); err != nil { + return fmt.Errorf("%s - store origin mark: %w", location, err) + } + return nil +} + +// scheduleEndedReview makes a review due now for an attempt that just ended. +// It runs in the transaction of the ending, so the job exists exactly when the +// attempt ended; the review itself is computed later by the job and can never +// block or change the result. +func (observer *SignalObserver) scheduleEndedReview( + ctx context.Context, + unit outbound.UnitOfWork, + attempt domain.AssessmentAttempt, + at time.Time, +) error { + if observer == nil || !isRealAttemptKind(attempt.Kind()) { + return nil + } + return scheduleSignalReview(ctx, unit, attempt.ID(), signalReviewEndedKey, at) +} + +func scheduleSignalReview( + ctx context.Context, + unit outbound.UnitOfWork, + attemptID domain.AssessmentAttemptID, + suffix string, + dueAt time.Time, +) error { + const location = "assessment.scheduleSignalReview" + payload, err := json.Marshal(map[string]string{"attempt_id": attemptID.String()}) + if err != nil { + return fmt.Errorf("%s - encode payload: %w", location, err) + } + job, err := domain.NewScheduledJob(domain.ScheduledJobInput{ + Kind: SignalReviewJobKind, Key: attemptID.String() + ":" + suffix, DueAt: dueAt, Payload: payload, + }) + if err != nil { + return fmt.Errorf("%s - build job: %w", location, err) + } + if _, err := unit.ScheduledJobs().Schedule(ctx, job); err != nil { + return fmt.Errorf("%s - schedule job: %w", location, err) + } + return nil +} + +// SignalReviewJob computes the review of one attempt and refreshes the review +// of every other ended attempt that shares answers with it, so that a match +// flags both. It reads only committed facts and takes no lock apart from the +// rows it writes, which it writes in ascending attempt order, so concurrent +// jobs over shared attempts cannot deadlock. A job for an attempt that is still +// running when the match is found is not needed: the running attempt has its +// own job for its end and its deadline, and that job sees the other facts. +type SignalReviewJob struct { + logger *slog.Logger +} + +// NewSignalReviewJob returns the handler of SignalReviewJobKind. The logger +// receives one line per job with counts and the duration, never an answer, an +// address, or a candidate. +func NewSignalReviewJob(logger *slog.Logger) *SignalReviewJob { + if logger == nil { + logger = slog.New(slog.DiscardHandler) + } + return &SignalReviewJob{logger: logger} +} + +// JobKind is the stable kind name. +func (*SignalReviewJob) JobKind() string { return SignalReviewJobKind } + +// Handle computes the reviews. A malformed payload is final; any storage error +// is retried by the runner with backoff. +func (handler *SignalReviewJob) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error { + const location = "SignalReviewJob.Handle" + started := time.Now() + attemptID, err := signalReviewJobAttempt(job) + if err != nil { + return fmt.Errorf("%s - read payload: %w", location, err) + } + repository := unit.AssessmentSignals() + policyID, found, err := repository.ReviewSubject(ctx, attemptID) + if err != nil { + return fmt.Errorf("%s - read attempt: %w", location, err) + } + if !found { + // The attempt is gone (its account was deleted) or is not a real attempt. + return nil + } + policy, err := unit.Policies().GetByID(ctx, policyID) + if err != nil { + return fmt.Errorf("%s - read pinned policy: %w", location, err) + } + signals := policy.Policy().Assessment.Signals + if signals == nil { + return nil + } + now, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read database time: %w", location, err) + } + now = now.UTC().Truncate(time.Microsecond) + targets, err := reviewTargets(ctx, repository, attemptID, policyID, signals, now) + if err != nil { + return fmt.Errorf("%s - list matched attempts: %w", location, err) + } + if err := writeReviews(ctx, unit, targets, policy, now); err != nil { + return fmt.Errorf("%s - write reviews: %w", location, err) + } + handler.logger.InfoContext(ctx, "assessment review job finished", + slog.Int("reviews", len(targets)), slog.Int("matched_attempts", len(targets)-1), + slog.Int64("duration_ms", time.Since(started).Milliseconds())) + return nil +} + +func signalReviewJobAttempt(job outbound.ClaimedJob) (domain.AssessmentAttemptID, error) { + var payload struct { + AttemptID string `json:"attempt_id"` + } + if err := json.Unmarshal(job.Payload, &payload); err != nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("decode payload: %w", inbound.ErrJobRejected) + } + parsed, err := uuid.Parse(payload.AttemptID) + if err != nil || parsed == uuid.Nil { + return domain.AssessmentAttemptID{}, fmt.Errorf("payload names no attempt: %w", inbound.ErrJobRejected) + } + return domain.AssessmentAttemptID(parsed), nil +} + +// writeReviews locks every review it will write, in ascending attempt order, +// before any fact is read. The later of two jobs over one attempt then waits +// here and reads what the earlier one committed, so no job overwrites a newer +// review with an older evaluation, and no lock order can form a cycle. +func writeReviews( + ctx context.Context, + unit outbound.UnitOfWork, + targets []reviewTarget, + own domain.PolicyVersion, + now time.Time, +) error { + repository := unit.AssessmentSignals() + for _, entry := range targets { + if err := repository.LockReview(ctx, entry.id); err != nil { + return fmt.Errorf("lock review: %w", err) + } + } + for _, entry := range targets { + pinned := own + if entry.policy != own.ID() { + var err error + if pinned, err = unit.Policies().GetByID(ctx, entry.policy); err != nil { + return fmt.Errorf("read pinned policy of a matched attempt: %w", err) + } + } + if err := evaluateReview(ctx, repository, entry.id, pinned, now); err != nil { + return fmt.Errorf("evaluate attempt: %w", err) + } + } + return nil +} + +type reviewTarget struct { + id domain.AssessmentAttemptID + policy domain.PolicyVersionID +} + +// reviewTargets lists the attempt itself and the ended attempts whose pair with +// it reaches the attention level, in ascending attempt order. Two jobs over the +// same pair therefore lock the review rows in the same order. +func reviewTargets( + ctx context.Context, + repository outbound.AssessmentSignalRepository, + attemptID domain.AssessmentAttemptID, + policyID domain.PolicyVersionID, + signals *domain.AssessmentSignalPolicy, + now time.Time, +) ([]reviewTarget, error) { + pairs, err := repository.DuplicatePairs(ctx, attemptID, outbound.AssessmentDuplicateQuery{ + IntegerCapBits: signals.DuplicateIntegerCapBits, SequenceCapBits: signals.DuplicateSequenceCapBits, + MinBits: signals.DuplicateAttentionBits, EndedOnly: true, Now: now, Limit: signalReviewPairLimit, + }) + if err != nil { + return nil, err + } + targets := []reviewTarget{{id: attemptID, policy: policyID}} + for _, pair := range pairs { + if pair.AttemptID != attemptID { + targets = append(targets, reviewTarget{id: pair.AttemptID, policy: pair.PolicyVersionID}) + } + } + slices.SortFunc(targets, func(left, right reviewTarget) int { return bytes.Compare(left.id[:], right.id[:]) }) + return targets, nil +} + +// evaluateReview computes and stores the review of one attempt under the +// signal thresholds of the policy version that attempt is pinned to. A version +// without a signal section produces no review. +func evaluateReview( + ctx context.Context, + repository outbound.AssessmentSignalRepository, + attemptID domain.AssessmentAttemptID, + policy domain.PolicyVersion, + now time.Time, +) error { + const location = "assessment.evaluateReview" + signals := policy.Policy().Assessment.Signals + if signals == nil { + return nil + } + inputs, err := repository.ReviewInputs(ctx, attemptID) + if err != nil { + return fmt.Errorf("%s - read stored facts: %w", location, err) + } + best, err := repository.DuplicatePairs(ctx, attemptID, outbound.AssessmentDuplicateQuery{ + IntegerCapBits: signals.DuplicateIntegerCapBits, SequenceCapBits: signals.DuplicateSequenceCapBits, + Limit: 1, + }) + if err != nil { + return fmt.Errorf("%s - find the strongest pair: %w", location, err) + } + times := signals.ClassifyResponseTimes(inputs.Answers) + anomalies := domain.CountOriginAnomalies(inputs.Marks) + measures := domain.AssessmentReviewMeasures{ + AnsweredItems: times.Answered, FastAnswers: times.Fast, DeviatingAnswers: times.Deviating, + ParallelAlternations: anomalies.ParallelAlternations, ExtraNetworks: anomalies.ExtraNetworks, + ClientFocusLossMS: inputs.ClientFocusLossMS, ClientClipboardEvents: inputs.ClientClipboardCount, + ClientFullscreenExits: inputs.ClientFullscreenExit, + } + if len(best) > 0 { + measures.DuplicateEvidenceBits = best[0].EvidenceBits + measures.MatchedIntegerItems, measures.MatchedSequenceItems = best[0].IntegerItems, best[0].SequenceItems + } + review := domain.AssessmentAttemptReview{ + AttemptID: attemptID, PolicyVersionID: policy.ID(), PolicyVersion: policy.Version(), + Measures: measures, Outcome: signals.Evaluate(measures), EvaluatedAt: now, UpdatedAt: now, + } + if err := repository.SaveReview(ctx, review); err != nil { + return fmt.Errorf("%s - store review: %w", location, err) + } + return nil +} + +// ReviewOperator lets an operator read the stored review of one attempt. Every +// read is recorded with the operator handle. Until staff roles exist this is +// the only way to read a band. +type ReviewOperator struct { + transactor outbound.Transactor +} + +func NewReviewOperator(transactor outbound.Transactor) (*ReviewOperator, error) { + if transactor == nil { + return nil, errors.New("assessment.NewReviewOperator - transactor must be set") + } + return &ReviewOperator{transactor: transactor}, nil +} + +// Inspect returns the review of an attempt and records the read, also when the +// attempt has no review. The actor is an audit handle, not authentication. +func (operator *ReviewOperator) Inspect( + ctx context.Context, + attemptID domain.AssessmentAttemptID, + actor string, +) (domain.AssessmentAttemptReview, error) { + const location = "ReviewOperator.Inspect" + parsed, err := domain.ParseAssessmentReviewActor(actor) + if err != nil { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - parse actor: %w", location, err) + } + if attemptID.IsZero() { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentReview) + } + readID, err := uuid.NewV7() + if err != nil { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - generate read ID: %w", location, err) + } + var review domain.AssessmentAttemptReview + missing := false + err = operator.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + repository := unit.AssessmentSignals() + stored, err := repository.GetReview(ctx, attemptID) + switch { + case errors.Is(err, outbound.ErrAssessmentReviewNotFound): + missing = true + case err != nil: + return fmt.Errorf("%s - read review: %w", location, err) + default: + review = stored + } + at, err := unit.AssessmentBank().DatabaseTime(ctx) + if err != nil { + return fmt.Errorf("%s - read database time: %w", location, err) + } + if err := repository.RecordReviewRead(ctx, readID, attemptID, parsed, !missing, at.UTC().Truncate(time.Microsecond)); err != nil { + return fmt.Errorf("%s - record read: %w", location, err) + } + return nil + }) + if err != nil { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - transaction: %w", location, err) + } + if missing { + return domain.AssessmentAttemptReview{}, fmt.Errorf("%s - attempt has no review: %w", location, outbound.ErrAssessmentReviewNotFound) + } + return review, nil +} diff --git a/backend/internal/usecase/assessment/signal_review_test.go b/backend/internal/usecase/assessment/signal_review_test.go new file mode 100644 index 0000000..366b6d2 --- /dev/null +++ b/backend/internal/usecase/assessment/signal_review_test.go @@ -0,0 +1,700 @@ +package assessment + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "math" + "slices" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +var signalReviewTestTime = time.Date(2026, time.October, 5, 9, 0, 0, 0, time.UTC) + +// signalDigesterFake derives plain SHA-256 values so a test can compare them; +// the production keyring uses HMAC under a server secret. +type signalDigesterFake struct{} + +func (signalDigesterFake) AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, answer []byte) domain.AssessmentDigest { + return domain.AssessmentDigest(sha256.Sum256(append(append(familyID[:], binary.BigEndian.AppendUint32(nil, uint32(familyVersion))...), answer...))) +} + +func (signalDigesterFake) AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest { + return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], sessionID[:]...))) +} + +func (signalDigesterFake) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest { + return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], clientKey...))) +} + +func (signalDigesterFake) AssessmentDigestKeyVersion() int16 { return 7 } + +// signalRepositoryFake records the writes of the observer and the job. The +// embedded interface is nil, so a call the test does not expect panics. +type signalRepositoryFake struct { + outbound.AssessmentSignalRepository + + observations []domain.AssessmentAnswerObservation + marks []domain.AssessmentOriginMark + reviews []domain.AssessmentAttemptReview + inputs outbound.AssessmentReviewInputs + pairs map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair + subjects map[domain.AssessmentAttemptID]domain.PolicyVersionID + queries []outbound.AssessmentDuplicateQuery + // events records the order of locks and reads of a job. + events []string +} + +func (repository *signalRepositoryFake) SaveAnswerObservation(_ context.Context, observation domain.AssessmentAnswerObservation) error { + repository.observations = append(repository.observations, observation) + return nil +} + +func (repository *signalRepositoryFake) SaveOriginMark(_ context.Context, mark domain.AssessmentOriginMark) error { + repository.marks = append(repository.marks, mark) + return nil +} + +func (repository *signalRepositoryFake) LastOriginMark(context.Context, domain.AssessmentAttemptID) (domain.AssessmentOriginMark, bool, error) { + if len(repository.marks) == 0 { + return domain.AssessmentOriginMark{}, false, nil + } + return repository.marks[len(repository.marks)-1], true, nil +} + +func (repository *signalRepositoryFake) ReviewInputs(context.Context, domain.AssessmentAttemptID) (outbound.AssessmentReviewInputs, error) { + repository.events = append(repository.events, "read") + return repository.inputs, nil +} + +func (repository *signalRepositoryFake) LockReview(_ context.Context, attemptID domain.AssessmentAttemptID) error { + repository.events = append(repository.events, "lock:"+attemptID.String()) + return nil +} + +func (repository *signalRepositoryFake) DuplicatePairs( + _ context.Context, + attemptID domain.AssessmentAttemptID, + query outbound.AssessmentDuplicateQuery, +) ([]outbound.AssessmentDuplicatePair, error) { + repository.queries = append(repository.queries, query) + pairs := repository.pairs[attemptID] + if query.MinBits > 0 { + pairs = slices.DeleteFunc(slices.Clone(pairs), func(pair outbound.AssessmentDuplicatePair) bool { return pair.EvidenceBits < query.MinBits }) + } + return pairs, nil +} + +func (repository *signalRepositoryFake) ReviewSubject(_ context.Context, attemptID domain.AssessmentAttemptID) (domain.PolicyVersionID, bool, error) { + id, found := repository.subjects[attemptID] + return id, found, nil +} + +func (repository *signalRepositoryFake) SaveReview(_ context.Context, review domain.AssessmentAttemptReview) error { + repository.reviews = append(repository.reviews, review) + return nil +} + +type jobSchedulerFake struct { + jobs []domain.ScheduledJob +} + +func (scheduler *jobSchedulerFake) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) { + scheduler.jobs = append(scheduler.jobs, job) + return true, nil +} + +func (*jobSchedulerFake) Cancel(context.Context, string, string) (bool, error) { return false, nil } + +type policiesFake struct { + outbound.PolicyRepository + + versions map[domain.PolicyVersionID]domain.PolicyVersion +} + +func (policies policiesFake) GetByID(_ context.Context, id domain.PolicyVersionID) (domain.PolicyVersion, error) { + return policies.versions[id], nil +} + +type bankClockFake struct { + outbound.AssessmentBankRepository +} + +func (bankClockFake) DatabaseTime(context.Context) (time.Time, error) { + return signalReviewTestTime, nil +} + +type signalUnitFake struct { + outbound.UnitOfWork + + repository *signalRepositoryFake + scheduler *jobSchedulerFake + policies policiesFake +} + +func newSignalUnitFake() *signalUnitFake { + return &signalUnitFake{repository: &signalRepositoryFake{}, scheduler: &jobSchedulerFake{}} +} + +func (unit *signalUnitFake) AssessmentSignals() outbound.AssessmentSignalRepository { + return unit.repository +} +func (unit *signalUnitFake) ScheduledJobs() outbound.JobScheduler { return unit.scheduler } +func (unit *signalUnitFake) Policies() outbound.PolicyRepository { return unit.policies } +func (unit *signalUnitFake) AssessmentBank() outbound.AssessmentBankRepository { + return bankClockFake{} +} + +func signalReviewFamily(t *testing.T, draft domain.AssessmentFamilyDraft) domain.AssessmentFamily { + t.Helper() + core, hash := draft.Core(), draft.ContentHash() + generator, err := draft.SeedGeneratorJSON() + if err != nil { + t.Fatalf("SeedGeneratorJSON() error = %v", err) + } + answerKey, err := draft.AnswerKeyJSON() + if err != nil { + t.Fatalf("AnswerKeyJSON() error = %v", err) + } + rubric, err := draft.RubricJSON() + if err != nil { + t.Fatalf("RubricJSON() error = %v", err) + } + family, err := domain.RestoreAssessmentFamily(domain.StoredAssessmentFamily{ + ID: draft.ID(), FamilyKey: string(core.Key), Version: core.Version, Category: string(core.Category), + Specialization: string(core.Specialization), Title: core.Title, BundleName: string(core.BundleName), + Author: string(core.Author), Reviewer: string(core.Reviewer), ReviewStatus: string(core.ReviewStatus), + SeedGenerator: generator, AnswerKey: answerKey, Rubric: rubric, ContentHash: hash[:], + HashScheme: draft.HashScheme(), Lifecycle: string(domain.AssessmentLifecycleDraft), CreatedAt: signalReviewTestTime, + }) + if err != nil { + t.Fatalf("RestoreAssessmentFamily() error = %v", err) + } + return family +} + +func signalReviewDemoFamilies(t *testing.T) []domain.AssessmentFamily { + t.Helper() + drafts, err := loadDemoBundle(t).Drafts() + if err != nil { + t.Fatalf("Drafts() error = %v", err) + } + families := make([]domain.AssessmentFamily, 0, len(drafts)) + for _, draft := range drafts { + families = append(families, signalReviewFamily(t, draft)) + } + return families +} + +func signalReviewPolicyVersion(t *testing.T, number int32, policy domain.ProductPolicy) domain.PolicyVersion { + t.Helper() + draft, err := domain.NewPolicyVersionDraft(domain.NewPolicyVersionDraftInput{ + Key: domain.ProductPolicyKey, Kind: domain.PolicyKindDemo, Author: domain.DemoPolicySeedAuthor, + EffectiveAt: signalReviewTestTime, Policy: policy, + }) + if err != nil { + t.Fatalf("NewPolicyVersionDraft() error = %v", err) + } + numbered, err := draft.WithVersion(number) + if err != nil { + t.Fatalf("WithVersion() error = %v", err) + } + hash := numbered.DocumentHash() + version, err := domain.RestorePolicyVersion(domain.StoredPolicyVersion{ + ID: numbered.ID(), Key: string(numbered.Key()), Version: numbered.Version(), Kind: string(numbered.Kind()), + Author: string(numbered.Author()), EffectiveAt: signalReviewTestTime, CreatedAt: signalReviewTestTime, + Document: numbered.Document(), DocumentHash: hash[:], + }) + if err != nil { + t.Fatalf("RestorePolicyVersion() error = %v", err) + } + return version +} + +func signalReviewAttempt(t *testing.T, policy domain.PolicyVersion, kind domain.AssessmentAttemptKind) domain.AssessmentAttempt { + t.Helper() + families := signalReviewDemoFamilies(t) + items := make([]domain.AssessmentAttemptItemInput, len(families)) + for index, family := range families { + variant, err := family.NewVariant(domain.VariantSeed(1000 + index)) + if err != nil { + t.Fatalf("NewVariant() error = %v", err) + } + items[index] = domain.AssessmentAttemptItemInput{Variant: variant} + } + versions := domain.AssessmentAttemptVersions{ + ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(), + BankVersion: "backend-demo.v1", AlgorithmVersion: "assessment.v1", + } + input := domain.NewAssessmentAttemptInput{ + UserID: uuid.New(), Kind: kind, BankCategory: "backend", Versions: versions, Policy: policy, + CreatedAt: signalReviewTestTime, Items: items, + } + if kind == domain.AssessmentAttemptKindDemoExpress { + input.BankCategory = "training-demo" + input.Items = items[:policy.Policy().Assessment.Training.DemoExpressItemCount] + input.Versions.TrainingBindingID, input.Versions.TrainingManifestHash = uuid.New(), [32]byte{2} + } else { + specialization, grade := domain.SpecializationBackend, domain.GradeJunior + input.Specialization, input.TargetGrade = &specialization, &grade + input.Versions.GradingPolicyVersionID, input.Versions.OpeningID = policy.ID(), uuid.New() + input.Versions.OpeningManifestHash = [32]byte{1} + } + attempt, err := domain.NewAssessmentAttempt(input) + if err != nil { + t.Fatalf("NewAssessmentAttempt() error = %v", err) + } + return attempt +} + +func signalReviewFirstAnswer(t *testing.T, attempt domain.AssessmentAttempt, at time.Time) (domain.AssessmentAttempt, domain.AssessmentAttemptItemSnapshot) { + t.Helper() + item := attempt.Snapshot().Items[0] + updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, json.RawMessage(`{"format":"number","number":424242}`), at) + if err != nil || !changed { + t.Fatalf("SubmitAnswer() = changed %v, error %v", changed, err) + } + return updated, updated.Snapshot().Items[0] +} + +func signalReviewSecondAnswer(t *testing.T, attempt domain.AssessmentAttempt, at time.Time) (domain.AssessmentAttempt, domain.AssessmentAttemptItemSnapshot) { + t.Helper() + item := attempt.Snapshot().Items[1] + tasks := item.Variant.Parameters["tasks"] + elements := make([]string, 0, tasks) + for task := int32(1); task <= tasks; 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 order answer: %v", err) + } + updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, at) + if err != nil || !changed { + t.Fatalf("SubmitAnswer(second) = changed %v, error %v", changed, err) + } + return updated, updated.Snapshot().Items[1] +} + +func TestObserveAnswerStoresServerTimeAndKeyedFingerprintOnly(t *testing.T) { + policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()) + attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot) + answeredAt := signalReviewTestTime.Add(12*time.Second + 340*time.Millisecond) + updated, item := signalReviewFirstAnswer(t, attempt, answeredAt) + observer, err := NewSignalObserver(signalDigesterFake{}) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + unit := newSignalUnitFake() + origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77"} + if err := observer.observeAnswer(context.Background(), unit, attempt, updated, item.ID, origin); err != nil { + t.Fatalf("observeAnswer() error = %v", err) + } + if len(unit.repository.observations) != 1 || len(unit.repository.marks) != 1 { + t.Fatalf("stored %d observations and %d marks, want one of each", len(unit.repository.observations), len(unit.repository.marks)) + } + observation := unit.repository.observations[0] + if observation.ElapsedMS != 12340 || observation.ItemInstanceID != item.ID || observation.FamilyID != item.Variant.FamilyID || + observation.Seed != item.Variant.Seed || observation.AnswerFormat != item.Variant.AnswerFormat { + t.Fatalf("observation = %+v, want 12340 ms from the attempt start for the answered item", observation) + } + if observation.MeasuredFromAnswer { + t.Fatal("the first item of a session was measured from an answer; it is measured from the session start") + } + if observation.KeyVersion != 7 || unit.repository.marks[0].KeyVersion != 7 { + t.Fatalf("key versions = %d and %d, want the digester generation 7", observation.KeyVersion, unit.repository.marks[0].KeyVersion) + } + if want := (signalDigesterFake{}).AssessmentAnswerFingerprint(uuid.UUID(item.Variant.FamilyID), item.Variant.FamilyVersion, item.Answer); observation.Fingerprint != want { + t.Fatal("fingerprint is not the keyed digest of the canonical answer") + } + mark := unit.repository.marks[0] + if mark.Source != domain.AssessmentOriginAnswer || mark.NetworkDigest.IsZero() || mark.SessionDigest.IsZero() { + t.Fatalf("origin mark = %+v, want an answer mark with session and network digests", mark) + } + stored := fmt.Sprintf("%+v %+v", observation, mark) + for _, secret := range []string{"424242", "198.51.100.77", origin.SessionID.String()} { + if strings.Contains(stored, secret) { + t.Fatalf("stored facts contain %q", secret) + } + } + + // A review is due when the attempt reaches its deadline, however it ends. + if len(unit.scheduler.jobs) != 1 { + t.Fatalf("scheduled %d jobs, want the review at the deadline", len(unit.scheduler.jobs)) + } + job := unit.scheduler.jobs[0] + if job.Kind() != SignalReviewJobKind || job.Key() != attempt.ID().String()+":deadline" || !job.DueAt().Equal(attempt.ExpiresAt().Add(time.Minute)) { + t.Fatalf("job = %s %s due %s, want the deadline job of the attempt due a minute after its expiry", job.Kind(), job.Key(), job.DueAt()) + } + if strings.Contains(string(job.Payload()), "424242") || !strings.Contains(string(job.Payload()), attempt.ID().String()) { + t.Fatalf("job payload = %s, want the attempt ID only", job.Payload()) + } +} + +func TestObserveAnswerMeasuresLaterItemsFromThePreviousAnswerAndMarksOnlyChanges(t *testing.T) { + policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()) + first := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot) + firstUpdated, firstItem := signalReviewFirstAnswer(t, first, signalReviewTestTime.Add(20*time.Second)) + secondUpdated, secondItem := signalReviewSecondAnswer(t, firstUpdated, signalReviewTestTime.Add(24*time.Second)) + observer, err := NewSignalObserver(signalDigesterFake{}) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + unit := newSignalUnitFake() + origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77"} + if err := observer.observeAnswer(context.Background(), unit, first, firstUpdated, firstItem.ID, origin); err != nil { + t.Fatalf("observeAnswer(first) error = %v", err) + } + if err := observer.observeAnswer(context.Background(), unit, firstUpdated, secondUpdated, secondItem.ID, origin); err != nil { + t.Fatalf("observeAnswer(second) error = %v", err) + } + second := unit.repository.observations[1] + if second.ElapsedMS != 4000 || !second.MeasuredFromAnswer { + t.Fatalf("second observation = %+v, want 4000 ms measured from the previous answer", second) + } + if len(unit.repository.marks) != 1 { + t.Fatalf("stored %d marks for two requests from one session and network, want 1", len(unit.repository.marks)) + } + + // Writing a mark for every request would grow without bound; a change of the + // session or the network writes one. + thirdOrigin := RequestOrigin{SessionID: origin.SessionID, ClientKey: "203.0.113.5"} + if err := observer.recordOrigin(context.Background(), unit.repository, first.ID(), domain.AssessmentOriginSignals, signalReviewTestTime, thirdOrigin); err != nil { + t.Fatalf("recordOrigin(new network) error = %v", err) + } + if err := observer.recordOrigin(context.Background(), unit.repository, first.ID(), domain.AssessmentOriginSignals, signalReviewTestTime, thirdOrigin); err != nil { + t.Fatalf("recordOrigin(repeat) error = %v", err) + } + if len(unit.repository.marks) != 2 { + t.Fatalf("stored %d marks after a network change and a repeat, want 2", len(unit.repository.marks)) + } +} + +func TestObserveAnswerSkipsTrainingAttemptsAndMarksNothingWithoutASession(t *testing.T) { + observer, err := NewSignalObserver(signalDigesterFake{}) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()) + + training := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindDemoExpress) + trainingUpdated, trainingItem := signalReviewFirstAnswer(t, training, signalReviewTestTime.Add(time.Second)) + unit := newSignalUnitFake() + if err := observer.observeAnswer(context.Background(), unit, training, trainingUpdated, trainingItem.ID, RequestOrigin{SessionID: uuid.New()}); err != nil { + t.Fatalf("observeAnswer(training) error = %v", err) + } + if err := observer.scheduleEndedReview(context.Background(), unit, trainingUpdated, signalReviewTestTime); err != nil { + t.Fatalf("scheduleEndedReview(training) error = %v", err) + } + if len(unit.repository.observations)+len(unit.repository.marks)+len(unit.scheduler.jobs) != 0 { + t.Fatal("a training attempt produced server signals or a review job") + } + + root := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot) + rootUpdated, rootItem := signalReviewFirstAnswer(t, root, signalReviewTestTime.Add(time.Second)) + if err := observer.observeAnswer(context.Background(), unit, root, rootUpdated, rootItem.ID, RequestOrigin{}); err != nil { + t.Fatalf("observeAnswer(no session) error = %v", err) + } + if len(unit.repository.observations) != 1 || len(unit.repository.marks) != 0 { + t.Fatalf("no-session request stored %d observations and %d marks, want 1 and 0", len(unit.repository.observations), len(unit.repository.marks)) + } + + var disabled *SignalObserver + if err := disabled.observeAnswer(context.Background(), unit, root, rootUpdated, rootItem.ID, RequestOrigin{SessionID: uuid.New()}); err != nil { + t.Fatalf("observeAnswer(disabled observer) error = %v", err) + } + if err := disabled.scheduleEndedReview(context.Background(), unit, rootUpdated, signalReviewTestTime); err != nil { + t.Fatalf("scheduleEndedReview(disabled observer) error = %v", err) + } + if len(unit.repository.observations) != 1 { + t.Fatal("a disabled observer stored an observation") + } + if _, err := NewSignalObserver(nil); err == nil { + t.Fatal("NewSignalObserver(nil) accepted a missing digester") + } +} + +func TestScheduleEndedReviewIsKeyedByTheAttemptEnding(t *testing.T) { + observer, err := NewSignalObserver(signalDigesterFake{}) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + attempt := signalReviewAttempt(t, signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()), domain.AssessmentAttemptKindRoot) + unit := newSignalUnitFake() + if err := observer.scheduleEndedReview(context.Background(), unit, attempt, signalReviewTestTime); err != nil { + t.Fatalf("scheduleEndedReview() error = %v", err) + } + job := unit.scheduler.jobs[0] + if job.Key() != attempt.ID().String()+":ended" || !job.DueAt().Equal(signalReviewTestTime) { + t.Fatalf("job = %s due %s, want the ended job due at the ending", job.Key(), job.DueAt()) + } +} + +func signalJob(attemptID domain.AssessmentAttemptID) outbound.ClaimedJob { + return outbound.ClaimedJob{ + Kind: SignalReviewJobKind, Key: attemptID.String() + ":ended", + Payload: json.RawMessage(`{"attempt_id":"` + attemptID.String() + `"}`), + } +} + +func TestSignalReviewJobRefusesBrokenPayloadsAndIgnoresMissingAttempts(t *testing.T) { + job := NewSignalReviewJob(nil) + if job.JobKind() != "assessment.signal_review" { + t.Fatalf("JobKind() = %q", job.JobKind()) + } + unit := newSignalUnitFake() + for _, payload := range []string{``, `{}`, `{"attempt_id":"not-a-uuid"}`, `{"attempt_id":"00000000-0000-0000-0000-000000000000"}`} { + err := job.Handle(context.Background(), unit, outbound.ClaimedJob{Payload: json.RawMessage(payload)}) + if !errors.Is(err, inbound.ErrJobRejected) { + t.Errorf("Handle(%q) error = %v, want a rejected job", payload, err) + } + } + if err := job.Handle(context.Background(), unit, signalJob(domain.AssessmentAttemptID(uuid.New()))); err != nil { + t.Fatalf("Handle(unknown attempt) error = %v, want a finished job", err) + } + if len(unit.repository.reviews) != 0 { + t.Fatal("a review was stored for an unknown attempt") + } +} + +// A job writes the reviews of its attempt and of the matched ended attempts in +// ascending attempt order, each under the policy version that attempt is pinned +// to, so two concurrent jobs over the same pair take row locks in one order. +func TestSignalReviewJobWritesPairsInAscendingOrderUnderTheirOwnPolicies(t *testing.T) { + strictSignals := domain.DemoAssessmentSignalPolicy() + strictSignals.FastAnswersAttention, strictSignals.FastAnswersReview = 1, 2 + strict := domain.DemoProductPolicyV3() + strict.Assessment.Signals = &strictSignals + relaxedSignals := domain.DemoAssessmentSignalPolicy() + relaxedSignals.FastAnswersAttention, relaxedSignals.FastAnswersReview = 100, 200 + relaxed := domain.DemoProductPolicyV3() + relaxed.Assessment.Signals = &relaxedSignals + strictVersion := signalReviewPolicyVersion(t, 4, strict) + relaxedVersion := signalReviewPolicyVersion(t, 5, relaxed) + legacyVersion := signalReviewPolicyVersion(t, 2, domain.DemoProductPolicyV2()) + + low := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000001")) + middle := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000002")) + high := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000003")) + legacy := domain.AssessmentAttemptID(uuid.MustParse("00000000-0000-7000-8000-000000000004")) + unit := newSignalUnitFake() + unit.policies = policiesFake{versions: map[domain.PolicyVersionID]domain.PolicyVersion{ + strictVersion.ID(): strictVersion, relaxedVersion.ID(): relaxedVersion, legacyVersion.ID(): legacyVersion, + }} + unit.repository.subjects = map[domain.AssessmentAttemptID]domain.PolicyVersionID{high: strictVersion.ID()} + unit.repository.inputs = outbound.AssessmentReviewInputs{Answers: []domain.AssessmentResponseSample{ + answerSampleForJob(100), answerSampleForJob(100), + }} + unit.repository.pairs = map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair{high: { + {AttemptID: middle, PolicyVersionID: relaxedVersion.ID(), EvidenceBits: 90}, + {AttemptID: low, PolicyVersionID: strictVersion.ID(), EvidenceBits: 80}, + {AttemptID: legacy, PolicyVersionID: legacyVersion.ID(), EvidenceBits: 70}, + // Below the attention level of the evaluated policy: not refreshed. + {AttemptID: domain.AssessmentAttemptID(uuid.New()), PolicyVersionID: strictVersion.ID(), EvidenceBits: 1}, + }} + if err := NewSignalReviewJob(nil).Handle(context.Background(), unit, signalJob(high)); err != nil { + t.Fatalf("Handle() error = %v", err) + } + reviews := unit.repository.reviews + if len(reviews) != 3 { + t.Fatalf("stored %d reviews, want the attempt, its two matched attempts, and none for a version without a signal section", len(reviews)) + } + if reviews[0].AttemptID != low || reviews[1].AttemptID != middle || reviews[2].AttemptID != high { + t.Fatalf("review order = %s %s %s, want ascending attempt IDs", reviews[0].AttemptID, reviews[1].AttemptID, reviews[2].AttemptID) + } + if reviews[0].Outcome.Band != domain.AssessmentReviewBandReview || reviews[1].Outcome.Band != domain.AssessmentReviewBandNormal || + reviews[1].PolicyVersionID != relaxedVersion.ID() { + t.Fatalf("bands = %s/%s, want each attempt judged by its own pinned policy", reviews[0].Outcome.Band, reviews[1].Outcome.Band) + } + // All locks come first, in ascending order, before any fact is read. + wantEvents := []string{"lock:" + low.String(), "lock:" + middle.String(), "lock:" + high.String(), "lock:" + legacy.String()} + if len(unit.repository.events) < 5 || !slices.Equal(unit.repository.events[:4], wantEvents) || unit.repository.events[4] != "read" { + t.Fatalf("job events = %v, want the four review locks in ascending order before the first read", unit.repository.events) + } + queried := unit.repository.queries[0] + if !queried.EndedOnly || queried.Limit != signalReviewPairLimit || queried.MinBits != strictSignals.DuplicateAttentionBits { + t.Fatalf("pair query = %+v, want ended attempts only, bounded, from the attention level", queried) + } +} + +func answerSampleForJob(elapsed int32) domain.AssessmentResponseSample { + return domain.AssessmentResponseSample{AnswerFormat: domain.AnswerFormatInteger, ElapsedMS: elapsed, MeasuredFromAnswer: true} +} + +func TestEvaluateReviewTakesTheStrongestPair(t *testing.T) { + version := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()) + repository := &signalRepositoryFake{pairs: map[domain.AssessmentAttemptID][]outbound.AssessmentDuplicatePair{}} + attemptID := domain.AssessmentAttemptID(uuid.New()) + repository.pairs[attemptID] = []outbound.AssessmentDuplicatePair{ + {AttemptID: domain.AssessmentAttemptID(uuid.New()), EvidenceBits: 66, IntegerItems: 8, SequenceItems: 1}, + {AttemptID: domain.AssessmentAttemptID(uuid.New()), EvidenceBits: 20, IntegerItems: 3}, + } + if err := evaluateReview(context.Background(), repository, attemptID, version, signalReviewTestTime); err != nil { + t.Fatalf("evaluateReview() error = %v", err) + } + review := repository.reviews[0] + if review.Measures.DuplicateEvidenceBits != 66 || review.Measures.MatchedIntegerItems != 8 || review.Measures.MatchedSequenceItems != 1 || + review.Outcome.Band != domain.AssessmentReviewBandReview { + t.Fatalf("review = %+v, want the strongest pair and the review band", review) + } + if query := repository.queries[0]; query.Limit != 1 || query.MinBits != 0 || query.EndedOnly { + t.Fatalf("pair query = %+v, want the single strongest pair among all attempts", query) + } +} + +// The duplicate thresholds are sums of bits over one pair of attempts, and a +// matched answer carries -log2 of the share of attempts that hold its value. The +// test measures, for the four demo families, how likely two independent +// candidates are to give the same correct answer and which values they share, +// and from that computes the probability that one pair of honest candidates +// reaches each threshold on a 23-item attempt. Since an attempt is compared with +// every other one, the per-attempt rate is that probability times the number of +// rivals. The measurement covers four AI-drafted families; it is not a +// calibration, and a real bank needs its own run. +func TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow(t *testing.T) { + const ( + seedsPerFamily = 4000 + rivals = 1e4 + items = 23 + // Targets for one honest attempt facing all rivals. + attentionTarget = 1e-3 + reviewTarget = 1e-8 + ) + policy := domain.DemoAssessmentSignalPolicy() + type outcome struct { + probability float64 + bits int + } + families := signalReviewDemoFamilies(t) + perFamily := make([][]outcome, 0, len(families)) + for _, family := range families { + counts := map[string]int{} + var format string + for seed := 1; seed <= seedsPerFamily; seed++ { + variant, err := family.NewVariant(domain.VariantSeed(seed)) + if err != nil { + t.Fatalf("NewVariant(%d) error = %v", seed, err) + } + counts[variant.ReferenceAnswer]++ + format = variant.AnswerFormat + } + capBits := float64(policy.DuplicateIntegerCapBits) + if format == domain.AnswerFormatIntegerSequence { + capBits = float64(policy.DuplicateSequenceCapBits) + } + matched := 0.0 + outcomes := make([]outcome, 0, len(counts)+1) + for _, count := range counts { + share := float64(count) / seedsPerFamily + // Rounded up, so the computed probability is not understated. + bits := int(math.Ceil(math.Min(capBits, -math.Log2(share)))) + outcomes = append(outcomes, outcome{probability: share * share, bits: bits}) + matched += share * share + } + perFamily = append(perFamily, append(outcomes, outcome{probability: 1 - matched})) + } + tail := func(threshold int) float64 { + distribution := make([]float64, threshold+1) + distribution[0] = 1 + for item := range items { + next := make([]float64, threshold+1) + for sum, mass := range distribution { + if mass == 0 { + continue + } + for _, entry := range perFamily[item%len(perFamily)] { + next[min(sum+entry.bits, threshold)] += mass * entry.probability + } + } + distribution = next + } + return distribution[threshold] + } + attention := tail(int(policy.DuplicateAttentionBits)) * rivals + review := tail(int(policy.DuplicateReviewBits)) * rivals + t.Logf("per-attempt false flag rate against %.0f rivals: attention %.3g, review %.3g", rivals, attention, review) + if attention > attentionTarget || review > reviewTarget { + t.Fatalf("per-attempt false flag rate attention %.3g (target %.0e), review %.3g (target %.0e)", attention, attentionTarget, review, reviewTarget) + } +} + +func TestSignalLogsAndErrorsCarryNoAnswerOrAddress(t *testing.T) { + policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3()) + attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot) + updated, item := signalReviewFirstAnswer(t, attempt, signalReviewTestTime.Add(time.Second)) + observer, err := NewSignalObserver(signalDigesterFake{}) + if err != nil { + t.Fatalf("NewSignalObserver() error = %v", err) + } + // An observation for an item the attempt does not hold is refused with an + // error that names neither the answer nor the origin. + err = observer.observeAnswer(context.Background(), newSignalUnitFake(), attempt, updated, uuid.New(), RequestOrigin{SessionID: uuid.New(), ClientKey: "203.0.113.9"}) + if err == nil { + t.Fatal("observeAnswer(foreign item) succeeded") + } + for _, secret := range []string{"424242", "203.0.113.9", string(item.Answer)} { + if strings.Contains(err.Error(), secret) { + t.Fatalf("error text contains %q: %v", secret, err) + } + } +} + +// copiedPairEvidence is the evidence of a pair that copies every answer of an +// attempt of the given length in a population of the given number of answers +// per family: each shared value is held by the two copiers only, so a matched +// answer carries log2(population / 2) bits up to the cap of its format. The +// items follow the demo bank: three integer families for one order family. +func copiedPairEvidence(policy domain.AssessmentSignalPolicy, items, population int) float64 { + bits := math.Log2(float64(population) / 2) + total := 0.0 + for item := range items { + capBits := float64(policy.DuplicateIntegerCapBits) + if item%4 == 1 { + capBits = float64(policy.DuplicateSequenceCapBits) + } + total += math.Min(capBits, bits) + } + return math.Floor(total) +} + +// The demo thresholds are tuned against ten thousand rivals, so a copied pair +// is only flagged once enough attempts exist for its shared values to be rare. +// This test calculates how many answers per family that takes, so the figure in +// the documentation is not an estimate; to try the feature on a small stand, +// publish a policy with lower thresholds instead of changing the demo values. +func TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged(t *testing.T) { + policy := domain.DemoAssessmentSignalPolicy() + needed := func(items int, threshold int32) int { + for population := 2; population <= 1<<20; population++ { + if copiedPairEvidence(policy, items, population) >= float64(threshold) { + return population + } + } + return -1 + } + for _, test := range []struct { + items int + wantAttention, wantReview int + }{ + {items: 13, wantAttention: 26, wantReview: 61}, + {items: 23, wantAttention: 9, wantReview: 14}, + } { + attention := needed(test.items, policy.DuplicateAttentionBits) + review := needed(test.items, policy.DuplicateReviewBits) + t.Logf("%d items: a copied pair reaches attention from %d answers per family and review from %d", test.items, attention, review) + if attention != test.wantAttention || review != test.wantReview { + t.Errorf("%d items: attention at %d and review at %d answers per family, want %d and %d", test.items, attention, review, test.wantAttention, test.wantReview) + } + } +} diff --git a/backend/internal/usecase/identity/keyring.go b/backend/internal/usecase/identity/keyring.go index 24f70a8..5cccbab 100644 --- a/backend/internal/usecase/identity/keyring.go +++ b/backend/internal/usecase/identity/keyring.go @@ -4,9 +4,12 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/base64" + "encoding/binary" "encoding/hex" "fmt" + "github.com/google/uuid" + "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) @@ -24,6 +27,10 @@ const ( labelTokenBucket = "lincodex/identity/verification-token-bucket/v1" labelSessionCSRF = "lincodex/identity/session-csrf/v1" labelCandidateView = "lincodex/identity/candidate-view/v1" + + labelAnswerFingerprint = "lincodex/assessment/answer-fingerprint/v1" + labelSignalSession = "lincodex/assessment/signal-session/v1" + labelSignalNetwork = "lincodex/assessment/signal-network/v1" ) // Keyring computes the keyed digests of the anonymous identity operations: @@ -39,6 +46,9 @@ type Keyring struct { tokenKey []byte sessionCSRFKey []byte candidateViewKey []byte + answerKey []byte + signalSessionKey []byte + signalNetworkKey []byte } // NewKeyring derives the purpose keys from secret. @@ -54,6 +64,9 @@ func NewKeyring(secret []byte) (*Keyring, error) { tokenKey: derive(secret, labelTokenBucket), sessionCSRFKey: derive(secret, labelSessionCSRF), candidateViewKey: derive(secret, labelCandidateView), + answerKey: derive(secret, labelAnswerFingerprint), + signalSessionKey: derive(secret, labelSignalSession), + signalNetworkKey: derive(secret, labelSignalNetwork), }, nil } @@ -143,3 +156,39 @@ func (keyring *Keyring) VerifySessionCSRF(token domain.SecretToken, supplied str } return hmac.Equal([]byte(keyring.SessionCSRF(token)), []byte(supplied)) } + +// AssessmentDigestKeyVersion is the key generation of the assessment +// fingerprints and digests. It is stored next to each of them; a rotation adds +// a new generation instead of silently changing the old values. +func (keyring *Keyring) AssessmentDigestKeyVersion() int16 { return 1 } + +// AssessmentAnswerFingerprint is the keyed digest of a normalized answer to a +// family version. It is the same for every candidate and every seed, which +// lets stored fingerprints be compared without the answer text. +func (keyring *Keyring) AssessmentAnswerFingerprint(familyID uuid.UUID, familyVersion int32, canonicalAnswer []byte) domain.AssessmentDigest { + mac := hmac.New(sha256.New, keyring.answerKey) + mac.Write(familyID[:]) + mac.Write(binary.BigEndian.AppendUint32(nil, uint32(familyVersion))) //nolint:gosec // A family version is a positive int32. + mac.Write(canonicalAnswer) + return domain.AssessmentDigest(mac.Sum(nil)) +} + +// AssessmentSessionDigest identifies a login session inside one attempt. The +// digest changes with the attempt, so it cannot link attempts or reveal the +// session identifier. +func (keyring *Keyring) AssessmentSessionDigest(attemptID, sessionID uuid.UUID) domain.AssessmentDigest { + mac := hmac.New(sha256.New, keyring.signalSessionKey) + mac.Write(attemptID[:]) + mac.Write(sessionID[:]) + return domain.AssessmentDigest(mac.Sum(nil)) +} + +// AssessmentNetworkDigest identifies a client network inside one attempt from +// its limiter key. The address itself is never stored, and the digest cannot +// link attempts. +func (keyring *Keyring) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey string) domain.AssessmentDigest { + mac := hmac.New(sha256.New, keyring.signalNetworkKey) + mac.Write(attemptID[:]) + mac.Write([]byte(clientKey)) + return domain.AssessmentDigest(mac.Sum(nil)) +} diff --git a/backend/internal/usecase/identity/keyring_test.go b/backend/internal/usecase/identity/keyring_test.go index e35da5a..3ce00da 100644 --- a/backend/internal/usecase/identity/keyring_test.go +++ b/backend/internal/usecase/identity/keyring_test.go @@ -2,9 +2,12 @@ package identity import ( "bytes" + "crypto/sha256" "testing" "github.com/google/uuid" + + "lincodex/backend/internal/domain" ) func TestCandidateViewPseudonymKeyIsPurposeDerived(t *testing.T) { @@ -54,3 +57,69 @@ func TestCandidateViewPseudonymKeyRequiresValidKeyring(t *testing.T) { t.Fatal("CandidateViewPseudonymKey() accepted a nil keyring") } } + +func TestAssessmentAnswerFingerprintIsKeyedDeterministicAndScoped(t *testing.T) { + keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + other, err := NewKeyring(bytes.Repeat([]byte{2}, MinKeySecretBytes)) + if err != nil { + t.Fatalf("NewKeyring(other) error = %v", err) + } + family, otherFamily := uuid.New(), uuid.New() + answer := []byte(`{"format":"number","number":42}`) + first := keyring.AssessmentAnswerFingerprint(family, 1, answer) + if first.IsZero() || first != keyring.AssessmentAnswerFingerprint(family, 1, answer) { + t.Fatal("the same family version and answer must give the same non-zero fingerprint") + } + for name, different := range map[string]domain.AssessmentDigest{ + "another answer": keyring.AssessmentAnswerFingerprint(family, 1, []byte(`{"format":"number","number":43}`)), + "another family": keyring.AssessmentAnswerFingerprint(otherFamily, 1, answer), + "another family version": keyring.AssessmentAnswerFingerprint(family, 2, answer), + "another secret": other.AssessmentAnswerFingerprint(family, 1, answer), + } { + if different == first { + t.Errorf("%s gave the same fingerprint", name) + } + } + plain := sha256.Sum256(append(append(family[:], 0, 0, 0, 1), answer...)) + if first == domain.AssessmentDigest(plain) { + t.Fatal("the fingerprint is a plain hash and can be checked without the server secret") + } + if keyring.AssessmentDigestKeyVersion() < 1 { + t.Fatal("the digest key version must be positive") + } +} + +func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) { + keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + attempt, otherAttempt, session, otherSession := uuid.New(), uuid.New(), uuid.New(), uuid.New() + sessionDigest := keyring.AssessmentSessionDigest(attempt, session) + if sessionDigest != keyring.AssessmentSessionDigest(attempt, session) { + t.Fatal("the session digest is not deterministic") + } + if sessionDigest == keyring.AssessmentSessionDigest(otherAttempt, session) { + t.Fatal("one session has the same digest in two attempts, so attempts could be linked") + } + if sessionDigest == keyring.AssessmentSessionDigest(attempt, otherSession) { + t.Fatal("two sessions of one attempt have the same digest") + } + networkDigest := keyring.AssessmentNetworkDigest(attempt, "198.51.100.0") + if networkDigest != keyring.AssessmentNetworkDigest(attempt, "198.51.100.0") { + t.Fatal("the network digest is not deterministic") + } + if networkDigest == keyring.AssessmentNetworkDigest(otherAttempt, "198.51.100.0") { + t.Fatal("one network has the same digest in two attempts, so attempts could be linked") + } + if networkDigest == keyring.AssessmentNetworkDigest(attempt, "198.51.100.1") { + t.Fatal("two client networks have the same digest") + } + // Each purpose has its own key: the same bytes under another purpose differ. + if sessionDigest == keyring.AssessmentNetworkDigest(attempt, string(session[:])) { + t.Fatal("session and network digests share a key") + } +} diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 440cf16..ff095fb 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -174,7 +174,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini ### Scheduled jobs -Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs). +Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. One product handler is registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band). The tests also use a test-only kind. The first planned deadline kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs). Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `:`. @@ -430,7 +430,7 @@ Typed policy, `domain.ProductPolicy`: every value is a named field whose type ca The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization. -Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility. +Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility. The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage. @@ -608,6 +608,21 @@ Implemented as storage and a loader, not as a candidate-facing feature: migratio - Demo bundle. `backend/testdata/assessment/backend_demo_bundle.json` holds four original practice problems for the category `backend`. They are an AI-generated draft (author `ai:claude-draft`) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval. - Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, selection of tasks for an attempt, the storage of attempts and answers, grading, an HTTP or admin interface, authenticated reviewer and operator identities, and a wiring of the loader in bootstrap. +### Assessment signals and the review band + +Implemented as server-side signals of a real attempt (root or corrective), a review band computed by a scheduled job under the policy version pinned to the attempt, and an operator-only reader. The band is a hint for a manual check by a person. It does not change the result, the category, or a quota; no candidate or employer operation carries it, and the public contract has no field for it (a test walks every operation, request, response, and header to check this). Until staff roles exist, the only reader is the local command `assessment-review`, which records each read ([DEPLOY.md](DEPLOY.md#assessment-review-band)). Browser signals are described separately by the signal receipt contract; this section covers what the server observes itself. + +Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql`, queries `backend/db/queries/assessment_signal_review.sql`, the policy section and band rules in `backend/internal/domain/` (`assessment_signal_policy.go`, `assessment_signal_review.go`), the observer, the review job, and `ReviewOperator` in `backend/internal/usecase/assessment/signal_review.go`, the repository in `backend/internal/adapter/secondary/postgres/assessment_signal_review.go`, and the command in `backend/cmd/assessment-review/`. + +- Facts. `assessment_answer_observations` has one row per accepted answer: the family, the seed, the answer format, the server time from the last activity of the attempt (the previous answer or the start of the current work session) to the accepted answer, whether that time starts at the previous answer, and a keyed answer fingerprint. `assessment_attempt_origin_marks` has a row when the login session or the client network of an accepted answer or signal batch differs from the last row (digests of both), so the list stays short however many requests arrive. The browser events of the signal receipt contract only add totals (focus loss time, clipboard events, fullscreen exits). Rows are append-only, removed only by the cascade from the attempt or the account, and written in the same transaction as the answer or the batch, which already holds the attempt row lock. Two maintained counters, `assessment_answer_fingerprint_holders` (answers per family version, key generation, and fingerprint) and `assessment_answer_family_totals` (answers per family version and key generation), are increased by a trigger in the transaction of each observation insert; they only grow, so an answer removed with an account stays counted, and they are derived caches without foreign keys. A transaction touches one row of each, always in the same order. +- No answer text, keyed digests only. The new tables store no answer text; the raw answer already exists in `assessment_attempt_items` and is untouched. Fingerprints and digests are HMAC-SHA-256 values under purpose keys derived from `IDENTITY_KEY_SECRET` with their own domain labels (`Keyring.AssessmentAnswerFingerprint`, `AssessmentSessionDigest`, `AssessmentNetworkDigest`); no new secret exists. Each stored value carries a `key_version` (now 1) and only values of one generation are compared, so a future key rotation is an explicit step. The answer fingerprint covers the family version and the canonical answer and is the same for every candidate and seed. The session and network digests also bind the attempt, so they cannot be linked between attempts. The HTTP adapter passes the session ID and the limiter key of the client address (an IPv6 address reduced to its /64) to the usecase, which hashes them; no address, session ID, token, or answer text is logged or stored. The digests live as long as the attempt (the retention period is an open question). Changing `IDENTITY_KEY_SECRET` makes old and new fingerprints incomparable. +- Server signals. Response time: an answer faster than the per-format floor of the policy is fast, and within one format an answer more than the policy ratio below the median of the attempt is an anomalous deviation (only the fast side; a slow answer is not suspicious, and a format needs enough answers of its own). One answer counts once: an answer under its floor is fast and not also a deviation. The first item of a work session is measured from the session start, which only bounds when the item was shown, so it is excluded from both. Parallel sessions: requests that return to an earlier login session after another session was used (a single move to a new session is not counted). Networks: the number of distinct client networks beyond the first, so a move to another network and back counts once. Parallel sessions and extra networks are weak and correlated (a phone and a laptop produce both), so they form one group: alone it reaches attention at most, and review only together with a strong signal (fast, deviating, or duplicate answers) at attention or above. Client time only complements server time: it is never the source of a response time, and client signals can raise a normal band to attention but never to review. +- Identical answers of different candidates, compared pairwise. For one attempt the comparison looks at every other attempt separately: matched answers are equal fingerprints of the same family version and key generation, given by another candidate to a different seed variant, so an expected agreement on one seed is not a signal and a candidate never matches their own attempt. A matched answer carries -log2 of the share of answers that hold that fingerprint among the answers of the family version and key generation, read from the maintained counters (so a rotation does not skew the share), between zero and the cap of its format (`duplicate_integer_cap_bits`, `duplicate_sequence_cap_bits`). A popular value, such as the correct answer of a variant, therefore carries little, and so does a population of a few attempts. The bits of one pair add up, the strongest pair decides, and `duplicate_bits_attention` and `duplicate_bits_review` are thresholds on that sum. The list of pairs is bounded and never leaves the usecase; nothing identifies the other attempt or candidate in any output, and the operator output holds counts only. +- Why the demo thresholds are 48 and 64 bits, and what the figure means. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction, `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds in `assessment.signals` (the integration tests do this with 4 and 6 bits); the demo policy is not changed for that. +- Policy. The optional section `assessment.signals` of a schema 2 policy document holds every threshold (`domain.AssessmentSignalPolicy`); a version without it computes no band. `DemoProductPolicyV3` is `DemoProductPolicyV2` plus `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1` and `DemoProductPolicyV2` and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version in `assessment_attempts.product_policy_version_id`, so a policy published later does not change an attempt in progress or a stored review; `assessment_attempt_reviews.policy_version_id` records the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level. +- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that. +- Limits. Browser signals can be forged or suppressed, so they are a hint only. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided. + ## Matching and explanations Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 13a68f2..8f55c0a 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -187,7 +187,7 @@ To inspect an `invalid_record` while the topic retains it, read exactly that rec ### Scheduled jobs -The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: no product job kind is registered, so the backend logs `no scheduled job kind is registered` at startup and runs no worker; the settings below are still validated. With a registered kind, the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled. +The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: one product kind is registered, `assessment.signal_review` (see [Assessment review band](#assessment-review-band)), so the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set; the settings below are validated in any case. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled. | Variable | Default | Meaning | | --- | --- | --- | @@ -310,6 +310,23 @@ Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate - The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed. - Golden files in `testdata/` make every copy change visible in review. After an intended change, run `go test ./internal/usecase/notification/mailtemplate -update` from `backend/` and review the diff. +## Assessment review band + +The server computes a manual-review band (`normal`, `attention`, `review`) for real assessment attempts from the server signals and the policy version pinned to the attempt (see [ARCHITECTURE.md](ARCHITECTURE.md#assessment-signals-and-the-review-band)). The band is a hint for a person who checks an attempt by hand. It changes no result, category, or quota, and no HTTP endpoint serves it. Until staff roles exist, an operator reads it with a local command: + +```sh +make -C backend assessment-review ARGS='inspect --attempt --actor operator:' +``` + +- The band is computed by the scheduled job kind `assessment.signal_review`, never in a candidate's request. The jobs are inserted into `scheduled_jobs` with the first answer (due one minute after the deadline of the attempt) and with finalization (due at once). The worker must run (`JOBS_ENABLED=true`, [Scheduled jobs](#scheduled-jobs)); with the worker off the reviews wait with their jobs and no result is affected. A failed job is retried with the worker's backoff; a dead job (see [Dead jobs](#dead-jobs)) leaves the attempt without a refreshed review and does not touch its result. +- The command needs `DATABASE_URL` and reads nothing else from the environment or a dotenv file; the local database credential is its operator boundary. `make -C backend assessment-review-build` builds `backend/bin/assessment-review`. +- It prints the attempt ID, the band, the reason codes, the policy version, the evaluation and update times, and the counts behind the band. It prints no answer, address, session, candidate, or contact data, and it never names another candidate of a duplicate match. +- Every read is recorded in `assessment_review_reads` (attempt ID, actor handle, found or missing, database time) in the same transaction as the read, also when the attempt has no review. The table refuses UPDATE, DELETE, and TRUNCATE. The actor is an audit handle, not authentication: any holder of the database credential can type any handle. Rolling migration 33 back is refused while the audit holds a row; export or resolve it first. +- A band can be missing for a real reason: the policy version of the attempt has no `assessment.signals` section, the review job has not run yet, or the attempt has neither ended nor reached its deadline. +- A review is updated in place when a later attempt matches one of its answers; the policy version and the first evaluation time stay. +- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`). +- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet. + ## Separate ML Compose project ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty. diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index e73b9cf..578e397 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -439,6 +439,26 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas `TestPostgresMigrations` rolls migration 00011 back with the others and checks that its two tables and five functions disappear while the policy table stays. The suite proves the storage and loader rules only: it does not validate the content of the demo bundle, task difficulty, or any grade, it does not prove the serialization of concurrent publications beyond the held-lock case, and it does not cover a candidate-facing flow, because none exists yet. Integration tests need Docker. +## Assessment signal and review band tests + +`backend/internal/domain/assessment_signal_policy_test.go` and `assessment_signal_review_test.go` check without a database: the demo signal section is valid and round-trips through the schema 2 document, a signal section alone is a valid extension and never acquires defaults, schema 1 rejects the key, out-of-range and inconsistent thresholds are refused, response times follow the per-format floors and the median ratio only on the fast side within one format and leave out the first item of a session, origin marks count alternations and distinct networks in time order (a return to an earlier network is not a new one), the band follows the policy, weak signals (parallel sessions and extra networks, one correlated group) stop at attention unless a strong signal is raised, an answer counts once as fast or as a deviation, client signals only raise a band to attention, and the operator handle must be `operator:`. `backend/internal/usecase/identity/keyring_test.go` checks the new keyring methods: the answer fingerprint is deterministic, keyed, and scoped to the family version; session and network digests differ across attempts (no linking), across sessions, and across client keys, and use separate purpose keys. + +`backend/internal/usecase/assessment/signal_review_test.go` checks the observer and the review job with fake ports: an accepted answer stores the server time, whether it is measured from the previous answer, the key version, and the keyed fingerprint only, with no answer text, address, or session ID in the stored values or in the error text; origin marks are written only when the session or network changes; the first answer schedules the deadline job (one minute after the deadline) and finalization the ended job; training attempts and requests without a session store nothing; a policy version without a signal section makes no review; the job rejects a broken payload, ignores a missing attempt, locks the reviews of a pair in ascending attempt order before it reads any fact and writes them under their own pinned policies, and refreshes only ended attempts at the attention level, bounded. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each demo family, builds the distribution of shared values with their bits, and computes the probability that one honest pair reaches each demo threshold on a 23-item attempt; times 10,000 rivals it gives about 4e-5 (attention) and 3e-9 (review), against the targets 1e-3 and 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs for the demo thresholds to flag it (26 for attention and 61 for review at 13 items, 9 and 14 at 23 items). The FP model uses the distribution of reference answers only, not wrong answers or correlated mistakes. The targets are test constants chosen here, not a product decision, and the measurement covers four AI-drafted families. + +`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` walks every path of the public contract through its references and refuses any property, schema name, or enum that would carry the band, its reasons, fingerprints, or origin digests, and checks that the signal receipt still has exactly `status`, `accepted_events`, and `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` checks argument validation before any environment read, the printed fields, and sanitized errors. The bootstrap test checks that the review job kind is registered. + +`TestAssessmentSignalReviewOverHTTP` in `backend/integration_test/assessment_signal_review_http_test.go` runs the real router, PostgreSQL, and the scheduled job worker: + +- A candidate answers every item within milliseconds from two login sessions and three network addresses and sends paste events from the second session. Before the worker runs no review exists and the review jobs are pending, so nothing was computed in a candidate's transaction. Then the attempt has the band `attention` with the reasons fast answers, parallel sessions, extra networks, and client signals, and its result is `confirmed`, equal in outcome, score, limitations, and mode to the result of an equally correct attempt with band `normal`; no assessment table other than the review table has a band column. +- A policy version with other thresholds is published while attempts are in progress and the category is opened under it. The attempts started earlier keep the first version, the attempt created later is pinned to the new version and stays `normal` for the same behavior, and its facts are still stored. +- Two candidates with different seeds copy the same wrong answers: the first attempt has no duplicate flag until the second candidate has answered and ended, and then both have the band `review` with the reason duplicate answers. A third copying attempt is abandoned: while it runs it is not flagged, and after it ends its job at the deadline (the worker clock is moved past it) flags it. Honest attempts with correct answers are not flagged even when a low-entropy answer coincides, and an attempt with one session and one network has exactly one origin mark. +- Candidate reads of the attempt, the result, and the availability contain no band, reasons, fingerprints, or signal names. The operator command prints the band and its audit rows are written for a found and a missing attempt; an actor without the `operator:` prefix is refused. Facts, reviews, and audit rows refuse UPDATE and DELETE, and the audit refuses TRUNCATE. +- The logs and the text of the new tables and of `scheduled_jobs` contain no network address, answer value, session token, or CSRF token. + +`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` creates 30 honest candidates with different seeds who answer each item correctly or not at random (a fixed generator) and two who copy the same answers: no honest attempt is flagged as a duplicate and both copied attempts are. The population is small, so the test uses thresholds of 32 and 44 bits instead of the demo ones. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` ends four copied attempts at the same moment among eight honest ones and runs their jobs on four workers at once: no job fails or is retried and every copied attempt is flagged. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` holds the review lock of an attempt in one transaction and checks that the review job waits, writes nothing, and computes the review from the committed facts once the lock is released; this is the ordering that prevents a stale evaluation from overwriting a newer review. The concurrent test was run ten times in a row (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` checks that the rollback of migration 33 is refused while the audit holds a row (the tables and the row stay, TRUNCATE is refused) and succeeds with an empty audit. + +The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation. + ## Future software validation Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index 7f44e56..acb8880 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -174,7 +174,7 @@ Offsets и партиции. Каждый обработчик - один уча ### Задания по сроку -Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку). +Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. В `jobHandlers()` (`backend/internal/bootstrap/jobs.go`) зарегистрирован один продуктовый обработчик: `assessment.signal_review`, который считает [полосу проверки оценки](#серверные-сигналы-оценки-и-полоса-проверки). Тесты используют и вид задания, который есть только в тестах. Первый запланированный вид по сроку - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку). Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `:`. @@ -430,7 +430,7 @@ Offsets и партиции. Каждый обработчик - один уча Решение для учета попыток MVP: `MaxAttemptsPerWindow` считает корневые попытки кандидата по всем специализациям в скользящем окне `AttemptWindow`. Корректирующая попытка использует место своего корня, учебная его не расходует. Таймеры пересдачи и повышения остаются независимыми по специализациям. -Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются. +Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training`, `assessment.signals` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются. Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу. @@ -608,6 +608,21 @@ contact_grant относится к паре кандидат-компания - Демонстрационный пакет. `backend/testdata/assessment/backend_demo_bundle.json` содержит четыре оригинальные практические задачи категории `backend`. Это черновик, созданный ИИ (автор `ai:claude-draft`), с рецензией `pending` и без рецензента, поэтому загрузчик импортирует их черновиками, публикация отклоняется, а категория остается закрытой. Условия, решения, рубрики и сложность никто из людей не проверял; пакет не заявляет ни валидности, ни калибровки. Настоящая рецензия порождает новую версию семейств с одобрением. - Не реализовано: авторство и рецензирование настоящего банка, blueprint по специализации и уровню, выбор задач для попытки, хранение попыток и ответов, проверка ответов, HTTP- или административный интерфейс, аутентифицированные личности рецензентов и операторов и подключение загрузчика в bootstrap. +### Серверные сигналы оценки и полоса проверки + +Реализовано как серверные сигналы реальной попытки (root или corrective), полоса проверки, которую считает задание по сроку под версией политики, закрепленной за попыткой, и чтение только оператором. Полоса - подсказка для ручной проверки человеком. Она не меняет результат, категорию или квоту; ни одна операция кандидата или работодателя ее не содержит, и в публичном контракте для нее нет поля (тест обходит каждую операцию, запрос, ответ и заголовок). Пока служебных ролей нет, единственный читатель - локальная команда `assessment-review`, которая записывает каждое чтение ([DEPLOY.md](DEPLOY.md#полоса-проверки-оценки)). Браузерные сигналы описывает контракт квитанции сигналов; этот раздел - о том, что сервер наблюдает сам. + +Код: миграция `backend/db/migrations/00033_create_assessment_signal_review.sql`, запросы `backend/db/queries/assessment_signal_review.sql`, раздел политики и правила полосы в `backend/internal/domain/` (`assessment_signal_policy.go`, `assessment_signal_review.go`), наблюдатель, задание проверки и `ReviewOperator` в `backend/internal/usecase/assessment/signal_review.go`, репозиторий в `backend/internal/adapter/secondary/postgres/assessment_signal_review.go` и команда в `backend/cmd/assessment-review/`. + +- Факты. В `assessment_answer_observations` одна строка на принятый ответ: семейство, seed, формат ответа, серверное время от последней активности попытки (предыдущий ответ или начало текущей рабочей сессии) до принятого ответа, считается ли оно от предыдущего ответа, и ключевой отпечаток ответа. В `assessment_attempt_origin_marks` строка появляется, когда сессия входа или сеть клиента принятого ответа или пакета сигналов отличается от последней строки (дайджесты обоих), поэтому список короткий при любом числе запросов. Браузерные события из контракта квитанции добавляют только суммы (время потери фокуса, события буфера обмена, выходы из полноэкранного режима). Строки только добавляются, удаляются лишь каскадом от попытки или аккаунта и пишутся в той же транзакции, что ответ или пакет, которая уже держит блокировку строки попытки. Два поддерживаемых счетчика, `assessment_answer_fingerprint_holders` (ответов на версию семейства, поколение ключа и отпечаток) и `assessment_answer_family_totals` (ответов на версию семейства и поколение ключа), увеличивает триггер в транзакции каждой вставки наблюдения; они только растут, поэтому ответ, удаленный вместе с аккаунтом, остается в счете, а сами они - производный кэш без внешних ключей. Транзакция трогает по одной строке каждого, всегда в одном порядке. +- Без текста ответа, только ключевые дайджесты. Новые таблицы не хранят текст ответа; сырой ответ уже есть в `assessment_attempt_items` и не затрагивается. Отпечатки и дайджесты - HMAC-SHA-256 под ключами назначения, выведенными из `IDENTITY_KEY_SECRET` со своими метками домена (`Keyring.AssessmentAnswerFingerprint`, `AssessmentSessionDigest`, `AssessmentNetworkDigest`); нового секрета нет. Каждое сохраненное значение несет `key_version` (сейчас 1), сравниваются только значения одного поколения, поэтому будущая ротация ключа - явный шаг. Отпечаток ответа покрывает версию семейства и канонический ответ и одинаков для любого кандидата и seed. Дайджесты сессии и сети дополнительно привязаны к попытке, поэтому их нельзя связать между попытками. HTTP-адаптер передает usecase идентификатор сессии и ключ лимитера адреса клиента (IPv6 сокращается до /64), а usecase их хеширует; адрес, идентификатор сессии, токен и текст ответа не пишутся в журнал и не хранятся. Дайджесты живут столько же, сколько попытка (срок хранения - открытый вопрос). После смены `IDENTITY_KEY_SECRET` старые и новые отпечатки несравнимы. +- Серверные сигналы. Время ответа: ответ быстрее порога формата из политики считается быстрым, а в пределах одного формата ответ, который меньше медианы попытки более чем в заданное политикой число раз, считается аномальным отклонением (только быстрая сторона: медленный ответ не подозрителен, и формату нужно достаточно собственных ответов). Один ответ считается один раз: ответ ниже порога - быстрый, а не еще и отклонение. Первый элемент рабочей сессии отсчитывается от начала сессии, что лишь ограничивает время показа элемента, поэтому он исключен из обоих счетчиков. Параллельные сессии: запросы, которые возвращаются к прежней сессии входа после использования другой (одиночный переход на новую сессию не считается). Сети: число различных сетей клиента сверх первой, так что переход в другую сеть и обратно считается один раз. Параллельные сессии и лишние сети слабые и коррелированы (телефон и ноутбук дают оба), поэтому они образуют одну группу: сама по себе она дает не выше «внимание», а «проверить» только вместе с сильным сигналом (быстрые, отклоняющиеся или одинаковые ответы) уровня «внимание» и выше. Клиентское время только дополняет серверное: оно никогда не источник времени ответа, а клиентские сигналы могут поднять нормальную полосу до «внимание», но не до «проверить». +- Одинаковые ответы разных кандидатов, сравнение попарное. Для одной попытки сравнение смотрит на каждую другую попытку отдельно: совпавший ответ - это равные отпечатки одной версии семейства и поколения ключа, данные другим кандидатом на другой вариант seed, поэтому ожидаемое совпадение при одном seed не сигнал, а кандидат не совпадает со своей же попыткой. Совпавший ответ несет -log2 доли ответов с этим отпечатком среди ответов версии семейства и поколения ключа, она читается из поддерживаемых счетчиков (поэтому ротация ключа не искажает долю), от нуля до предела его формата (`duplicate_integer_cap_bits`, `duplicate_sequence_cap_bits`). Поэтому популярное значение, например верный ответ варианта, несет мало, как и совокупность из нескольких попыток. Биты одной пары складываются, решает самая сильная пара, а `duplicate_bits_attention` и `duplicate_bits_review` - пороги на эту сумму. Список пар ограничен и не покидает usecase; ничто в выводе не называет другую попытку или кандидата, а вывод оператора содержит только числа. +- Почему демо-пороги равны 48 и 64 битам и что означает эта цифра. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого из четырех демо-семейств (у трех целочисленных 36-47 различных ответов, у порядка зависимостей около 2250), строит распределение общих значений и их битов и считает вероятность того, что одна пара честных кандидатов, верно ответивших на попытку из 23 заданий, достигнет каждого порога. Умноженная на 10 000 соперников (граница объединения), доля ложных пометок на попытку - около 4e-5 для «внимание» и 3e-9 для «проверить» при целях теста 1e-3 и 1e-8. Модель использует распределение эталонных ответов: она не моделирует распределение неверных ответов и коррелированные ошибки (одинаковая типичная ошибка многих кандидатов, общий учебник), из-за которых честные совпадения могут быть вероятнее расчетных. Это демо-значения до калибровки на настоящем банке, измеренные на четырех семействах, написанных ИИ. В обратную сторону `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили, когда пара копирует все ответы и больше никто эти значения не держит: для попытки из 13 заданий «внимание» от 26 ответов на семейство и «проверить» от 61; для 23 заданий от 9 и от 14. Стенд с меньшим числом попыток по замыслу ничего не помечает. Чтобы попробовать функцию на малом стенде, опубликуйте версию политики с меньшими порогами в `assessment.signals` (интеграционные тесты делают так с 4 и 6 битами); демо-политика для этого не меняется. +- Политика. Необязательный раздел `assessment.signals` документа схемы 2 хранит все пороги (`domain.AssessmentSignalPolicy`); версия без него не считает полосу. `DemoProductPolicyV3` - это `DemoProductPolicyV2` плюс `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1`, `DemoProductPolicyV2` и стартовый seed не изменились, сохраненная версия не переписывается. Полоса использует пороги версии продуктовой политики из `assessment_attempts.product_policy_version_id`, поэтому политика, опубликованная позже, не меняет попытку в процессе и сохраненную проверку; `assessment_attempt_reviews.policy_version_id` фиксирует версию, а триггер запрещает ее менять. Попытка из пары пересчитывается под своей закрепленной версией; пары выбираются по уровню «внимание» считающей попытки, поэтому между версиями с разными уровнями пара может быть пропущена на стороне с меньшим уровнем. +- Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел. +- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено. + ## Подбор и объяснение До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index a5883d1..694960c 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -189,7 +189,7 @@ Dead letter - запись, от которой обработчик отказ ### Задания по сроку -Backend запускает worker заданий по сроку как горутину процесса backend рядом с HTTP-серверами, relay и обработчиками событий. Он выполняет задания, которые usecase запланировали в своих транзакциях, когда наступает их срок; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку). Текущее состояние: продуктовый вид задания не зарегистрирован, поэтому backend при старте пишет в журнал `no scheduled job kind is registered` и не запускает worker; настройки ниже все равно проверяются. С зарегистрированным видом worker работает, когда `JOBS_ENABLED` равно true и задан `DATABASE_URL`. Compose не передает ни одну из этих настроек, поэтому стенд использует значения по умолчанию; чтобы изменить значение, добавьте его в `environment` backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает запуск, даже когда worker выключен. +Backend запускает worker заданий по сроку как горутину процесса backend рядом с HTTP-серверами, relay и обработчиками событий. Он выполняет задания, которые usecase запланировали в своих транзакциях, когда наступает их срок; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку). Текущее состояние: зарегистрирован один продуктовый вид, `assessment.signal_review` (см. [Полоса проверки оценки](#полоса-проверки-оценки)), поэтому worker работает, когда `JOBS_ENABLED` равно true и задан `DATABASE_URL`; настройки ниже проверяются в любом случае. Compose не передает ни одну из этих настроек, поэтому стенд использует значения по умолчанию; чтобы изменить значение, добавьте его в `environment` backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает запуск, даже когда worker выключен. | Переменная | По умолчанию | Значение | | --- | --- | --- | @@ -312,6 +312,23 @@ Compose передает эти переменные из корневого `.e - Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются. - Golden файлы в `testdata/` делают каждое изменение текста видимым на ревью. После намеренного изменения выполните `go test ./internal/usecase/notification/mailtemplate -update` из `backend/` и проверьте diff. +## Полоса проверки оценки + +Сервер считает для реальных попыток оценки полосу ручной проверки (`normal`, `attention`, `review`) по серверным сигналам и версии политики, закрепленной за попыткой (см. [ARCHITECTURE.md](ARCHITECTURE.md#серверные-сигналы-оценки-и-полоса-проверки)). Полоса - подсказка для человека, который проверяет попытку вручную. Она не меняет результат, категорию или квоту, и ни один HTTP endpoint ее не отдает. Пока служебных ролей нет, оператор читает ее локальной командой: + +```sh +make -C backend assessment-review ARGS='inspect --attempt --actor operator:' +``` + +- Полосу считает задание по сроку вида `assessment.signal_review`, никогда не запрос кандидата. Задания вставляются в `scheduled_jobs` с первым ответом (срок - через минуту после дедлайна попытки) и с завершением (срок - сразу). Worker должен работать (`JOBS_ENABLED=true`, [Задания по сроку](#задания-по-сроку)); при выключенном worker проверки ждут вместе со своими заданиями, и ни один результат не затрагивается. Упавшее задание повторяется с задержкой worker; мертвое задание (см. [Dead задания](#dead-задания)) оставляет попытку без обновленной проверки и не трогает ее результат. +- Команде нужен `DATABASE_URL`, больше она ничего не читает из окружения и dotenv-файла; границей оператора служит локальный доступ к базе. `make -C backend assessment-review-build` собирает `backend/bin/assessment-review`. +- Она печатает идентификатор попытки, полосу, коды причин, версию политики, время вычисления и обновления и числа, из которых составлена полоса. Она не печатает ответы, адреса, сессии, данные кандидата или контакты и никогда не называет другого кандидата при совпадении ответов. +- Каждое чтение записывается в `assessment_review_reads` (идентификатор попытки, имя оператора, найдено или нет, время базы) в той же транзакции, что и чтение, в том числе когда у попытки нет проверки. Таблица отклоняет UPDATE, DELETE и TRUNCATE. Имя оператора - метка для аудита, а не аутентификация: любой, у кого есть доступ к базе, может ввести любое имя. Откат миграции 33 отклоняется, пока в аудите есть строка; сначала экспортируйте или разберите ее. +- Полосы может не быть по реальной причине: в версии политики попытки нет раздела `assessment.signals`, задание проверки еще не выполнено, либо попытка еще не завершилась и не достигла дедлайна. +- Проверка обновляется на месте, когда более поздняя попытка совпала с одним из ее ответов; версия политики и время первого вычисления остаются. +- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `assessment.signals` через публикатор политик. `DemoProductPolicyV3` - демо-пример, он публикуется только явно (так делает изолированная браузерная фикстура); стартовый seed публикует только версию 1. Попытки, которые уже начались, сохраняют версию, с которой начались. Демо-пороги дубликатов рассчитаны на совокупность: скопированная пара помечается лишь примерно от 26 ответов на семейство («внимание») и 61 («проверить») при 13 заданиях или от 9 и 14 при 23. Чтобы попробовать функцию на меньшем стенде, опубликуйте версию политики с меньшими `duplicate_bits_attention` и `duplicate_bits_review` (интеграционные тесты используют 4 и 6); демо-политику не редактируйте. Проверка - оценка на момент, задание на дедлайне запускает ее снова. Задание пишет в журнал одну строку на запуск с числом проверок и длительностью (`assessment review job finished`). +- Строки хранят числа, длительности и ключевые дайджесты (HMAC-SHA-256 под ключами, выведенными из `IDENTITY_KEY_SECRET`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен. + ## Отдельный ML Compose ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 09e8c3e..9d97d98 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -439,6 +439,26 @@ Unit-тесты (`make -C backend test`) проверяют правила жу `TestPostgresMigrations` откатывает миграцию 00011 вместе с остальными и проверяет, что две ее таблицы и пять функций исчезают, а таблица политик остается. Набор доказывает только правила хранилища и загрузчика: он не проверяет содержимое демонстрационного пакета, сложность задач и какие-либо грейды, не доказывает сериализацию одновременных публикаций сверх случая с удерживаемой блокировкой и не покрывает сценарий кандидата, потому что его еще нет. Интеграционным тестам нужен Docker. +## Тесты сигналов оценки и полосы проверки + +`backend/internal/domain/assessment_signal_policy_test.go` и `assessment_signal_review_test.go` проверяют без базы: демо-раздел сигналов корректен и проходит круг через документ схемы 2, один раздел сигналов - допустимое расширение и никогда не получает значений по умолчанию, схема 1 отклоняет ключ, значения вне диапазона и несогласованные пороги отвергаются, время ответа следует порогам формата и отношению к медиане только на быстрой стороне в пределах одного формата и не учитывает первый элемент сессии, метки происхождения считают чередования и различные сети по времени (возврат в прежнюю сеть не новая сеть), полоса следует политике, слабые сигналы (параллельные сессии и лишние сети - одна коррелированная группа) останавливаются на «внимание», пока нет сильного сигнала, ответ считается один раз как быстрый или как отклонение, клиентские сигналы поднимают полосу только до «внимание», и имя оператора должно быть `operator:`. `backend/internal/usecase/identity/keyring_test.go` проверяет новые методы keyring: отпечаток ответа детерминирован, ключевой и привязан к версии семейства; дайджесты сессии и сети различаются между попытками (связать нельзя), между сессиями и между ключами клиента и используют отдельные ключи назначения. + +`backend/internal/usecase/assessment/signal_review_test.go` проверяет наблюдателя и задание проверки на поддельных портах: принятый ответ сохраняет серверное время, признак отсчета от предыдущего ответа, версию ключа и только ключевой отпечаток, без текста ответа, адреса и идентификатора сессии ни в сохраняемых значениях, ни в тексте ошибки; метки происхождения пишутся только при смене сессии или сети; первый ответ планирует задание дедлайна (через минуту после дедлайна), а завершение - задание завершения; тренировочные попытки и запросы без сессии ничего не сохраняют; версия политики без раздела сигналов не создает проверку; задание отклоняет испорченную нагрузку, пропускает отсутствующую попытку, блокирует проверки пары по возрастанию идентификатора попытки до чтения любого факта и пишет их под своими закрепленными политиками, и обновляет только завершившиеся попытки на уровне «внимание», ограниченно. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого демо-семейства, строит распределение общих значений с их битами и считает вероятность того, что одна честная пара достигнет каждого демо-порога на попытке из 23 заданий; умноженная на 10 000 соперников она равна примерно 4e-5 («внимание») и 3e-9 («проверить») при целях 1e-3 и 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили (26 для «внимание» и 61 для «проверить» при 13 заданиях, 9 и 14 при 23). Модель ложных срабатываний использует только распределение эталонных ответов, а не неверные ответы и коррелированные ошибки. Цели - константы теста, выбранные здесь, а не продуктовое решение, а измерение покрывает четыре семейства, написанных ИИ. + +`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` обходит каждый путь публичного контракта по ссылкам и отвергает любое свойство, имя схемы или enum, которые несли бы полосу, ее причины, отпечатки или дайджесты происхождения, и проверяет, что в квитанции сигналов по-прежнему ровно `status`, `accepted_events` и `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` проверяет проверку аргументов до чтения окружения, выводимые поля и очищенные ошибки. Тест bootstrap проверяет, что вид задания проверки зарегистрирован. + +`TestAssessmentSignalReviewOverHTTP` в `backend/integration_test/assessment_signal_review_http_test.go` запускает настоящий роутер, PostgreSQL и worker заданий по сроку: + +- Кандидат отвечает на все задания за миллисекунды из двух сессий входа и с трех сетевых адресов и шлет события вставки из второй сессии. Пока worker не запущен, проверки нет, а задания проверки ожидают, то есть в транзакции кандидата ничего не считалось. Затем у попытки полоса `attention` с причинами быстрые ответы, параллельные сессии, лишние сети и клиентские сигналы, а результат `confirmed` совпадает по исходу, баллам, ограничениям и режиму с результатом столь же верной попытки с полосой `normal`; ни в одной таблице оценки, кроме таблицы проверок, нет колонки полосы. +- Пока попытки идут, публикуется версия политики с другими порогами и под ней открывается категория. Попытки, начатые раньше, сохраняют первую версию, попытка, созданная позже, закреплена за новой версией и остается `normal` при том же поведении, а ее факты все равно сохранены. +- Двое кандидатов с разными seed копируют одинаковые неверные ответы: у первой попытки нет признака дубликата, пока второй кандидат не ответил и не завершил попытку, после чего у обеих полоса `review` с причиной одинаковые ответы. Третья копирующая попытка брошена: пока она идет, ее не помечают, а после окончания ее задание дедлайна (часы worker сдвинуты за срок) ее помечает. Честные попытки с верными ответами не помечаются, даже если совпал ответ из малого пространства, а у попытки с одной сессией и одной сетью ровно одна метка происхождения. +- Чтения кандидатом попытки, результата и доступности не содержат полосу, причины, отпечатки и названия сигналов. Команда оператора выводит полосу, а строки аудита пишутся для найденной и для отсутствующей попытки; имя без префикса `operator:` отклоняется. Факты, проверки и строки аудита отклоняют UPDATE и DELETE, а аудит - и TRUNCATE. +- Журналы и текст новых таблиц и `scheduled_jobs` не содержат сетевых адресов, значений ответов, токенов сессии и CSRF. + +`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` создает 30 честных кандидатов с разными seed, которые отвечают на каждое задание верно или нет случайно (фиксированный генератор), и двоих, копирующих одинаковые ответы: ни одна честная попытка не помечена дубликатом, обе копирующие помечены. Совокупность мала, поэтому тест использует пороги 32 и 44 бита, а не демо-пороги. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` завершает четыре копирующие попытки одновременно среди восьми честных и запускает их задания на четырех worker сразу: ни одно задание не падает и не повторяется, и каждая копирующая попытка помечена. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` держит блокировку проверки попытки в одной транзакции и проверяет, что задание проверки ждет, ничего не пишет и считает проверку по зафиксированным фактам после снятия блокировки; именно этот порядок не дает устаревшей оценке затереть более новую проверку. Тест параллельных заданий прогнан десять раз подряд (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` проверяет, что откат миграции 33 отклоняется, пока в аудите есть строка (таблицы и строка остаются, TRUNCATE отклоняется), и проходит при пустом аудите. + +Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции. + ## Будущая программная валидация Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером. diff --git a/frontend/README.en.md b/frontend/README.en.md index 8f73777..c45bdc9 100644 --- a/frontend/README.en.md +++ b/frontend/README.en.md @@ -53,7 +53,11 @@ A 412 conflict retains the draft and offers explicit reload or replacement again `/candidate/assessment` reads availability and creates attempts through the API; `/candidate/assessment/:attemptId` resumes an attempt, submits answers, and finalizes it through server commands. Real assessment requires current C3 consent. `demo_express` is labeled as a demonstration and does not award a qualification score or confirmed category. The attempt screen displays the server result, but the separate `/candidate/results` route is still a placeholder; result history and confirmed category assignment are not implemented. The client does not calculate scores. -The screen includes an informational notice about technical signals, but the browser does not yet collect or submit them. The server signal-ingest API exists separately; it is not connected to the UI. +Before a real attempt starts, the screen shows a dialog that lists the signals. The browser records tab or window switches, copy, paste and cut, and fullscreen exits; the server measures the answer time per item, a change of network address during the attempt, parallel sessions, and the match of answer digests with other candidates' answers. The dialog states that image, sound, and clipboard contents are not collected, that addresses and session tokens are not stored (only one-way keyed digests), and that browser events are stored only while the C3 consent is current. The attempt cannot start without confirmation: closing the dialog or pressing Escape starts nothing. The confirmation is stored on the server (`/me/assessment-signal-notice`) for the text version, so a reload or a new browser does not ask again; the same dialog opens when an older attempt that was created without the confirmation is resumed. It is a record of being informed, not a consent: C3 stays separate. + +During a real attempt, `features/assessment-signals` collects the disclosed signals: focus loss with its duration, copy, paste and cut with a size only, and fullscreen exit. The listeners are passive, block nothing, and show nothing. Events go in batches (every 10 seconds, when the tab is hidden, or at 20 queued events), and each batch keeps one `Idempotency-Key` across retries. When the page is closed (`pagehide`) or the collector unmounts, what remains is sent in one last request with `keepalive`, so closing the tab does not lose the last seconds of events; the result of that request is not awaited and not retried. A network failure never affects answer submission: a failed batch is sent again with the same key and body after a growing pause and is dropped after the attempt limit. A server refusal (no C3, finished attempt) stops collection. The demonstration run collects no signals. + +Clipboard contents and typed text are never read into a signal or sent. The paste size comes from the `paste` event: file sizes (`File.size`) plus the UTF-8 length of the plain-text item of `clipboardData`; the string lives in one local variable during the count and is not kept. The Clipboard API (`navigator.clipboard`) is not used. The copy and cut size is the selection length in UTF-16 code units taken from the field offsets without reading its value; when the active field has no numeric offsets the size is zero and the page selection is not read. It is an approximate size, not an exact byte count. The answer time per item is measured by the server and not sent by the client. Event timestamps are moved to server time: the client remembers the difference between the device clock and the `Date` header of API responses, because the server rejects a whole batch when a timestamp is more than five minutes from its own clock. Durations use the device clock and do not depend on that difference. Browser signals are easy to forge and false positives are possible, so they are only a hint for a review. ## Privacy settings diff --git a/frontend/README.md b/frontend/README.md index 241c839..8f79e1d 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -53,7 +53,11 @@ SPA на React и TypeScript со сборкой Vite и структурой FS `/candidate/assessment` получает доступность и создает попытки через API; `/candidate/assessment/:attemptId` возобновляет попытку, отправляет ответы и завершает ее серверными командами. Реальный режим требует действующего C3. `demo_express` помечен как демонстрационный и не выдает квалификационный балл или подтвержденную категорию. Интерфейс показывает серверный итог в экране попытки, но отдельный маршрут `/candidate/results` пока остается заглушкой; история результатов и присвоение подтвержденных категорий не реализованы. Клиент не вычисляет баллы. -На экране есть уведомление о технических сигналах, но браузер пока не собирает и не отправляет их. Серверный API приема сигналов существует отдельно; это не означает, что сигнализация подключена к интерфейсу. +Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным. + +Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели пассивные, ничего не блокируют и не показывают; события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает. + +Содержимое буфера и вводимый текст не читаются в сигнал и не отправляются. Размер вставки берется из события `paste`: размер файлов (`File.size`) и длина обычного текста в байтах UTF-8 из `clipboardData`; строка живет в одной локальной переменной на время подсчета и не сохраняется. Clipboard API (`navigator.clipboard`) не используется. Размер копирования и вырезания - длина выделения в единицах UTF-16 по смещениям поля, без чтения его значения; если у активного поля нет числовых смещений, размер равен нулю, а выделение страницы не читается. Это приблизительный размер, а не точный счет байтов. Время ответа по заданию измеряет сервер, клиент его не присылает. Время событий приводится к серверному: клиент запоминает разницу между часами устройства и заголовком `Date` ответов API, потому что сервер отклоняет весь пакет, если метка времени выходит за пять минут от его часов. Длительности считаются по часам устройства и от этой разницы не зависят. Браузерные сигналы легко подделать, а ложные срабатывания возможны, поэтому они только подсказка для перепроверки. ## Настройки приватности diff --git a/frontend/e2e/assessment.spec.ts b/frontend/e2e/assessment.spec.ts index 047d387..c8a62e7 100644 --- a/frontend/e2e/assessment.spec.ts +++ b/frontend/e2e/assessment.spec.ts @@ -213,7 +213,7 @@ test("candidate can review, resume, and finish separate assessment modes", async await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); await expect(page.getByText(/Метод:/)).toBeVisible(); await expect(page.getByText("Лимит времени", { exact: true })).toBeVisible(); - await expect(page.getByText(/Камера, микрофон и запись экрана не используются/)).toBeVisible(); + await expect(page.getByText(/камера и запись экрана не используются/)).toBeVisible(); await page.getByLabel("Язык задания").selectOption("python"); await expect(page.getByLabel("Язык задания")).toHaveValue("python"); await expectNoHorizontalOverflow(page, 360); @@ -226,6 +226,9 @@ test("candidate can review, resume, and finish separate assessment modes", async new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", ); await page.getByRole("button", { name: "Начать полную проверку" }).click(); + await expect(page.getByRole("dialog", { name: /какие сигналы собираются/ })).toBeVisible(); + await expectNoHorizontalOverflow(page, 360); + await page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }).click(); const createRealResponse = await createRealResponsePromise; expect(createRealResponse.status()).toBe(201); expect(createRealResponse.request().postDataJSON()).toMatchObject({ @@ -503,3 +506,343 @@ test("candidate can review, resume, and finish separate assessment modes", async await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0); page.off("request", captureAnswerCommand); }); + +const noticePath = "/api/v1/me/assessment-signal-notice"; +const confirmNoticeName = "Подтверждаю ознакомление и начинаю"; + +function isSignalsRequest(request: Request): boolean { + return ( + request.method() === "POST" && + /^\/api\/v1\/me\/assessment-attempts\/[^/]+\/signals$/.test(new URL(request.url()).pathname) + ); +} + +async function prepareCandidateOnAssessmentScreen(page: Page): Promise { + await registerVerifiedCandidate(page); + await grantC3(page); + await saveAssessmentQuestionnaire(page); + await page.goto("/candidate/assessment"); + await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible(); + await page.getByLabel("Язык задания").selectOption("python"); +} + +async function readNotice(page: Page): Promise<{ acknowledged: boolean; notice_version: number }> { + return page.evaluate(async (path) => { + const response = await fetch(path, { credentials: "same-origin" }); + return (await response.json()) as { acknowledged: boolean; notice_version: number }; + }, noticePath); +} + +/** Confirms the notice, creates the real attempt, and opens its first item. */ +async function openFirstRealItem(page: Page): Promise { + const createResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", + ); + await page.getByRole("button", { name: "Начать полную проверку" }).click(); + await page.getByRole("button", { name: confirmNoticeName }).click(); + const attempt = (await (await createResponse).json()) as AttemptSnapshot; + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); + return attempt.id; +} + +/** Dispatches a paste event that carries recognizable clipboard text. */ +async function simulatePaste(page: Page, text: string): Promise { + await page.evaluate((pasted) => { + const target = document.querySelector("input, textarea") ?? document.body; + const data = new DataTransfer(); + data.setData("text/plain", pasted); + target.dispatchEvent( + new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }), + ); + }, text); +} + +/** Hides or shows the tab the way a tab switch does, through visibilitychange. */ +async function setTabHidden(page: Page, hidden: boolean): Promise { + await page.evaluate((nextHidden) => { + Object.defineProperty(document, "visibilityState", { + configurable: true, + get: () => (nextHidden ? "hidden" : "visible"), + }); + document.hasFocus = () => true; + document.dispatchEvent(new Event("visibilitychange")); + }, hidden); +} + +/** Paste, then leave the tab for a moment. Hiding the tab sends the queued paste. */ +async function simulatePasteAndTabSwitch(page: Page, pastedText: string): Promise { + await simulatePaste(page, pastedText); + await setTabHidden(page, true); + await page.waitForTimeout(300); + await setTabHidden(page, false); +} + +function utf8Length(text: string): number { + return new TextEncoder().encode(text).length; +} + +type SignalEventBody = Record; + +function signalEvents(bodies: string[]): SignalEventBody[] { + return bodies.flatMap((body) => (JSON.parse(body) as { events: SignalEventBody[] }).events); +} + +test("signal requests carry counters and sizes, never the clipboard text", async ({ page }) => { + test.skip( + !questionnaireFixtureEnabled || !mailFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + test.setTimeout(120_000); + const asciiText = "PASTED-SECRET-TEXT-12345"; + const cyrillicText = "Пароль-тест-секрет"; + const bodies: string[] = []; + const keys: (string | undefined)[] = []; + const requestTexts: string[] = []; + const receipts: unknown[] = []; + page.on("request", (request) => { + // Every URL, query string, and body of a non-GET request is searched for the text. + requestTexts.push(decodeURIComponent(request.url()), request.postData() ?? ""); + if (!isSignalsRequest(request)) return; + bodies.push(request.postData() ?? ""); + keys.push(request.headers()["idempotency-key"]); + }); + page.on("response", async (response) => { + if (isSignalsRequest(response.request()) && response.status() === 200) { + receipts.push(await response.json()); + } + }); + + await prepareCandidateOnAssessmentScreen(page); + const attemptId = await openFirstRealItem(page); + + await simulatePaste(page, asciiText); + await simulatePaste(page, cyrillicText); + // Hiding the tab sends the pastes; the absence is sent when the tab is hidden again. + await setTabHidden(page, true); + await page.waitForTimeout(300); + await setTabHidden(page, false); + await setTabHidden(page, true); + await expect + .poll(() => signalEvents(bodies).some((event) => event.kind === "focus_loss"), { + timeout: 15_000, + }) + .toBe(true); + await setTabHidden(page, false); + await expect.poll(() => receipts.length, { timeout: 10_000 }).toBeGreaterThan(1); + + const events = signalEvents(bodies); + const pastes = events.filter((event) => event.kind === "paste"); + expect(pastes.map((event) => event.size_bytes)).toEqual([ + utf8Length(asciiText), + utf8Length(cyrillicText), + ]); + // The size is bytes, not characters: the Cyrillic text is longer in UTF-8. + expect(utf8Length(cyrillicText)).toBeGreaterThan(cyrillicText.length); + const focusLoss = events.find((event) => event.kind === "focus_loss"); + expect(Number(focusLoss?.duration_ms)).toBeGreaterThan(0); + const allowed = new Set(["kind", "item_instance_id", "occurred_at", "size_bytes", "duration_ms"]); + for (const event of events) { + for (const field of Object.keys(event)) expect(allowed.has(field)).toBe(true); + } + for (const text of [asciiText, cyrillicText, encodeURIComponent(cyrillicText)]) { + for (const seen of [...bodies, ...requestTexts]) expect(seen).not.toContain(text); + } + expect(keys.every((key) => Boolean(key))).toBe(true); + expect(new Set(keys).size).toBe(keys.length); + expect(receipts[0]).toMatchObject({ status: "accepted" }); + expect(attemptId).toBeTruthy(); + // Collection shows nothing: no alert and no status text appeared for the candidate. + await expect(page.getByRole("alert")).toHaveCount(0); +}); + +test("a device clock far from the server clock does not drop the signals", async ({ page }) => { + test.skip( + !questionnaireFixtureEnabled || !mailFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + test.setTimeout(120_000); + // The page believes it is two hours later than the server says. + const skewMs = 2 * 60 * 60 * 1000; + await page.addInitScript((skew) => { + const RealDate = Date; + window.Date = new Proxy(RealDate, { + construct: (target, args: unknown[]) => + args.length === 0 + ? new target(RealDate.now() + skew) + : new target(...(args as ConstructorParameters)), + get: (target, property, receiver) => + property === "now" ? () => RealDate.now() + skew : Reflect.get(target, property, receiver), + apply: () => new RealDate(RealDate.now() + skew).toString(), + }); + }, skewMs); + const bodies: string[] = []; + const statuses: number[] = []; + page.on("request", (request) => { + if (isSignalsRequest(request)) bodies.push(request.postData() ?? ""); + }); + page.on("response", (response) => { + if (isSignalsRequest(response.request())) statuses.push(response.status()); + }); + + await prepareCandidateOnAssessmentScreen(page); + await openFirstRealItem(page); + expect(await page.evaluate(() => Date.now())).toBeGreaterThan(Date.now() + skewMs - 60_000); + + await simulatePaste(page, "clock skew paste"); + await setTabHidden(page, true); + await expect.poll(() => statuses.length, { timeout: 15_000 }).toBeGreaterThan(0); + expect(statuses).toEqual([200]); + const [event] = signalEvents(bodies); + const occurredAt = Date.parse(String(event?.occurred_at)); + // The timestamp was moved back to server time, within the five minutes the server accepts. + expect(Math.abs(occurredAt - Date.now())).toBeLessThan(2 * 60 * 1000); +}); + +test("closing the notice does not start the attempt and a confirmation is remembered", async ({ + page, +}) => { + test.skip( + !questionnaireFixtureEnabled || !mailFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + test.setTimeout(120_000); + const creates: string[] = []; + page.on("request", (request) => { + if ( + request.method() === "POST" && + new URL(request.url()).pathname === "/api/v1/me/assessment-attempts" + ) { + creates.push(request.url()); + } + }); + + await prepareCandidateOnAssessmentScreen(page); + const start = page.getByRole("button", { name: "Начать полную проверку" }); + const dialog = page.getByRole("dialog", { name: /какие сигналы собираются/ }); + + await start.click(); + await expect(dialog).toBeVisible(); + for (const text of [ + "Смена вкладки или окна", + "Копирование, вставка и вырезание", + "Выход из полноэкранного режима", + "Время ответа на каждое задание", + "Смена сетевого адреса во время попытки", + "Параллельные сессии", + "Изображение: камера и запись экрана не используются", + "Звук: микрофон не используется", + "Содержимое буфера обмена и вводимый текст", + "только пока действует согласие C3", + "Адреса и токены сессий не хранятся", + ]) { + await expect(dialog.getByText(text)).toBeVisible(); + } + await expect(page.getByRole("heading", { name: /Перед началом/ })).toBeFocused(); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(start).toBeFocused(); + + await start.click(); + await expect(dialog).toBeVisible(); + await page.getByRole("button", { name: "Закрыть без подтверждения" }).click(); + await expect(dialog).toBeHidden(); + expect(creates).toHaveLength(0); + expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 1 }); + + await start.click(); + await expect(dialog).toBeVisible(); + const confirm = dialog.getByRole("button", { name: confirmNoticeName }); + await focusWithKeyboard(page, confirm); + const putResponse = page.waitForResponse( + (response) => + response.request().method() === "PUT" && new URL(response.url()).pathname === noticePath, + ); + const createResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === "/api/v1/me/assessment-attempts", + ); + await page.keyboard.press("Enter"); + expect((await putResponse).status()).toBe(200); + expect(((await (await putResponse).json()) as { acknowledged: boolean }).acknowledged).toBe(true); + const attempt = (await (await createResponse).json()) as AttemptSnapshot; + expect(creates).toHaveLength(1); + await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`)); + + // The confirmation lives on the server: a reload goes straight to the work. + await page.reload(); + expect(await readNotice(page)).toMatchObject({ acknowledged: true }); + const sessionResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/sessions`, + ); + await page.getByRole("button", { name: "Начать или продолжить" }).click(); + expect((await sessionResponse).status()).toBe(200); + await expect(page.getByRole("dialog")).toHaveCount(0); + await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible(); +}); + +test("a failed signal batch is retried with the same key while the answer is saved", async ({ + page, +}) => { + test.skip( + !questionnaireFixtureEnabled || !mailFixtureEnabled, + "Requires the isolated reviewed assessment-bank and mail fixtures.", + ); + test.setTimeout(120_000); + const signalRequests: { key: string | undefined; body: string }[] = []; + const failedSignalUrls: string[] = []; + page.on("request", (request) => { + if (isSignalsRequest(request)) { + signalRequests.push({ + key: request.headers()["idempotency-key"], + body: request.postData() ?? "", + }); + } + }); + page.on("requestfailed", (request) => { + if (isSignalsRequest(request)) failedSignalUrls.push(request.url()); + }); + + await prepareCandidateOnAssessmentScreen(page); + const attemptId = await openFirstRealItem(page); + + // The network is down exactly while the batch is sent. + await page.context().setOffline(true); + await simulatePasteAndTabSwitch(page, "text that must never be sent"); + await expect.poll(() => failedSignalUrls.length, { timeout: 10_000 }).toBe(1); + await page.context().setOffline(false); + + // The answer does not wait for, or depend on, the signal batch. + const answerField = page.getByRole("textbox", { name: /^Числовой ответ/ }); + await focusWithKeyboard(page, answerField); + await page.keyboard.type("1"); + const answerResponse = page.waitForResponse( + (response) => + response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/answers`, + ); + await page.getByRole("button", { name: "Отправить ответ" }).click(); + expect((await answerResponse).status()).toBe(200); + await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + + // The failed batch is sent again with the same key and body, and only once more. + await expect + .poll(() => signalRequests.filter((item) => item.key === signalRequests[0]?.key).length, { + timeout: 20_000, + }) + .toBe(2); + const [first, second] = signalRequests; + expect(first?.key).toBeTruthy(); + expect(second?.key).toBe(first?.key); + expect(second?.body).toBe(first?.body); + expect(first?.body).not.toContain("must never be sent"); + await page.waitForTimeout(3_000); + expect(signalRequests.filter((item) => item.key === first?.key)).toHaveLength(2); +}); diff --git a/frontend/src/entities/assessment/api/assessment-queries.ts b/frontend/src/entities/assessment/api/assessment-queries.ts index 44b965c..2ec5222 100644 --- a/frontend/src/entities/assessment/api/assessment-queries.ts +++ b/frontend/src/entities/assessment/api/assessment-queries.ts @@ -1,20 +1,24 @@ import { useQuery, type QueryClient } from "@tanstack/react-query"; import { + acknowledgeMyAssessmentSignalNotice, getMyAssessmentAvailability, getMyAssessmentAttempt, getMyAssessmentResult, + getMyAssessmentSignalNotice, } from "../../../shared/api/endpoints/assessment/assessment"; import { getMyQuestionnaire } from "../../../shared/api/endpoints/candidate/candidate"; import type { AssessmentAttempt, AssessmentAvailability, AssessmentResult, + AssessmentSignalNotice, Session, } from "../../../shared/api/schemas"; import { parseAssessmentAvailabilityResponse, parseAssessmentAttemptResponse, parseAssessmentResultResponse, + parseAssessmentSignalNoticeResponse, parseCandidateQuestionnaireResponse, } from "../model/contract-validation"; import { assessmentQueryKeys, assertCurrentAssessmentSession } from "../model/session"; @@ -119,4 +123,50 @@ export function useAssessmentResult({ }); } +/** + * Server-owned state of the notice about the collected signals. It is read + * again on mount so an acknowledgement made in another window or browser is + * honored and a reload never asks twice. + */ +export function useAssessmentSignalNotice({ + actor, + enabled = true, + queryClient, +}: AssessmentQueryOptions) { + return useQuery({ + queryKey: actor + ? assessmentQueryKeys.signalNotice(actor) + : [...assessmentQueryKeysPrefix, "signal-notice"], + enabled: Boolean(actor && enabled), + ...privateQueryOptions, + queryFn: async ({ signal }) => { + assertCurrentAssessmentSession(queryClient, actor); + const response = await getMyAssessmentSignalNotice({ signal }); + assertCurrentAssessmentSession(queryClient, actor); + return parseAssessmentSignalNoticeResponse(response); + }, + }); +} + +/** + * Records that the candidate read the notice of the given version and stores + * the server answer in the query cache. The request is idempotent on the + * server, so a retry after a lost response is safe. + */ +export async function acknowledgeAssessmentSignalNotice( + queryClient: QueryClient, + actor: Session, + noticeVersion: number, +): Promise { + assertCurrentAssessmentSession(queryClient, actor); + const response = await acknowledgeMyAssessmentSignalNotice( + { notice_version: noticeVersion }, + { headers: { "X-CSRF-Token": actor.csrf_token } }, + ); + const notice = parseAssessmentSignalNoticeResponse(response); + assertCurrentAssessmentSession(queryClient, actor); + queryClient.setQueryData(assessmentQueryKeys.signalNotice(actor), notice); + return notice; +} + const assessmentQueryKeysPrefix = ["candidate-assessment"] as const; diff --git a/frontend/src/entities/assessment/index.ts b/frontend/src/entities/assessment/index.ts index 55153cb..d3ef242 100644 --- a/frontend/src/entities/assessment/index.ts +++ b/frontend/src/entities/assessment/index.ts @@ -1,8 +1,10 @@ export { + acknowledgeAssessmentSignalNotice, useAssessmentAttempt, useAssessmentAvailability, useAssessmentQuestionnaire, useAssessmentResult, + useAssessmentSignalNotice, } from "./api/assessment-queries"; export { assessmentQueryKeys, diff --git a/frontend/src/entities/assessment/model/contract-validation.test.ts b/frontend/src/entities/assessment/model/contract-validation.test.ts index a31ceca..717e51a 100644 --- a/frontend/src/entities/assessment/model/contract-validation.test.ts +++ b/frontend/src/entities/assessment/model/contract-validation.test.ts @@ -5,6 +5,7 @@ import { parseAssessmentAvailabilityResponse, parseAssessmentAttemptResponse, parseAssessmentResultResponse, + parseAssessmentSignalNoticeResponse, parseCandidateQuestionnaireResponse, } from "./contract-validation"; @@ -90,4 +91,17 @@ describe("assessment response contract validation", () => { expect.objectContaining({ status: 200, code: invalidResponseCode }), ); }); + + it("accepts the signal notice before and after the acknowledgement", () => { + const pending = { notice_version: 1, acknowledged: false, acknowledged_at: null }; + const done = { notice_version: 1, acknowledged: true, acknowledged_at: "2026-10-08T10:00:00Z" }; + expect(parseAssessmentSignalNoticeResponse(pending)).toEqual(pending); + expect(parseAssessmentSignalNoticeResponse(done)).toEqual(done); + }); + + it("rejects an incomplete signal notice payload", () => { + expect(() => parseAssessmentSignalNoticeResponse({ notice_version: 1 })).toThrowError( + expect.objectContaining({ code: invalidResponseCode }), + ); + }); }); diff --git a/frontend/src/entities/assessment/model/contract-validation.ts b/frontend/src/entities/assessment/model/contract-validation.ts index 68b0ff6..5815b0e 100644 --- a/frontend/src/entities/assessment/model/contract-validation.ts +++ b/frontend/src/entities/assessment/model/contract-validation.ts @@ -3,10 +3,12 @@ import { AssessmentAttempt as assessmentAttemptSchema, AssessmentAvailability as assessmentAvailabilitySchema, AssessmentResult as assessmentResultSchema, + AssessmentSignalNotice as assessmentSignalNoticeSchema, CandidateQuestionnaire as candidateQuestionnaireSchema, type AssessmentAttempt, type AssessmentAvailability, type AssessmentResult, + type AssessmentSignalNotice, type CandidateQuestionnaire, } from "../../../shared/api/schemas"; @@ -47,3 +49,12 @@ export function parseAssessmentResultResponse(value: unknown, status = 200): Ass if (!parsed.success) throw invalidAssessmentResponse(status); return parsed.data; } + +export function parseAssessmentSignalNoticeResponse( + value: unknown, + status = 200, +): AssessmentSignalNotice { + const parsed = assessmentSignalNoticeSchema.safeParse(value); + if (!parsed.success) throw invalidAssessmentResponse(status); + return parsed.data; +} diff --git a/frontend/src/entities/assessment/model/session.ts b/frontend/src/entities/assessment/model/session.ts index 31b0ad7..e211f27 100644 --- a/frontend/src/entities/assessment/model/session.ts +++ b/frontend/src/entities/assessment/model/session.ts @@ -47,6 +47,8 @@ export const assessmentQueryKeys = { [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "attempt", attemptId] as const, result: (actor: Session, attemptId: string) => [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "result", attemptId] as const, + signalNotice: (actor: Session) => + [...assessmentQueryPrefix, actor.account.id, actor.csrf_token, "signal-notice"] as const, }; export function removeAssessmentQueries(queryClient: QueryClient): void { diff --git a/frontend/src/features/assessment-signals/index.ts b/frontend/src/features/assessment-signals/index.ts new file mode 100644 index 0000000..6846b4c --- /dev/null +++ b/frontend/src/features/assessment-signals/index.ts @@ -0,0 +1,5 @@ +export { useAssessmentSignals } from "./model/use-assessment-signals"; +export { useSignalNoticeGate } from "./model/use-signal-notice-gate"; +export type { SignalNoticeGate } from "./model/use-signal-notice-gate"; +export { SignalNoticeDialog, SignalNoticeSummary } from "./ui/signal-notice"; +export { shouldCollectSignals } from "./model/signal-session"; diff --git a/frontend/src/features/assessment-signals/model/batcher.test.ts b/frontend/src/features/assessment-signals/model/batcher.test.ts new file mode 100644 index 0000000..6d99f57 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/batcher.test.ts @@ -0,0 +1,259 @@ +import { describe, expect, it, vi } from "vitest"; +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import type { AssessmentSignalEvent } from "../../../shared/api/schemas"; +import { + classifySendFailure, + createSignalBatcher, + type SignalBatch, + type SignalSender, +} from "./batcher"; + +const itemId = "0198d3a0-0000-7000-8000-000000000001"; + +function event(index: number): AssessmentSignalEvent { + return { + kind: "copy", + item_instance_id: itemId, + occurred_at: new Date(Date.UTC(2026, 9, 8, 12, 0, index)).toISOString(), + size_bytes: index, + }; +} + +function apiError(status: number, extra: Partial<{ code: never; retryAfterSeconds: number }> = {}) { + return new ApiRequestError({ + status, + code: (extra.code ?? (status === 0 ? "network_error" : "http_error")) as never, + title: "failure", + retryAfterSeconds: extra.retryAfterSeconds, + }); +} + +function harness(send: (batch: SignalBatch) => Promise, overrides = {}) { + const timers: Array<{ id: number; delay: number; run: () => void }> = []; + let nextId = 1; + let keyCounter = 0; + const batcher = createSignalBatcher({ + send, + newKey: () => `key-${++keyCounter}`, + schedule: (run, delay) => { + const timer = { id: nextId++, delay, run }; + timers.push(timer); + return timer.id; + }, + cancel: (handle) => { + const index = timers.findIndex((timer) => timer.id === handle); + if (index >= 0) timers.splice(index, 1); + }, + ...overrides, + }); + const fire = async () => { + const timer = timers.shift(); + if (!timer) throw new Error("no timer is scheduled"); + timer.run(); + await Promise.resolve(); + await new Promise((resolve) => setTimeout(resolve, 0)); + }; + return { batcher, timers, fire }; +} + +describe("signal batcher", () => { + it("collects events and sends them as one batch after the interval", async () => { + const send = vi.fn(async () => undefined); + const { batcher, timers, fire } = harness(send); + batcher.enqueue(event(1)); + batcher.enqueue(event(2)); + expect(send).not.toHaveBeenCalled(); + expect(timers).toHaveLength(1); + expect(timers[0]?.delay).toBe(10_000); + await fire(); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0]?.[0]).toMatchObject({ key: "key-1", events: [event(1), event(2)] }); + }); + + it("splits a large queue into batches of at most fifty events", async () => { + const send = vi.fn(async () => undefined); + const { batcher, fire } = harness(send); + for (let index = 0; index < 120; index += 1) batcher.enqueue(event(index)); + await fire(); + const sizes = send.mock.calls.map(([batch]) => batch.events.length); + expect(sizes).toEqual([50, 50, 20]); + const keys = send.mock.calls.map(([batch]) => batch.key); + expect(new Set(keys).size).toBe(3); + }); + + it("retries a failed batch with the same key and the same events, once, without duplicates", async () => { + const calls: SignalBatch[] = []; + let online = false; + const send = vi.fn(async (batch: SignalBatch) => { + calls.push({ key: batch.key, events: [...batch.events] }); + if (!online) throw apiError(0); + }); + const { batcher, timers, fire } = harness(send); + batcher.enqueue(event(1)); + await fire(); + expect(calls).toHaveLength(1); + expect(timers).toHaveLength(1); + + // An event that arrives while the retry waits joins the next batch, not the retried one. + batcher.enqueue(event(2)); + expect(timers).toHaveLength(1); + online = true; + await fire(); + expect(calls.map((call) => call.key)).toEqual(["key-1", "key-1", "key-2"]); + expect(calls[1]?.events).toEqual(calls[0]?.events); + expect(calls[2]?.events).toEqual([event(2)]); + expect(timers).toHaveLength(0); + }); + + it("backs off exponentially and abandons a batch after the attempt limit", async () => { + const send = vi.fn(async () => { + throw apiError(503); + }); + const { batcher, timers, fire } = harness(send, { maxAttempts: 3 }); + batcher.enqueue(event(1)); + await fire(); + expect(timers[0]?.delay).toBe(2_000); + await fire(); + expect(timers[0]?.delay).toBe(4_000); + await fire(); + expect(send).toHaveBeenCalledTimes(3); + expect(timers).toHaveLength(0); + }); + + it("waits for the server's Retry-After on a rate limit", async () => { + const send = vi.fn(async () => { + throw apiError(429, { retryAfterSeconds: 30 }); + }); + const { batcher, timers, fire } = harness(send); + batcher.enqueue(event(1)); + await fire(); + expect(timers[0]?.delay).toBe(30_000); + }); + + it("drops an unusable batch and keeps collecting", async () => { + const send = vi + .fn<(batch: SignalBatch) => Promise>() + .mockRejectedValueOnce(apiError(400)) + .mockResolvedValue(undefined); + const { batcher, fire } = harness(send, { flushThreshold: 1 }); + batcher.enqueue(event(1)); + await fire(); + batcher.enqueue(event(2)); + await fire(); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1]?.[0].events).toEqual([event(2)]); + }); + + it("stops collecting when the server refuses the attempt", async () => { + const send = vi.fn(async () => { + throw apiError(403); + }); + const { batcher, timers, fire } = harness(send); + batcher.enqueue(event(1)); + await fire(); + batcher.enqueue(event(2)); + expect(timers).toHaveLength(0); + expect(send).toHaveBeenCalledTimes(1); + }); + + it("bounds the queue by dropping the oldest events", async () => { + const send = vi.fn(async () => undefined); + const { batcher, fire } = harness(send, { maxQueuedEvents: 60, maxBatchEvents: 100 }); + for (let index = 0; index < 100; index += 1) batcher.enqueue(event(index)); + await fire(); + const batch = send.mock.calls[0]?.[0]; + expect(batch?.events).toHaveLength(60); + expect(batch?.events[0]).toEqual(event(40)); + }); + + it("never lets a sender failure escape", async () => { + const { batcher, fire } = harness(async () => { + throw new TypeError("unexpected"); + }); + batcher.enqueue(event(1)); + await expect(fire()).resolves.toBeUndefined(); + expect(() => batcher.dispose()).not.toThrow(); + }); + + it("dispose sends the remaining events once and then ignores new ones", async () => { + const send = vi.fn(async () => undefined); + const { batcher, timers } = harness(send); + batcher.enqueue(event(1)); + batcher.dispose(); + expect(send).toHaveBeenCalledTimes(1); + expect(timers).toHaveLength(0); + batcher.enqueue(event(2)); + expect(timers).toHaveLength(0); + }); +}); + +describe("signal batcher on exit", () => { + it("sends the queued events once with keepalive and keeps working afterwards", async () => { + const send = vi.fn(async () => undefined); + const { batcher, timers, fire } = harness(send); + batcher.enqueue(event(1)); + batcher.flushOnExit(); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true }); + expect(timers).toHaveLength(0); + // The page may come back from the back/forward cache. + batcher.enqueue(event(2)); + await fire(); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1]?.[1]).toBeUndefined(); + }); + + it("takes over a batch that is waiting for its retry and does not schedule another", async () => { + const send = vi + .fn() + .mockRejectedValueOnce(apiError(0)) + .mockResolvedValue(undefined); + const { batcher, timers, fire } = harness(send); + batcher.enqueue(event(1)); + await fire(); + expect(timers).toHaveLength(1); + batcher.flushOnExit(); + expect(send).toHaveBeenCalledTimes(2); + expect(send.mock.calls[1]?.[0].key).toBe(send.mock.calls[0]?.[0].key); + expect(send.mock.calls[1]?.[1]).toEqual({ keepalive: true }); + expect(timers).toHaveLength(0); + }); + + it("sends nothing and fails nothing when the queue is empty or the send rejects", () => { + const send = vi.fn(async () => { + throw apiError(0); + }); + const { batcher } = harness(send); + batcher.flushOnExit(); + expect(send).not.toHaveBeenCalled(); + batcher.enqueue(event(1)); + expect(() => batcher.flushOnExit()).not.toThrow(); + expect(() => batcher.dispose()).not.toThrow(); + }); + + it("dispose uses keepalive for the last send", () => { + const send = vi.fn(async () => undefined); + const { batcher } = harness(send); + batcher.enqueue(event(1)); + batcher.dispose(); + expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true }); + }); +}); + +describe("classifySendFailure", () => { + it("separates temporary failures from permanent ones", () => { + expect(classifySendFailure(apiError(0)).kind).toBe("retry"); + expect(classifySendFailure(apiError(502)).kind).toBe("retry"); + expect(classifySendFailure(apiError(200, { code: invalidResponseCode as never })).kind).toBe( + "retry", + ); + expect(classifySendFailure(apiError(403, { code: "csrf_check_failed" as never })).kind).toBe( + "retry", + ); + expect(classifySendFailure(apiError(403)).kind).toBe("stop"); + expect(classifySendFailure(apiError(401)).kind).toBe("stop"); + expect(classifySendFailure(apiError(409)).kind).toBe("stop"); + expect(classifySendFailure(apiError(422)).kind).toBe("drop"); + expect(classifySendFailure(new Error("x")).kind).toBe("drop"); + }); +}); diff --git a/frontend/src/features/assessment-signals/model/batcher.ts b/frontend/src/features/assessment-signals/model/batcher.ts new file mode 100644 index 0000000..4ce379a --- /dev/null +++ b/frontend/src/features/assessment-signals/model/batcher.ts @@ -0,0 +1,179 @@ +import { ApiRequestError, invalidResponseCode } from "../../../shared/api"; +import type { AssessmentSignalEvent } from "../../../shared/api/schemas"; + +/** One request body with the key that makes its retries harmless. */ +export type SignalBatch = { readonly key: string; readonly events: AssessmentSignalEvent[] }; + +/** + * Sends one batch. `keepalive` asks the transport to let the request outlive + * the page; it is set only for the final sends when the page is going away. + */ +export type SignalSender = (batch: SignalBatch, options?: { keepalive?: boolean }) => Promise; + +export type SignalBatcherOptions = { + send: SignalSender; + newKey: () => string; + /** Timer functions are injected so tests control time. */ + schedule: (callback: () => void, delayMs: number) => unknown; + cancel: (handle: unknown) => void; + flushIntervalMs?: number; + /** Queue length that triggers an early send. */ + flushThreshold?: number; + maxBatchEvents?: number; + /** Oldest events are dropped beyond this many, so memory stays bounded. */ + maxQueuedEvents?: number; + /** Sends of one batch before it is abandoned. */ + maxAttempts?: number; + baseBackoffMs?: number; + maxBackoffMs?: number; +}; + +export type SignalBatcher = { + /** Adds an event. Never throws and never waits for the network. */ + enqueue(event: AssessmentSignalEvent): void; + /** Sends what is queued now, unless a failed batch is waiting for its retry. */ + flush(): void; + /** + * Sends what is queued once, as a keepalive request, for a page that is + * going away. The result is not awaited and nothing is retried; the batcher + * stays usable in case the page is restored from the back/forward cache. + */ + flushOnExit(): void; + /** Stops the timers and makes one last keepalive send attempt without retries. */ + dispose(): void; +}; + +type Verdict = { kind: "retry"; delayMs?: number } | { kind: "drop" } | { kind: "stop" }; + +/** + * Decides what a failed send means. Signals are a hint, so a failure is never + * shown and never reaches the answer flow: it only decides whether the same + * batch is sent again. + * + * - No response, a server error, an unreadable success body, a rate limit, and + * a rejected CSRF token are temporary: the same batch and key are sent again. + * - An unauthenticated, forbidden (for example without C3), unknown, or + * conflicting attempt will not improve: collection stops. + * - Any other client error means this batch is unusable: it is dropped. + */ +export function classifySendFailure(error: unknown): Verdict { + if (!(error instanceof ApiRequestError)) return { kind: "drop" }; + if (error.status === 429) { + return { kind: "retry", delayMs: Math.max(error.retryAfterSeconds ?? 5, 1) * 1000 }; + } + if (error.status === 403 && error.code === "csrf_check_failed") return { kind: "retry" }; + if (error.status === 0 || error.status >= 500 || error.code === invalidResponseCode) { + return { kind: "retry" }; + } + if ([401, 403, 404, 409].includes(error.status)) return { kind: "stop" }; + return { kind: "drop" }; +} + +export function createSignalBatcher(options: SignalBatcherOptions): SignalBatcher { + const flushIntervalMs = options.flushIntervalMs ?? 10_000; + const flushThreshold = options.flushThreshold ?? 20; + const maxBatchEvents = options.maxBatchEvents ?? 50; + const maxQueuedEvents = options.maxQueuedEvents ?? 500; + const maxAttempts = options.maxAttempts ?? 8; + const baseBackoffMs = options.baseBackoffMs ?? 2_000; + const maxBackoffMs = options.maxBackoffMs ?? 60_000; + + const queue: AssessmentSignalEvent[] = []; + let inFlight: SignalBatch | null = null; + let attempts = 0; + let timer: unknown = null; + let retryWaiting = false; + let running = false; + let stopped = false; + let disposed = false; + + function clearTimer(): void { + if (timer !== null) options.cancel(timer); + timer = null; + } + + function arm(delayMs: number): void { + clearTimer(); + timer = options.schedule(() => { + timer = null; + retryWaiting = false; + void run(); + }, delayMs); + } + + function nextBatch(): SignalBatch | null { + if (queue.length === 0) return null; + return { key: options.newKey(), events: queue.splice(0, maxBatchEvents) }; + } + + async function run(): Promise { + if (running || stopped || disposed) return; + running = true; + try { + while (!stopped && !disposed) { + if (!inFlight) { + inFlight = nextBatch(); + attempts = 0; + if (!inFlight) return; + } + try { + await options.send(inFlight); + inFlight = null; + } catch (error: unknown) { + const verdict = classifySendFailure(error); + if (verdict.kind === "stop") { + stopped = true; + inFlight = null; + queue.length = 0; + return; + } + attempts += 1; + if (verdict.kind === "drop" || attempts >= maxAttempts) { + inFlight = null; + continue; + } + retryWaiting = true; + const backoff = Math.min(baseBackoffMs * 2 ** (attempts - 1), maxBackoffMs); + arm(Math.max(verdict.delayMs ?? 0, backoff)); + return; + } + } + } finally { + running = false; + } + } + + return { + enqueue(event) { + if (stopped || disposed) return; + queue.push(event); + if (queue.length > maxQueuedEvents) queue.shift(); + if (running || retryWaiting) return; + if (queue.length >= flushThreshold) arm(0); + else if (timer === null) arm(flushIntervalMs); + }, + flush() { + if (stopped || disposed || retryWaiting) return; + clearTimer(); + void run(); + }, + flushOnExit() { + if (stopped || disposed || running) return; + clearTimer(); + retryWaiting = false; + const last = inFlight ?? nextBatch(); + inFlight = null; + if (last) void options.send(last, { keepalive: true }).catch(() => undefined); + }, + dispose() { + if (disposed) return; + clearTimer(); + const last = inFlight ?? nextBatch(); + disposed = true; + if (last && !stopped && !running) { + // Best effort only: the answer flow never waits for this request. + void options.send(last, { keepalive: true }).catch(() => undefined); + } + }, + }; +} diff --git a/frontend/src/features/assessment-signals/model/collector.test.ts b/frontend/src/features/assessment-signals/model/collector.test.ts new file mode 100644 index 0000000..863dd2e --- /dev/null +++ b/frontend/src/features/assessment-signals/model/collector.test.ts @@ -0,0 +1,228 @@ +import { describe, expect, it } from "vitest"; +import type { AssessmentSignalEvent } from "../../../shared/api/schemas"; +import { attachSignalCollector, type CollectorEnvironment } from "./collector"; + +const itemId = "0198d3a0-0000-7000-8000-000000000001"; + +class FakeDocument extends EventTarget { + visibilityState = "visible"; + fullscreenElement: unknown = null; + focused = true; + activeElement: { selectionStart: number; selectionEnd: number } | null = null; + selected = ""; + hasFocus(): boolean { + return this.focused; + } + getSelection() { + return { rangeCount: this.selected ? 1 : 0, toString: () => this.selected }; + } +} + +function setup(item: string | null = itemId) { + const doc = new FakeDocument(); + const win = new EventTarget(); + let clock = Date.UTC(2026, 9, 8, 12, 0, 0); + const events: AssessmentSignalEvent[] = []; + let hidden = 0; + const detach = attachSignalCollector({ + environment: { document: doc, window: win, now: () => clock } as CollectorEnvironment, + currentItemId: () => item, + onEvent: (event) => events.push(event), + onHidden: () => { + hidden += 1; + }, + }); + return { + doc, + win, + events, + detach, + hidden: () => hidden, + advance: (ms: number) => { + clock += ms; + }, + }; +} + +function pasteEvent(text: string, files: Array<{ size: number }> = []) { + const event = new Event("paste", { cancelable: true }); + Object.defineProperty(event, "clipboardData", { + value: { types: ["text/plain"], files, getData: () => text }, + }); + return event; +} + +describe("signal collector", () => { + it("records a paste with its size and never the text", () => { + const { doc, events } = setup(); + const secret = "SECRET-ANSWER-TEXT"; + const event = pasteEvent(secret); + doc.dispatchEvent(event); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ kind: "paste", item_instance_id: itemId, size_bytes: 18 }); + expect(Object.keys(events[0] ?? {}).sort()).toEqual( + ["item_instance_id", "kind", "occurred_at", "size_bytes"].sort(), + ); + expect(JSON.stringify(events)).not.toContain(secret); + expect(event.defaultPrevented).toBe(false); + }); + + it("records copy and cut by selection length only", () => { + const { doc, events } = setup(); + doc.activeElement = { selectionStart: 0, selectionEnd: 5 }; + doc.dispatchEvent(new Event("copy")); + doc.activeElement = null; + doc.selected = "условие задачи"; + doc.dispatchEvent(new Event("cut")); + expect(events.map((event) => event.kind)).toEqual(["copy", "cut"]); + expect(events.map((event) => ("size_bytes" in event ? event.size_bytes : -1))).toEqual([5, 14]); + }); + + it("measures the time away between hiding and showing the tab", () => { + const { doc, events, advance, hidden } = setup(); + doc.visibilityState = "hidden"; + doc.dispatchEvent(new Event("visibilitychange")); + expect(hidden()).toBe(1); + advance(7_250); + doc.visibilityState = "visible"; + doc.dispatchEvent(new Event("visibilitychange")); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + kind: "focus_loss", + duration_ms: 7_250, + item_instance_id: itemId, + }); + }); + + it("counts a window blur and focus as one absence, even with both signals", () => { + const { doc, win, events, advance } = setup(); + doc.focused = false; + win.dispatchEvent(new Event("blur")); + doc.visibilityState = "hidden"; + doc.dispatchEvent(new Event("visibilitychange")); + advance(3_000); + doc.visibilityState = "visible"; + doc.dispatchEvent(new Event("visibilitychange")); + expect(events).toHaveLength(0); + doc.focused = true; + win.dispatchEvent(new Event("focus")); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ kind: "focus_loss", duration_ms: 3_000 }); + }); + + it("waits for the window focus before ending an absence", () => { + const { doc, win, events, advance } = setup(); + win.dispatchEvent(new Event("blur")); + advance(1_000); + doc.focused = false; + doc.dispatchEvent(new Event("visibilitychange")); + expect(events).toHaveLength(0); + doc.focused = true; + win.dispatchEvent(new Event("focus")); + expect(events).toHaveLength(1); + }); + + it("records only an exit from fullscreen, not entering it", () => { + const { doc, events } = setup(); + doc.fullscreenElement = {}; + doc.dispatchEvent(new Event("fullscreenchange")); + expect(events).toHaveLength(0); + doc.fullscreenElement = null; + doc.dispatchEvent(new Event("fullscreenchange")); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ kind: "fullscreen_exit" }); + }); + + it("ignores events while no item is shown", () => { + const { doc, events } = setup(null); + doc.dispatchEvent(new Event("copy")); + expect(events).toHaveLength(0); + }); + + it("contains a failing consumer and stops after detach", () => { + const doc = new FakeDocument(); + const detach = attachSignalCollector({ + environment: { + document: doc, + window: new EventTarget(), + now: () => 0, + } as CollectorEnvironment, + currentItemId: () => itemId, + onEvent: () => { + throw new Error("consumer failure"); + }, + }); + expect(() => doc.dispatchEvent(new Event("copy"))).not.toThrow(); + detach(); + const { events } = setup(); + expect(events).toHaveLength(0); + }); + + it("maps timestamps to server time without changing durations", () => { + const doc = new FakeDocument(); + const win = new EventTarget(); + let clock = Date.UTC(2026, 9, 8, 12, 0, 0); + const events: AssessmentSignalEvent[] = []; + const offset = -3_600_000; + attachSignalCollector({ + environment: { + document: doc, + window: win, + now: () => clock, + toServerTime: (deviceMs) => deviceMs + offset, + } as CollectorEnvironment, + currentItemId: () => itemId, + onEvent: (event) => events.push(event), + }); + doc.visibilityState = "hidden"; + doc.dispatchEvent(new Event("visibilitychange")); + const startedAt = clock; + clock += 4_000; + doc.visibilityState = "visible"; + doc.dispatchEvent(new Event("visibilitychange")); + doc.dispatchEvent(new Event("copy")); + expect(events[0]).toMatchObject({ + kind: "focus_loss", + duration_ms: 4_000, + occurred_at: new Date(startedAt + offset).toISOString(), + }); + expect(events[1]?.occurred_at).toBe(new Date(clock + offset).toISOString()); + }); + + it("reports the end of the page life", () => { + const doc = new FakeDocument(); + const win = new EventTarget(); + let exits = 0; + attachSignalCollector({ + environment: { document: doc, window: win, now: () => 0 } as CollectorEnvironment, + currentItemId: () => itemId, + onEvent: () => undefined, + onPageHide: () => { + exits += 1; + }, + }); + win.dispatchEvent(new Event("pagehide")); + expect(exits).toBe(1); + }); + + it("registers passive listeners so input is never delayed", () => { + const doc = new FakeDocument(); + const options: unknown[] = []; + const original = doc.addEventListener.bind(doc); + doc.addEventListener = ((type: string, listener: EventListener, opts?: unknown) => { + options.push(opts); + original(type, listener, opts as AddEventListenerOptions); + }) as typeof doc.addEventListener; + attachSignalCollector({ + environment: { + document: doc, + window: new EventTarget(), + now: () => 0, + } as CollectorEnvironment, + currentItemId: () => itemId, + onEvent: () => undefined, + }); + expect(options.length).toBeGreaterThan(0); + for (const entry of options) expect(entry).toMatchObject({ passive: true }); + }); +}); diff --git a/frontend/src/features/assessment-signals/model/collector.ts b/frontend/src/features/assessment-signals/model/collector.ts new file mode 100644 index 0000000..ddccde0 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/collector.ts @@ -0,0 +1,117 @@ +import type { AssessmentSignalEvent } from "../../../shared/api/schemas"; +import { pasteSizeBytes, selectionSize, type PasteSource, type SelectionSource } from "./measure"; +import { clipboardEvent, focusLossEvent, fullscreenExitEvent } from "./signal-events"; + +/** The browser objects the collector listens to; tests pass small fakes. */ +export type CollectorEnvironment = { + document: EventTarget & + SelectionSource & { + readonly visibilityState: string; + readonly fullscreenElement: unknown; + hasFocus(): boolean; + }; + window: EventTarget; + /** Device clock in milliseconds; only differences of it are used as durations. */ + now: () => number; + /** + * Maps a device timestamp to server time for the event metadata. It is kept + * apart from `now` so that a clock offset learned while an absence is being + * measured can never distort the duration. + */ + toServerTime?: (deviceMs: number) => number; +}; + +export type CollectorOptions = { + environment: CollectorEnvironment; + /** Identifier of the item on screen now, or null when none is shown. */ + currentItemId: () => string | null; + onEvent: (event: AssessmentSignalEvent) => void; + /** Called when the page is hidden, a good moment to send what is queued. */ + onHidden?: () => void; + /** Called when the page is being unloaded; the last chance to send. */ + onPageHide?: () => void; +}; + +type ClipboardLike = Event & { clipboardData?: PasteSource | null }; + +/** + * Observes the disclosed signals and reports them through onEvent. + * + * All listeners are passive, never call preventDefault or stopPropagation, and + * never touch the page, so typing, pasting, and answering behave exactly as + * without collection. A listener that throws is contained and cannot reach the + * page. + */ +export function attachSignalCollector(options: CollectorOptions): () => void { + const { document: doc, window: win, now } = options.environment; + const stamp = options.environment.toServerTime ?? ((deviceMs: number) => deviceMs); + let awaySince: number | null = null; + let wasFullscreen = doc.fullscreenElement != null; + + function emit(build: (itemId: string) => AssessmentSignalEvent): void { + const itemId = options.currentItemId(); + if (!itemId) return; + options.onEvent(build(itemId)); + } + + function beginAway(): void { + if (awaySince === null) awaySince = now(); + } + + function endAway(): void { + if (awaySince === null || doc.visibilityState !== "visible" || !doc.hasFocus()) return; + const startedAt = awaySince; + awaySince = null; + const duration = now() - startedAt; + emit((itemId) => focusLossEvent(itemId, stamp(startedAt), duration)); + } + + const handlers: Array<[EventTarget, string, EventListener]> = []; + function listen(target: EventTarget, type: string, handler: (event: Event) => void): void { + const guarded: EventListener = (event) => { + try { + handler(event); + } catch { + // Collection must never disturb the test. + } + }; + target.addEventListener(type, guarded, { capture: true, passive: true }); + handlers.push([target, type, guarded]); + } + + listen(doc, "visibilitychange", () => { + if (doc.visibilityState === "hidden") { + beginAway(); + options.onHidden?.(); + } else { + endAway(); + } + }); + listen(win, "pagehide", () => options.onPageHide?.()); + listen(win, "blur", beginAway); + listen(win, "focus", endAway); + listen(doc, "copy", () => { + const size = selectionSize(doc); + emit((itemId) => clipboardEvent("copy", itemId, stamp(now()), size)); + }); + listen(doc, "cut", () => { + const size = selectionSize(doc); + emit((itemId) => clipboardEvent("cut", itemId, stamp(now()), size)); + }); + listen(doc, "paste", (event) => { + const size = pasteSizeBytes((event as ClipboardLike).clipboardData); + emit((itemId) => clipboardEvent("paste", itemId, stamp(now()), size)); + }); + listen(doc, "fullscreenchange", () => { + const isFullscreen = doc.fullscreenElement != null; + if (wasFullscreen && !isFullscreen) emit((itemId) => fullscreenExitEvent(itemId, stamp(now()))); + wasFullscreen = isFullscreen; + }); + + return () => { + for (const [target, type, handler] of handlers) { + target.removeEventListener(type, handler, { capture: true }); + } + handlers.length = 0; + }; +} diff --git a/frontend/src/features/assessment-signals/model/measure.test.ts b/frontend/src/features/assessment-signals/model/measure.test.ts new file mode 100644 index 0000000..5d9cad9 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/measure.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it, vi } from "vitest"; +import { pasteSizeBytes, selectionSize, utf8ByteLength } from "./measure"; + +describe("utf8ByteLength", () => { + it("matches the platform encoder for ASCII, Cyrillic, emoji, and lone surrogates", () => { + for (const sample of ["", "abc", "привет, мир", "a😀b", "\ud800", "x\udc00y", "日本語"]) { + expect(utf8ByteLength(sample)).toBe(new TextEncoder().encode(sample).length); + } + }); +}); + +describe("pasteSizeBytes", () => { + it("returns only a number for plain text and adds file sizes", () => { + const source = { + types: ["text/plain", "text/html", "Files"], + files: [{ size: 100 }, { size: 20 }], + getData: vi.fn((format: string) => (format === "text/plain" ? "привет" : "x")), + }; + const size = pasteSizeBytes(source); + expect(size).toBe(12 + 120); + expect(typeof size).toBe("number"); + expect(source.getData).toHaveBeenCalledTimes(1); + expect(source.getData).toHaveBeenCalledWith("text/plain"); + }); + + it("does not read any data when the clipboard has no plain text", () => { + const getData = vi.fn(() => "secret"); + expect(pasteSizeBytes({ types: ["text/html"], files: [], getData })).toBe(0); + expect(getData).not.toHaveBeenCalled(); + }); + + it("treats a missing source as an empty paste", () => { + expect(pasteSizeBytes(null)).toBe(0); + expect(pasteSizeBytes(undefined)).toBe(0); + }); + + it("stays within the contract range", () => { + const huge = { types: [], files: [{ size: 5_000_000_000 }], getData: () => "" }; + expect(pasteSizeBytes(huge)).toBe(2_147_483_647); + }); +}); + +describe("selectionSize", () => { + it("uses the offsets of a text control without reading its value", () => { + const control = { + selectionStart: 2, + selectionEnd: 9, + get value(): string { + throw new Error("the typed value must not be read"); + }, + }; + expect(selectionSize({ activeElement: control })).toBe(7); + }); + + it("never falls back to the page selection while a form field has focus", () => { + const getSelection = vi.fn(() => ({ rangeCount: 1, toString: () => "typed secret" })); + expect( + selectionSize({ activeElement: { selectionStart: null, selectionEnd: null }, getSelection }), + ).toBe(0); + expect( + selectionSize({ activeElement: { selectionStart: 3, selectionEnd: 3 }, getSelection }), + ).toBe(0); + const throwing = { + get selectionStart(): number { + throw new DOMException("not supported"); + }, + selectionEnd: 0, + }; + expect(selectionSize({ activeElement: throwing, getSelection })).toBe(0); + expect(getSelection).not.toHaveBeenCalled(); + }); + + it("uses the length of the page selection when no form field has focus", () => { + const doc = { + activeElement: {}, + getSelection: () => ({ rangeCount: 1, toString: () => "условие" }), + }; + expect(selectionSize(doc)).toBe(7); + expect(selectionSize({ getSelection: () => ({ rangeCount: 0, toString: () => "x" }) })).toBe(0); + expect(selectionSize({})).toBe(0); + }); +}); diff --git a/frontend/src/features/assessment-signals/model/measure.ts b/frontend/src/features/assessment-signals/model/measure.ts new file mode 100644 index 0000000..a568a95 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/measure.ts @@ -0,0 +1,106 @@ +/** + * Size measurement for clipboard events. + * + * Only a number leaves this module. Clipboard contents, selections, and typed + * text are never stored, returned, logged, or sent. + * + * Paste: the paste event is the only moment the browser exposes what is being + * pasted, and DataTransfer has no size accessor for text. Dropped or pasted + * files report their size through File.size without reading them. For text, + * the length is taken from the plain-text item inside this function: the string + * lives in one local variable, is measured without copying it, and goes out of + * scope on return. The Clipboard API (navigator.clipboard) is never used, so no + * permission prompt appears and nothing outside the event is read. + * + * Copy and cut: the length of the current selection in UTF-16 code units. For + * form fields it comes from the selection offsets and does not read the typed + * value at all; a field without numeric offsets counts as zero. The page + * selection is measured only when no form field has focus. + */ + +const maxSizeBytes = 2_147_483_647; + +/** The part of DataTransfer that paste measurement needs. */ +export type PasteSource = { + readonly types: ReadonlyArray; + readonly files: ArrayLike<{ readonly size: number }>; + getData(format: string): string; +}; + +/** UTF-8 byte length of a string without allocating an encoded copy. */ +export function utf8ByteLength(text: string): number { + let bytes = 0; + for (let index = 0; index < text.length; index += 1) { + const unit = text.charCodeAt(index); + if (unit < 0x80) { + bytes += 1; + } else if (unit < 0x800) { + bytes += 2; + } else if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < text.length) { + const next = text.charCodeAt(index + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + bytes += 4; + index += 1; + } else { + bytes += 3; + } + } else { + bytes += 3; + } + } + return bytes; +} + +function clampSize(value: number): number { + if (!Number.isFinite(value) || value <= 0) return 0; + return Math.min(Math.floor(value), maxSizeBytes); +} + +/** Size in bytes of what a paste event carries: plain text plus file sizes. */ +export function pasteSizeBytes(source: PasteSource | null | undefined): number { + if (!source) return 0; + let total = 0; + for (let index = 0; index < source.files.length; index += 1) { + total += source.files[index]?.size ?? 0; + } + if (Array.from(source.types).includes("text/plain")) { + total += utf8ByteLength(source.getData("text/plain")); + } + return clampSize(total); +} + +/** The part of a text control or document that selection measurement needs. */ +export type SelectionSource = { + readonly activeElement?: object | null; + getSelection?(): { readonly rangeCount: number; toString(): string } | null; +}; + +/** + * Length of the current selection in UTF-16 code units. + * + * When a form field has focus, only its selection offsets are used. A field + * without numeric offsets (for example a number input) counts as zero rather + * than falling back to the page selection, so typed text is never read, not + * even to measure it. The page selection is used only when no form field is + * active, for example when the task statement is selected. + */ +export function selectionSize(doc: SelectionSource): number { + const active = doc.activeElement as object | null | undefined; + if (active && "selectionStart" in active) { + try { + const { selectionStart, selectionEnd } = active as { + selectionStart: unknown; + selectionEnd: unknown; + }; + if (typeof selectionStart === "number" && typeof selectionEnd === "number") { + return clampSize(selectionEnd - selectionStart); + } + } catch { + // Some field types refuse to expose offsets; treat the size as unknown. + } + return 0; + } + const selection = doc.getSelection?.(); + if (!selection || selection.rangeCount === 0) return 0; + return clampSize(selection.toString().length); +} diff --git a/frontend/src/features/assessment-signals/model/notice-content.ts b/frontend/src/features/assessment-signals/model/notice-content.ts new file mode 100644 index 0000000..d3877a1 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/notice-content.ts @@ -0,0 +1,60 @@ +/** + * Version of the notice text below. The server stores which version a + * candidate acknowledged; change this number together with the text and with + * the version the server requires, so that everyone acknowledges the new text. + */ +export const knownSignalNoticeVersion = 1; + +export type DisclosedSignal = { code: string; title: string; detail: string }; + +/** Signals measured in the browser and sent in batches, only while C3 is current. */ +export const browserSignals: readonly DisclosedSignal[] = [ + { + code: "tab_switch", + title: "Смена вкладки или окна", + detail: "Сколько времени страница теста была не в фокусе.", + }, + { + code: "clipboard", + title: "Копирование, вставка и вырезание", + detail: "Сколько раз это происходило и какого размера было действие.", + }, + { + code: "fullscreen", + title: "Выход из полноэкранного режима", + detail: "Только факт выхода. Полноэкранный режим включать не нужно.", + }, +]; + +/** Signals the server derives while it handles the attempt. */ +export const serverSignals: readonly DisclosedSignal[] = [ + { + code: "answer_time", + title: "Время ответа на каждое задание", + detail: "Его измеряет сервер между показом задания и получением ответа.", + }, + { + code: "network_change", + title: "Смена сетевого адреса во время попытки", + detail: + "Сам адрес не хранится, только односторонний ключевой отпечаток, привязанный к попытке.", + }, + { + code: "parallel_sessions", + title: "Параллельные сессии", + detail: "Токен сессии не хранится, только односторонний ключевой отпечаток.", + }, + { + code: "answer_match", + title: "Совпадение ответов с ответами других кандидатов", + detail: + "Сравниваются односторонние отпечатки ответов на варианты одного задания. Текст ответа для этого не сохраняется.", + }, +]; + +/** What is explicitly not collected. */ +export const notCollected: readonly string[] = [ + "Изображение: камера и запись экрана не используются.", + "Звук: микрофон не используется.", + "Содержимое буфера обмена и вводимый текст: отправляется только размер вставки.", +]; diff --git a/frontend/src/features/assessment-signals/model/notice-gate.test.ts b/frontend/src/features/assessment-signals/model/notice-gate.test.ts new file mode 100644 index 0000000..5dae3e8 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/notice-gate.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from "vitest"; +import { ApiRequestError } from "../../../shared/api"; +import { + closedNoticeDialog, + confirmationError, + decideNotice, + noticeDialogReducer, + type NoticeDialogState, +} from "./notice-gate"; +import { knownSignalNoticeVersion } from "./notice-content"; + +function conflict(status: number): ApiRequestError { + return new ApiRequestError({ status, code: "state_conflict", title: "failure" }); +} + +describe("decideNotice", () => { + it("does not proceed without data from the server", () => { + expect(decideNotice(undefined).kind).toBe("unavailable"); + }); + + it("refuses to confirm a text version the screen does not know", () => { + const decision = decideNotice({ + notice_version: knownSignalNoticeVersion + 1, + acknowledged: true, + }); + expect(decision.kind).toBe("outdated"); + }); + + it("proceeds at once when the server already has the acknowledgement", () => { + expect(decideNotice({ notice_version: knownSignalNoticeVersion, acknowledged: true })).toEqual({ + kind: "proceed", + }); + }); + + it("asks for confirmation when the acknowledgement is missing", () => { + expect(decideNotice({ notice_version: knownSignalNoticeVersion, acknowledged: false })).toEqual( + { kind: "confirm" }, + ); + }); +}); + +describe("confirmationError", () => { + it("tells the candidate to reload after a version conflict", () => { + expect(confirmationError(conflict(409))).toContain("Текст уведомления изменился"); + }); + + it("asks to retry after any other failure", () => { + expect(confirmationError(conflict(0))).toContain("Не удалось сохранить"); + expect(confirmationError(new Error("x"))).toContain("Не удалось сохранить"); + }); +}); + +describe("noticeDialogReducer", () => { + const open = noticeDialogReducer(closedNoticeDialog, { type: "open" }); + + it("opens and closes without a confirmation", () => { + expect(open).toEqual({ open: true, busy: false, errorMessage: null }); + expect(noticeDialogReducer(open, { type: "close" })).toEqual(closedNoticeDialog); + }); + + it("ignores a second confirmation while one is being saved", () => { + const busy = noticeDialogReducer(open, { type: "confirm" }); + expect(busy.busy).toBe(true); + expect(noticeDialogReducer(busy, { type: "confirm" })).toBe(busy); + }); + + it("cannot be closed while the confirmation is being saved", () => { + const busy: NoticeDialogState = noticeDialogReducer(open, { type: "confirm" }); + expect(noticeDialogReducer(busy, { type: "close" })).toBe(busy); + }); + + it("closes after the server stored the confirmation", () => { + const busy = noticeDialogReducer(open, { type: "confirm" }); + expect(noticeDialogReducer(busy, { type: "confirmed" })).toEqual(closedNoticeDialog); + }); + + it("stays open with a message after a version conflict and can be closed again", () => { + const busy = noticeDialogReducer(open, { type: "confirm" }); + const failed = noticeDialogReducer(busy, { type: "failed", error: conflict(409) }); + expect(failed.open).toBe(true); + expect(failed.busy).toBe(false); + expect(failed.errorMessage).toContain("Текст уведомления изменился"); + expect(noticeDialogReducer(failed, { type: "close" })).toEqual(closedNoticeDialog); + }); + + it("does not confirm a dialog that is closed", () => { + expect(noticeDialogReducer(closedNoticeDialog, { type: "confirm" })).toBe(closedNoticeDialog); + }); +}); diff --git a/frontend/src/features/assessment-signals/model/notice-gate.ts b/frontend/src/features/assessment-signals/model/notice-gate.ts new file mode 100644 index 0000000..e809d8d --- /dev/null +++ b/frontend/src/features/assessment-signals/model/notice-gate.ts @@ -0,0 +1,72 @@ +import { ApiRequestError } from "../../../shared/api"; +import { knownSignalNoticeVersion } from "./notice-content"; + +/** What the screen does with the notice state read from the server. */ +export type NoticeDecision = + | { kind: "unavailable"; message: string } + | { kind: "outdated"; message: string } + | { kind: "proceed" } + | { kind: "confirm" }; + +export function decideNotice( + notice: { notice_version: number; acknowledged: boolean } | undefined, +): NoticeDecision { + if (!notice) { + return { + kind: "unavailable", + message: "Не удалось проверить уведомление о сигналах. Повторите действие.", + }; + } + if (notice.notice_version !== knownSignalNoticeVersion) { + return { + kind: "outdated", + message: "Текст уведомления обновился. Обновите страницу и повторите действие.", + }; + } + return notice.acknowledged ? { kind: "proceed" } : { kind: "confirm" }; +} + +export function confirmationError(error: unknown): string { + if (error instanceof ApiRequestError && error.status === 409) { + return "Текст уведомления изменился. Обновите страницу и прочитайте его еще раз."; + } + return "Не удалось сохранить подтверждение. Проверьте соединение и повторите."; +} + +export type NoticeDialogState = { open: boolean; busy: boolean; errorMessage: string | null }; + +export type NoticeDialogEvent = + | { type: "open" } + | { type: "confirm" } + | { type: "confirmed" } + | { type: "failed"; error: unknown } + | { type: "close" }; + +export const closedNoticeDialog: NoticeDialogState = { + open: false, + busy: false, + errorMessage: null, +}; + +/** + * State of the confirmation dialog. While a confirmation is being saved the + * dialog cannot be closed, so a stored confirmation is never hidden by a closed + * dialog and the action that waits for it is not dropped. + */ +export function noticeDialogReducer( + state: NoticeDialogState, + event: NoticeDialogEvent, +): NoticeDialogState { + switch (event.type) { + case "open": + return { open: true, busy: false, errorMessage: null }; + case "confirm": + return state.open && !state.busy ? { ...state, busy: true, errorMessage: null } : state; + case "confirmed": + return closedNoticeDialog; + case "failed": + return { open: true, busy: false, errorMessage: confirmationError(event.error) }; + case "close": + return state.busy ? state : closedNoticeDialog; + } +} diff --git a/frontend/src/features/assessment-signals/model/signal-events.ts b/frontend/src/features/assessment-signals/model/signal-events.ts new file mode 100644 index 0000000..fc64fc5 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/signal-events.ts @@ -0,0 +1,43 @@ +import type { AssessmentSignalEvent } from "../../../shared/api/schemas"; + +const maxDurationMs = 259_200_000; +const maxSizeBytes = 2_147_483_647; + +export type ClipboardKind = "copy" | "paste" | "cut"; + +function timestamp(epochMs: number): string { + return new Date(epochMs).toISOString(); +} + +/** Time away from the test tab or window. Durations are clamped to the contract range. */ +export function focusLossEvent( + itemId: string, + startedAtMs: number, + durationMs: number, +): AssessmentSignalEvent { + return { + kind: "focus_loss", + item_instance_id: itemId, + occurred_at: timestamp(startedAtMs), + duration_ms: Math.min(Math.max(Math.floor(durationMs), 1), maxDurationMs), + }; +} + +/** A copy, paste, or cut with its size only. */ +export function clipboardEvent( + kind: ClipboardKind, + itemId: string, + atMs: number, + sizeBytes: number, +): AssessmentSignalEvent { + return { + kind, + item_instance_id: itemId, + occurred_at: timestamp(atMs), + size_bytes: Math.min(Math.max(Math.floor(sizeBytes), 0), maxSizeBytes), + }; +} + +export function fullscreenExitEvent(itemId: string, atMs: number): AssessmentSignalEvent { + return { kind: "fullscreen_exit", item_instance_id: itemId, occurred_at: timestamp(atMs) }; +} diff --git a/frontend/src/features/assessment-signals/model/signal-session.test.ts b/frontend/src/features/assessment-signals/model/signal-session.test.ts new file mode 100644 index 0000000..dddd79f --- /dev/null +++ b/frontend/src/features/assessment-signals/model/signal-session.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it, vi } from "vitest"; +import type { SignalSender } from "./batcher"; +import type { CollectorEnvironment } from "./collector"; +import { shouldCollectSignals, startSignalSession } from "./signal-session"; + +const itemId = "0198d3a0-0000-7000-8000-000000000001"; + +class FakeDocument extends EventTarget { + visibilityState = "visible"; + fullscreenElement: unknown = null; + activeElement: { selectionStart: number; selectionEnd: number } | null = null; + hasFocus(): boolean { + return true; + } +} + +function start(overrides: { itemId?: string | null; offsetMs?: number } = {}) { + const doc = new FakeDocument(); + const win = new EventTarget(); + const send = vi.fn(async () => undefined); + const timers: Array<() => void> = []; + const clock = Date.UTC(2026, 9, 8, 12, 0, 0); + const item = overrides.itemId === undefined ? itemId : overrides.itemId; + const stop = startSignalSession({ + environment: { + document: doc, + window: win, + now: () => clock, + toServerTime: (deviceMs) => deviceMs + (overrides.offsetMs ?? 0), + } as CollectorEnvironment, + send, + newKey: () => "key", + schedule: (callback) => timers.push(callback), + cancel: () => undefined, + currentItemId: () => item, + }); + return { doc, win, send, timers, stop, clock }; +} + +describe("signal session life cycle", () => { + it("batches an event and sends it when the timer fires", async () => { + const { doc, send, timers } = start(); + doc.dispatchEvent(new Event("copy")); + expect(send).not.toHaveBeenCalled(); + timers[0]?.(); + await Promise.resolve(); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0]?.[0].events[0]).toMatchObject({ + kind: "copy", + item_instance_id: itemId, + }); + }); + + it("sends what is queued when the tab is hidden", () => { + const { doc, send } = start(); + doc.dispatchEvent(new Event("copy")); + doc.visibilityState = "hidden"; + doc.dispatchEvent(new Event("visibilitychange")); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0]?.[1]).toBeUndefined(); + }); + + it("sends with keepalive when the page is being unloaded", () => { + const { doc, win, send } = start(); + doc.dispatchEvent(new Event("copy")); + win.dispatchEvent(new Event("pagehide")); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true }); + }); + + it("shifts event timestamps to server time", () => { + const { doc, send, stop, clock } = start({ offsetMs: -3_600_000 }); + doc.dispatchEvent(new Event("copy")); + stop(); + const event = send.mock.calls[0]?.[0].events[0]; + expect(event?.occurred_at).toBe(new Date(clock - 3_600_000).toISOString()); + }); + + it("stops listening and sends the rest once when disabled", () => { + const { doc, send, stop } = start(); + doc.dispatchEvent(new Event("copy")); + stop(); + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0]?.[1]).toEqual({ keepalive: true }); + doc.dispatchEvent(new Event("copy")); + doc.dispatchEvent(new Event("cut")); + expect(send).toHaveBeenCalledTimes(1); + }); + + it("does nothing while no item is on screen", () => { + const { doc, stop, send } = start({ itemId: null }); + doc.dispatchEvent(new Event("copy")); + stop(); + expect(send).not.toHaveBeenCalled(); + }); +}); + +describe("shouldCollectSignals", () => { + const base = { ready: true, kind: "root" as const, workReady: true, terminal: false }; + + it("collects for a real attempt that is being worked on", () => { + expect(shouldCollectSignals(base)).toBe(true); + expect(shouldCollectSignals({ ...base, kind: "corrective" })).toBe(true); + }); + + it("does not collect for a demonstration run", () => { + expect(shouldCollectSignals({ ...base, kind: "demo_express" })).toBe(false); + }); + + it.each([{ ready: false }, { workReady: false }, { terminal: true }])( + "does not collect when %o", + (change) => { + expect(shouldCollectSignals({ ...base, ...change })).toBe(false); + }, + ); +}); diff --git a/frontend/src/features/assessment-signals/model/signal-session.ts b/frontend/src/features/assessment-signals/model/signal-session.ts new file mode 100644 index 0000000..5f89569 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/signal-session.ts @@ -0,0 +1,55 @@ +import { createSignalBatcher, type SignalBatcher, type SignalSender } from "./batcher"; +import { attachSignalCollector, type CollectorEnvironment } from "./collector"; + +export type SignalSessionOptions = { + environment: CollectorEnvironment; + send: SignalSender; + newKey: () => string; + schedule: (callback: () => void, delayMs: number) => unknown; + cancel: (handle: unknown) => void; + currentItemId: () => string | null; +}; + +/** + * Starts collecting and batching for one attempt and returns the function that + * stops it. Stopping removes every listener, cancels the timers, and makes one + * last keepalive send of what is still queued. It is the whole life cycle that + * the React hook ties to the effect of an enabled attempt. + */ +export function startSignalSession(options: SignalSessionOptions): () => void { + const batcher: SignalBatcher = createSignalBatcher({ + send: options.send, + newKey: options.newKey, + schedule: options.schedule, + cancel: options.cancel, + }); + const detach = attachSignalCollector({ + environment: options.environment, + currentItemId: options.currentItemId, + onEvent: (event) => batcher.enqueue(event), + onHidden: () => batcher.flush(), + onPageHide: () => batcher.flushOnExit(), + }); + return () => { + detach(); + batcher.dispose(); + }; +} + +/** The part of an attempt that decides whether signals are collected. */ +export type SignalCollectionContext = { + /** The candidate session is current and the attempt has been read. */ + ready: boolean; + kind: "root" | "corrective" | "demo_express"; + /** The candidate started or resumed the work in this page. */ + workReady: boolean; + terminal: boolean; +}; + +/** + * Signals are collected only while a real attempt is being worked on. A + * demonstration run stores none, and a finished attempt accepts none. + */ +export function shouldCollectSignals(context: SignalCollectionContext): boolean { + return context.ready && context.workReady && !context.terminal && context.kind !== "demo_express"; +} diff --git a/frontend/src/features/assessment-signals/model/use-assessment-signals.ts b/frontend/src/features/assessment-signals/model/use-assessment-signals.ts new file mode 100644 index 0000000..94ee034 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/use-assessment-signals.ts @@ -0,0 +1,59 @@ +import { useEffect, useRef } from "react"; +import { recordMyAssessmentAttemptSignals } from "../../../shared/api/endpoints/assessment/assessment"; +import { toServerTime } from "../../../shared/api"; +import { startSignalSession } from "./signal-session"; + +export type UseAssessmentSignalsOptions = { + attemptId: string; + /** Identifier of the item on screen now; events are bound to it. */ + itemId: string | null; + csrfToken: string; + /** True only while a real attempt is being worked on. */ + enabled: boolean; +}; + +/** + * Collects the disclosed signals of a real attempt and sends them in batches. + * + * The hook has no output: nothing is rendered, nothing is awaited, and a failed + * request never reaches the answer flow. Each batch keeps one Idempotency-Key + * for all its retries, so a retry after a lost response cannot store it twice. + * Timestamps are shifted to server time, so a wrong device clock cannot make + * the server reject a batch. + */ +export function useAssessmentSignals({ + attemptId, + itemId, + csrfToken, + enabled, +}: UseAssessmentSignalsOptions): void { + const itemRef = useRef(itemId); + const csrfRef = useRef(csrfToken); + + useEffect(() => { + itemRef.current = itemId; + csrfRef.current = csrfToken; + }, [itemId, csrfToken]); + + useEffect(() => { + if (!enabled || !attemptId) return undefined; + return startSignalSession({ + environment: { document, window, now: () => Date.now(), toServerTime }, + send: async (batch, sendOptions) => { + await recordMyAssessmentAttemptSignals( + attemptId, + { events: batch.events }, + { "Idempotency-Key": batch.key }, + { + headers: { "X-CSRF-Token": csrfRef.current }, + ...(sendOptions?.keepalive ? { keepalive: true } : {}), + }, + ); + }, + newKey: () => crypto.randomUUID(), + schedule: (callback, delayMs) => window.setTimeout(callback, delayMs), + cancel: (handle) => window.clearTimeout(handle as number), + currentItemId: () => itemRef.current, + }); + }, [attemptId, enabled]); +} diff --git a/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts b/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts new file mode 100644 index 0000000..e556431 --- /dev/null +++ b/frontend/src/features/assessment-signals/model/use-signal-notice-gate.ts @@ -0,0 +1,87 @@ +import { useReducer, useRef, useState } from "react"; +import type { QueryClient } from "@tanstack/react-query"; +import { ApiRequestError } from "../../../shared/api"; +import type { Session } from "../../../shared/api/schemas"; +import { + acknowledgeAssessmentSignalNotice, + useAssessmentSignalNotice, +} from "../../../entities/assessment"; +import { knownSignalNoticeVersion } from "./notice-content"; +import { closedNoticeDialog, decideNotice, noticeDialogReducer } from "./notice-gate"; + +export type SignalNoticeGate = { + /** + * Runs the action at once when the notice is acknowledged on the server. + * Otherwise the notice dialog opens, and the action runs only after the + * candidate confirms and the server stores the confirmation. + */ + guard: (action: () => void) => Promise; + /** A message when the notice state could not be read or is outdated. */ + checkError: string | null; + dialog: { + open: boolean; + busy: boolean; + errorMessage: string | null; + onConfirm: () => void; + onClose: () => void; + }; +}; + +type Options = { actor: Session | undefined; queryClient: QueryClient; enabled: boolean }; + +/** + * Gate for actions that start a real attempt. The acknowledgement lives on the + * server, so it survives a reload and a new browser; closing the notice leaves + * it unset and the guarded action never runs. The decisions are in + * notice-gate.ts so they can be tested without a DOM. + */ +export function useSignalNoticeGate({ actor, queryClient, enabled }: Options): SignalNoticeGate { + const notice = useAssessmentSignalNotice({ actor, enabled, queryClient }); + const [dialog, dispatch] = useReducer(noticeDialogReducer, closedNoticeDialog); + const [checkError, setCheckError] = useState(null); + const pendingAction = useRef<(() => void) | null>(null); + + async function guard(action: () => void): Promise { + setCheckError(null); + const current = notice.data ?? (await notice.refetch()).data; + const decision = decideNotice(current); + if (decision.kind === "unavailable" || decision.kind === "outdated") { + setCheckError(decision.message); + return; + } + if (decision.kind === "proceed") { + action(); + return; + } + pendingAction.current = action; + dispatch({ type: "open" }); + } + + async function confirm(): Promise { + if (!actor || dialog.busy) return; + dispatch({ type: "confirm" }); + try { + await acknowledgeAssessmentSignalNotice(queryClient, actor, knownSignalNoticeVersion); + } catch (error: unknown) { + dispatch({ type: "failed", error }); + if (error instanceof ApiRequestError && error.status === 409) void notice.refetch(); + return; + } + dispatch({ type: "confirmed" }); + const action = pendingAction.current; + pendingAction.current = null; + action?.(); + } + + function close(): void { + if (dialog.busy) return; + pendingAction.current = null; + dispatch({ type: "close" }); + } + + return { + guard, + checkError, + dialog: { ...dialog, onConfirm: () => void confirm(), onClose: close }, + }; +} diff --git a/frontend/src/features/assessment-signals/ui/signal-notice.module.css b/frontend/src/features/assessment-signals/ui/signal-notice.module.css new file mode 100644 index 0000000..5d694c7 --- /dev/null +++ b/frontend/src/features/assessment-signals/ui/signal-notice.module.css @@ -0,0 +1,107 @@ +.content { + display: grid; + gap: var(--space-3); + min-width: 0; +} + +.content h3, +.content h4, +.content p, +.content ul { + margin: 0; +} + +.content h3, +.content h4 { + font-size: var(--font-size-s); + letter-spacing: var(--letter-spacing-label); + text-transform: uppercase; +} + +.content ul { + display: grid; + gap: var(--space-2); + padding-inline-start: var(--space-5); +} + +.content p, +.content li { + color: var(--color-text-secondary); + overflow-wrap: anywhere; +} + +.content strong { + color: var(--color-text); +} + +.summary { + display: grid; + gap: var(--space-3); + min-width: 0; + padding: var(--space-4); + border: var(--line-thin) solid var(--color-divider); + border-inline-start: var(--line-strong) solid var(--color-accent); + border-radius: var(--radius-m); + background: var(--color-canvas); +} + +.summary h3 { + margin: 0; + font-size: var(--font-size-m); +} + +.dialog { + box-sizing: border-box; + width: min(40rem, calc(100vw - 2 * var(--space-4))); + max-height: calc(100dvh - 2 * var(--space-4)); + padding: var(--space-5); + overflow-y: auto; + border: var(--line-strong) solid var(--color-border-strong); + border-radius: var(--radius-m); + color: var(--color-text); + background: var(--color-surface); +} + +.dialog[open] { + display: grid; + gap: var(--space-4); +} + +.dialog::backdrop { + background: color-mix(in srgb, var(--color-text) 60%, transparent); +} + +.title { + margin: 0; + font-size: var(--font-size-l); +} + +.title:focus-visible { + outline: var(--focus-ring-width) solid var(--color-focus-ring); + outline-offset: var(--focus-ring-offset); +} + +.error { + margin: 0; + color: var(--color-danger); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); +} + +@media (width < 42rem) { + .summary { + padding: var(--space-3); + } + + .dialog { + padding: var(--space-4); + } + + .actions > * { + flex: 1 1 100%; + } +} diff --git a/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx b/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx new file mode 100644 index 0000000..054d258 --- /dev/null +++ b/frontend/src/features/assessment-signals/ui/signal-notice.test.tsx @@ -0,0 +1,69 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice"; + +describe("signal notice", () => { + it("lists the browser signals and the server signals", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Смена вкладки или окна"); + expect(markup).toContain("Копирование, вставка и вырезание"); + expect(markup).toContain("Выход из полноэкранного режима"); + expect(markup).toContain("Время ответа на каждое задание"); + expect(markup).toContain("Смена сетевого адреса во время попытки"); + expect(markup).toContain("Параллельные сессии"); + }); + + it("states that addresses and session tokens are kept only as digests", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Адреса и токены сессий не хранятся"); + expect(markup).toContain("односторонний ключевой отпечаток"); + }); + + it("says that browser events are stored only while C3 is current", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("только пока действует согласие C3"); + }); + + it("uses the heading level it is given and states the camera rule once", () => { + const dialogMarkup = renderToStaticMarkup(); + expect(dialogMarkup).toContain("

Что не собирается

"); + expect(dialogMarkup).not.toContain(")).toContain( + "

Что не собирается

", + ); + expect(dialogMarkup.match(/микрофон/g)).toHaveLength(1); + }); + + it("states that image, sound, and clipboard contents are not collected", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Что не собирается"); + expect(markup).toContain("Изображение"); + expect(markup).toContain("Звук"); + expect(markup).toContain("камера и запись экрана не используются"); + expect(markup).toContain("микрофон не используется"); + expect(markup).toContain("Содержимое буфера обмена и вводимый текст"); + }); + + it("says that the confirmation is stored on the server and is not the C3 consent", () => { + const markup = renderToStaticMarkup(); + expect(markup).toContain("Подтверждение хранится на сервере"); + expect(markup).toContain("не заменяет согласие C3"); + }); + + it("is a labelled dialog with an explicit confirm and a close action", () => { + const markup = renderToStaticMarkup( + undefined} + onClose={() => undefined} + />, + ); + expect(markup).toContain('aria-labelledby="signal-notice-title"'); + expect(markup).toContain('id="signal-notice-title"'); + expect(markup).toContain("Подтверждаю ознакомление и начинаю"); + expect(markup).toContain("Закрыть без подтверждения"); + expect(markup).toContain('role="alert"'); + }); +}); diff --git a/frontend/src/features/assessment-signals/ui/signal-notice.tsx b/frontend/src/features/assessment-signals/ui/signal-notice.tsx new file mode 100644 index 0000000..d4df14d --- /dev/null +++ b/frontend/src/features/assessment-signals/ui/signal-notice.tsx @@ -0,0 +1,149 @@ +import { useEffect, useRef } from "react"; +import { Button } from "../../../shared/ui"; +import { + browserSignals, + notCollected, + serverSignals, + type DisclosedSignal, +} from "../model/notice-content"; +import styles from "./signal-notice.module.css"; + +type ContentProps = { headingLevel: "h3" | "h4" }; + +function SignalList({ signals }: { signals: readonly DisclosedSignal[] }) { + return ( +
    + {signals.map((signal) => ( +
  • + {signal.title}. {signal.detail} +
  • + ))} +
+ ); +} + +/** + * The disclosed list, shared by the page summary and the confirmation dialog. + * The heading level follows the heading that precedes it in each place. + */ +export function SignalNoticeContent({ headingLevel }: ContentProps) { + const Heading = headingLevel; + return ( +
+

+ Во время полной проверки собираются технические сигналы. Они помогают назначить ручную + перепроверку и сами по себе не меняют результат, категорию и квоты. +

+ Что фиксирует браузер +

События сохраняются, только пока действует согласие C3.

+ + Что измеряет сервер + + Что не собирается +
    + {notCollected.map((item) => ( +
  • {item}
  • + ))} +
+

+ Адреса и токены сессий не хранятся: для них есть только односторонние отпечатки. Во время + теста сбор ничего не показывает и не блокирует: ввод, вставка и отправка ответов работают + как обычно. Браузерные сигналы легко исказить, а ложные срабатывания возможны, например при + случайном переключении окна, поэтому это только подсказка. Демонстрационный запуск сигналы + не собирает. +

+

+ Подтверждение хранится на сервере. Оно не заменяет согласие C3, которое управляется отдельно + на странице приватности. +

+
+ ); +} + +/** Always visible description on the screen where the attempt is started. */ +export function SignalNoticeSummary() { + return ( + + ); +} + +export type SignalNoticeDialogProps = { + open: boolean; + busy: boolean; + errorMessage: string | null; + onConfirm: () => void; + onClose: () => void; +}; + +/** + * Modal notice shown before a real attempt starts. It is a native dialog, so + * the browser traps focus inside, closes it with Escape, and returns focus to + * the control that opened it. Closing never confirms anything. + */ +export function SignalNoticeDialog({ + open, + busy, + errorMessage, + onConfirm, + onClose, +}: SignalNoticeDialogProps) { + const dialogRef = useRef(null); + + useEffect(() => { + const dialog = dialogRef.current; + if (!dialog) return; + if (open && !dialog.open) { + dialog.showModal(); + // Start at the heading so a screen reader reads the notice before any action. + dialog.querySelector("#signal-notice-title")?.focus(); + } + if (!open && dialog.open) dialog.close(); + }, [open]); + + return ( + { + // A request in flight finishes first, so a closed notice never hides a stored confirmation. + if (busy) event.preventDefault(); + }} + onClose={() => { + // A second Escape can close the dialog even though the first was refused. + // While the confirmation is being saved the dialog stays modal. + const dialog = dialogRef.current; + if (busy && dialog && !dialog.open) { + dialog.showModal(); + return; + } + onClose(); + }} + > + {open ? ( + <> +

+ Перед началом: какие сигналы собираются +

+ + {errorMessage ? ( +

+ {errorMessage} +

+ ) : null} +
+ + +
+ + ) : null} +
+ ); +} diff --git a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx index bd657e6..65d21c4 100644 --- a/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx +++ b/frontend/src/pages/assessment/ui/assessment-attempt-page.tsx @@ -46,6 +46,12 @@ import { submitPendingAnswerCommand, } from "../../../features/answer-assessment"; import type { AnswerDraft, PendingAnswerCommand } from "../../../features/answer-assessment"; +import { + SignalNoticeDialog, + shouldCollectSignals, + useAssessmentSignals, + useSignalNoticeGate, +} from "../../../features/assessment-signals"; import attemptStyles from "./assessment-attempt-page.module.css"; type PendingFinalize = { key: string; body: AssessmentFinalization }; @@ -107,6 +113,28 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { queryClient, }); const [workReady, setWorkReady] = useState(false); + const collectsSignals = Boolean(attempt && attempt.kind !== "demo_express"); + const signalNotice = useSignalNoticeGate({ + actor, + queryClient, + enabled: actorReady && collectsSignals, + }); + // Signals are collected only while a real attempt is being worked on. The hook + // renders nothing and never waits for the network. + useAssessmentSignals({ + attemptId, + itemId: attempt?.current_item?.id ?? null, + csrfToken: actor?.csrf_token ?? "", + enabled: Boolean( + attempt && + shouldCollectSignals({ + ready: actorReady, + kind: attempt.kind, + workReady, + terminal: isTerminal(attempt), + }), + ), + }); const [resumeBusy, setResumeBusy] = useState(false); const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null); const [pendingAnswer, setPendingAnswer] = useState(null); @@ -529,7 +557,19 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) { Продолжение сверит актуальную версию с сервером. При перезагрузке задания не меняются, а ответ не отправляется повторно автоматически.

-