feat(assessment): record capture hints and keep one window per attempt

This commit is contained in:
shira committed 2026-10-11 13:16:52 +03:00
1 parent c975a0d506
commit bb917bf62e
108 files changed
+6649 -139

No files matched your search

+4 -1
View File
@@ -267,6 +267,8 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR
| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | session | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` |
| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | 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}/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 |
| `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (another page holds it, or the attempt has no work session) |
| `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | session and CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 |
| `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-results` | `ListMyAssessmentResults` | session | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
@@ -275,7 +277,7 @@ The `assessment` tag covers the assessment attempts of the current candidate (PR
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 notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, and the watermark of the task screen and text); it is text version 3, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement.
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, a screenshot key, and a guess that the developer tools are open; stored only while C3 is current) and server signals (response time, change of network address, parallel sessions, change of User-Agent, comparison of answer digests; only one-way keyed digests are stored, never addresses, User-Agents, 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 notice also lists the measures the page applies during a real attempt (fullscreen, covering the task, blocks on copying, selecting, and printing the task text, the paste rule, the one-window rule, and the watermark of the task screen and text) and says plainly that a screenshot or a phone photo cannot be prevented and that signals lead only to a manual check; it is text version 4, and an acknowledgement of an earlier version never counts for the current one. The `demo_express` mode collects no signals and needs no acknowledgement.
Access:
@@ -315,6 +317,7 @@ Items and answers:
- An item has an `id` (the instance), `sequence`, a plain-text `prompt`, and `content` (`ItemContent`) in one of the formats `choice`, `number`, `string`, `order`, `find_error`, `configuration`, and `practice`. It never contains an answer key, a correct option, a score, a family or variant identifier, a seed, or a hidden check, and seed items look like scored ones. `multiple`, `max_selections`, and `max_length` are properties of the format or the task family and never derived from the key. The variant is fixed when first served, so a reload, a retry, or a resumed session returns the same instance.
- Watermark. A real attempt (`root` or `corrective`) carries `watermark.code`, a keyed pseudonym of the attempt such as `7K3QD-9XM2T`, which the client shows with the time as a faint tile over the task screen; a `demo_express` attempt omits the field. The `prompt` of a real attempt also carries an invisible mark and interchangeable wordings chosen by the same server secret; they change neither the meaning nor the reference answer, and a client keeps the invisible characters (zero width space, non-joiner, joiner, word joiner) out of the accessibility tree. Neither the code nor the mark names the candidate, and no operation gives either to an employer. See [Watermark of the task text](../docs/en/ARCHITECTURE.md#watermark-of-the-task-text).
- One open window. A real attempt allows one open page at a time. The page generates a random identifier when it loads and sends it as `X-Attempt-Client` (16 to 64 characters of `A-Za-z0-9_-`) to `HoldMyAssessmentWorkSession`, which holds the work session for 120 seconds and asks the page to renew every 15 seconds, and to `ReleaseMyAssessmentWorkSession` when it closes. `StartMyAssessmentAttemptSession` and `SubmitMyAssessmentAnswer` take the same header as an optional parameter; while another page holds the session, a request from a different page or from none answers 409 `state_conflict` and changes nothing, and that refusal is not stored under the Idempotency-Key. An attempt that nobody holds, a released hold, and a hold that stopped renewing admit every page. It is a one-page-at-a-time rule, not a security boundary, and it is separate from `sessions` (`used`, `max`, `idle_timeout_seconds`), which count sequential work sessions. The server keeps only keyed digests of the page identifier and of the User-Agent bound to the attempt. No new problem code is added, so the page reads 409 on these operations as "open in another window".
- An answer (`AssessmentAnswer`) has the same seven formats and carries only the answer. Unknown fields such as `score`, `duration`, or `seed` answer 400. The server records the times and scores the answer with the key of the item instance; time never enters the grade decision. Responses never say whether an answer was correct.
- The practice solution runs asynchronously in the sandbox against three hidden check groups; the client polls the attempt while it is `pending`. The verdict shows only the score 0-3 and the pass state of each group. Every outcome caused by the solution (a compilation or runtime error, a time or memory limit) is `finished` with groups not passed. `failed` (`sandbox_busy` or `sandbox_error`) means only that the infrastructure could not run it; it consumes nothing. This keeps `failed` from acting as an oracle for hidden checks and from allowing endless retries. After `finished` no other solution is accepted.
- If the latest submission is still `failed` when the limit passes, the result is `not_determined` with the reason `sandbox_unavailable`. A practice never submitted gives `practice_incomplete`.
+4 -1
View File
@@ -267,6 +267,8 @@ ML-сервис отвечает на ошибки той же схемой `Pro
| `GET /api/v1/me/assessment-attempts/{attempt_id}` | `GetMyAssessmentAttempt` | сессия | 200 `AssessmentAttempt`, `Cache-Control: no-store` | 401, 403 `forbidden`, 404 `not_found` |
| `POST /api/v1/me/assessment-attempts/{attempt_id}/sessions` | `StartMyAssessmentAttemptSession` | сессия и 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}/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 |
| `PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `HoldMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 200 `AssessmentWorkSession`, `Cache-Control: no-store` | 400, 401, 403, 404, 409 `state_conflict` (сеанс занят другой страницей или у попытки нет рабочего сеанса) |
| `DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session` | `ReleaseMyAssessmentWorkSession` | сессия и CSRF, `X-Attempt-Client` | 204, `Cache-Control: no-store` | 400, 401, 403, 404 |
| `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-results` | `ListMyAssessmentResults` | сессия | 200 `AssessmentResultHistoryPage`, `Cache-Control: no-store` | 400 `validation_failed`, 401, 403 `forbidden` |
@@ -275,7 +277,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
Каждая операция также объявляет problem-ответ `default`.
Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки и водяной знак экрана и текста задания); это версия 3 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует.
Уведомление о сигналах (`assessment-signal-notice`) перечисляет сигналы, которые собираются во время реальной попытки: события браузера (потеря фокуса, копирование, вставка и вырезание с размером, выход из полноэкранного режима, сохраняются только при действующем C3) и серверные (время ответа, смена сетевого адреса, параллельные сессии, сравнение отпечатков ответов; хранятся только односторонние ключевые отпечатки, адреса и токены сессий не хранятся). `GET` возвращает версию уведомления, которую требует сервер, и признак, что кандидат ее подтвердил; `PUT` сохраняет подтверждение для аккаунта и этой версии. Подтверждение - запись о том, что кандидат ознакомлен, а не согласие: оно не меняет C3, и операция приема сигналов его не читает и не отклоняет пакет без него. `PUT` не требует Idempotency-Key: повтор сохраняет первое время и отвечает 200; другая версия отвечает 409 `state_conflict`. Уведомление также перечисляет меры, которые страница применяет во время реальной попытки (полноэкранный режим, скрытие задания, запрет копирования, выделения и печати текста задания, правило вставки, правило одного окна и водяной знак экрана и текста задания) и прямо говорит, что снимок экрана или фото телефоном предотвратить нельзя, а сигналы ведут только к ручной проверке; это версия 4 текста, и подтверждение более ранней версии для текущей никогда не засчитывается. Режим `demo_express` сигналы не собирает и подтверждения не требует.
Доступ:
@@ -315,6 +317,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro
- У задания есть `id` (экземпляр), `sequence`, `prompt` простым текстом и `content` (`ItemContent`) в одном из форматов `choice`, `number`, `string`, `order`, `find_error`, `configuration` и `practice`. Оно никогда не содержит ключ ответа, правильный вариант, балл, идентификатор семейства или варианта, seed или скрытую проверку, а посевные задания выглядят так же, как оцениваемые. `multiple`, `max_selections` и `max_length` - свойства формата или семейства заданий и никогда не выводятся из ключа. Вариант фиксируется при первой выдаче, поэтому перезагрузка, повтор запроса и возобновление сессии возвращают тот же экземпляр.
- Водяной знак. Реальная попытка (`root` или `corrective`) несет `watermark.code` - ключевой псевдоним попытки вроде `7K3QD-9XM2T`, который клиент показывает вместе со временем бледной плиткой поверх экрана задания; у попытки `demo_express` поля нет. `prompt` реальной попытки также несет невидимую метку и взаимозаменяемые формулировки, выбранные тем же секретом сервера; они не меняют ни смысл, ни эталонный ответ, а клиент держит невидимые символы (пробел нулевой ширины, не-соединитель, соединитель, соединитель слов) вне дерева доступности. Ни код, ни метка не называют кандидата, и ни одна операция не отдает их работодателю. См. [Водяной знак текста задания](../docs/ru/ARCHITECTURE.md#водяной-знак-текста-задания).
- Одно открытое окно. Реальная попытка допускает одну открытую страницу за раз. Страница при загрузке создает случайный идентификатор и отправляет его как `X-Attempt-Client` (от 16 до 64 символов `A-Za-z0-9_-`) в `HoldMyAssessmentWorkSession`, который занимает рабочий сеанс на 120 секунд и просит страницу продлевать его раз в 15 секунд, и в `ReleaseMyAssessmentWorkSession` при закрытии. `StartMyAssessmentAttemptSession` и `SubmitMyAssessmentAnswer` принимают тот же заголовок как необязательный параметр; пока сеанс занят другой страницей, запрос от другой страницы или без заголовка получает 409 `state_conflict` и ничего не меняет, а этот отказ не сохраняется под Idempotency-Key. Попытка, которую никто не держит, освобожденное занятие и переставшее продлеваться пускают любую страницу. Это правило "одна страница за раз", а не граница безопасности, и оно отделено от `sessions` (`used`, `max`, `idle_timeout_seconds`), которые считают последовательные рабочие сеансы. Сервер хранит только ключевые отпечатки идентификатора страницы и User-Agent, привязанные к попытке. Новый код ошибки не добавлялся, поэтому страница читает 409 на этих операциях как "открыто в другом окне".
- Ответ (`AssessmentAnswer`) имеет те же семь форматов и несет только ответ. Неизвестные поля вроде `score`, `duration` или `seed` дают 400. Сервер сам записывает время и оценивает ответ по ключу экземпляра задания; время не входит в решение о грейде. Ответы API никогда не сообщают, был ли ответ правильным.
- Решение практики исполняется в песочнице асинхронно на трех группах скрытых проверок; клиент опрашивает попытку, пока оно `pending`. Вердикт показывает только балл 0-3 и прохождение каждой группы. Любой исход, вызванный самим решением (ошибка компиляции или выполнения, лимит времени или памяти), - это `finished` с непройденными группами. `failed` (`sandbox_busy` или `sandbox_error`) означает только, что инфраструктура не смогла исполнить решение; он ничего не расходует. Так `failed` не становится оракулом для скрытых проверок и не дает бесконечных повторов. После `finished` другое решение не принимается.
- Если к истечению лимита последняя отправка все еще `failed`, результат - `not_determined` с причиной `sandbox_unavailable`. Неотправленная практика дает `practice_incomplete`.
+28
View File
@@ -68,6 +68,34 @@ AssessmentAttemptId:
type: string
format: uuid
example: 01928f7a-3c4d-7e5f-8a9b-0c1d2e3f4a5b
AttemptClient:
name: X-Attempt-Client
in: header
required: false
description: |-
Random identifier that one open page of the assessment attempt generates when it loads and keeps until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a one-way keyed digest bound to the attempt, never the value.
A request that omits the header counts as one anonymous client. It is refused with 409 `state_conflict` while another page holds the work session, and it is accepted while nobody does, so a client that predates the header keeps working until a page holds the session.
schema:
type: string
minLength: 16
maxLength: 64
pattern: "^[A-Za-z0-9_-]+$"
example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG
AttemptClientRequired:
name: X-Attempt-Client
in: header
required: true
description: >-
The page identifier described at AttemptClient. It is required here
because the operation exists to hold or release the work session of one
page.
schema:
type: string
minLength: 16
maxLength: 64
pattern: "^[A-Za-z0-9_-]+$"
example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG
OrganizationId:
name: org_id
in: path
+37
View File
@@ -736,6 +736,22 @@ AssessmentAttemptCommon:
$ref: '#/AssessmentPractice'
watermark:
$ref: '#/AssessmentWatermark'
AssessmentWorkSession:
type: object
description: The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for the attempt, not a score or a signal, and it changes no result.
additionalProperties: false
required:
- held_until
- renew_after_seconds
properties:
held_until:
$ref: '#/Timestamp'
renew_after_seconds:
type: integer
format: int32
minimum: 1
maximum: 3600
description: How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed down in the background still renews before its hold expires.
AssessmentWatermark:
type: object
description: 'Visible mark of a real attempt. The client shows `code` with the current time as a faint tile over the task screen, so that a screenshot or a photo of the screen can be traced back to the attempt by an operator. The code is a keyed pseudonym derived on the server: it carries no name, contact, or identifier of the account, and it cannot be computed without the server secret. The task text of such an attempt also carries an invisible mark and interchangeable wordings chosen by the same secret; they change neither the meaning of a task nor its reference answer, and the client keeps the invisible characters out of the accessibility tree. Training runs (`demo_express`) carry no watermark. It is evidence for a manual review and an appeal, never an automatic decision.'
@@ -1744,6 +1760,7 @@ AssessmentSignalEvent:
- $ref: '#/AssessmentFocusLossSignal'
- $ref: '#/AssessmentClipboardSignal'
- $ref: '#/AssessmentFullscreenExitSignal'
- $ref: '#/AssessmentCaptureSignal'
discriminator:
propertyName: kind
mapping:
@@ -1752,6 +1769,8 @@ AssessmentSignalEvent:
paste: '#/AssessmentClipboardSignal'
cut: '#/AssessmentClipboardSignal'
fullscreen_exit: '#/AssessmentFullscreenExitSignal'
screenshot_key: '#/AssessmentCaptureSignal'
devtools_open: '#/AssessmentCaptureSignal'
AssessmentFocusLossSignal:
type: object
additionalProperties: false
@@ -1816,6 +1835,24 @@ AssessmentFullscreenExitSignal:
$ref: '#/AssessmentItemId'
occurred_at:
$ref: '#/Timestamp'
AssessmentCaptureSignal:
type: object
description: 'A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.'
additionalProperties: false
required:
- kind
- item_instance_id
- occurred_at
properties:
kind:
type: string
enum:
- screenshot_key
- devtools_open
item_instance_id:
$ref: '#/AssessmentItemId'
occurred_at:
$ref: '#/Timestamp'
AssessmentSignalBatch:
type: object
description: A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.
@@ -815,6 +815,28 @@ schemas:
$ref: "#/schemas/AssessmentPractice"
watermark:
$ref: "#/schemas/AssessmentWatermark"
AssessmentWorkSession:
type: object
description: >-
The work session of a real attempt that the calling page holds. It is a
one-page-at-a-time rule for the attempt, not a score or a signal, and it
changes no result.
additionalProperties: false
required:
- held_until
- renew_after_seconds
properties:
held_until:
$ref: "./common_schemas.yml#/schemas/Timestamp"
renew_after_seconds:
type: integer
format: int32
minimum: 1
maximum: 3600
description: >-
How often the page repeats the hold. It is well below the hold time,
so a page whose timer is slowed down in the background still renews
before its hold expires.
AssessmentWatermark:
type: object
description: >-
@@ -8,6 +8,7 @@ schemas:
- $ref: "#/schemas/AssessmentFocusLossSignal"
- $ref: "#/schemas/AssessmentClipboardSignal"
- $ref: "#/schemas/AssessmentFullscreenExitSignal"
- $ref: "#/schemas/AssessmentCaptureSignal"
discriminator:
propertyName: kind
mapping:
@@ -16,6 +17,8 @@ schemas:
paste: "#/schemas/AssessmentClipboardSignal"
cut: "#/schemas/AssessmentClipboardSignal"
fullscreen_exit: "#/schemas/AssessmentFullscreenExitSignal"
screenshot_key: "#/schemas/AssessmentCaptureSignal"
devtools_open: "#/schemas/AssessmentCaptureSignal"
AssessmentFocusLossSignal:
type: object
additionalProperties: false
@@ -88,6 +91,34 @@ schemas:
$ref: "#/schemas/AssessmentItemId"
occurred_at:
$ref: "#/schemas/Timestamp"
AssessmentCaptureSignal:
type: object
description: >-
A hint that the screen may be captured or inspected. `screenshot_key`
is a key or key combination that the browser saw and that usually takes
a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S);
`devtools_open` is the result of a heuristic that guesses that the
developer tools are open (a docked panel changes the window size, or the
console reads an object). Both are weak: a browser does not see every
screenshot, an operating system can take one without a key the page
sees, a phone photo is invisible to the page, and the heuristic gives
false positives. They lead to attention in a manual review at most,
never to a score change, and they carry no measurement.
additionalProperties: false
required:
- kind
- item_instance_id
- occurred_at
properties:
kind:
type: string
enum:
- screenshot_key
- devtools_open
item_instance_id:
$ref: "#/schemas/AssessmentItemId"
occurred_at:
$ref: "#/schemas/Timestamp"
AssessmentSignalBatch:
type: object
description: >-
+143
View File
@@ -1014,6 +1014,8 @@ paths:
If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it.
One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in another window. That refusal is not stored under the Idempotency-Key, because it lasts only until the other page closes or stops renewing. A real attempt that nobody holds is not refused.
The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history.
security:
- sessionCookie: []
@@ -1023,6 +1025,7 @@ paths:
parameters:
- $ref: '#/components/parameters/AssessmentAttemptId'
- $ref: '#/components/parameters/IdempotencyKey'
- $ref: '#/components/parameters/AttemptClient'
requestBody:
required: true
content:
@@ -1116,6 +1119,81 @@ paths:
$ref: '#/components/responses/TooManyRequests'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/assessment-attempts/{attempt_id}/work-session:
put:
operationId: HoldMyAssessmentWorkSession
summary: Hold the single active work session of a real assessment attempt for this page.
description: |-
Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page at a time. The page that works on the attempt calls this operation when the candidate starts or resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until `held_until`.
- If nobody holds the work session, the previous holder released it, or its hold expired, the page becomes the holder and the answer is 200.
- If the same page holds it, the hold is renewed and the answer is 200.
- If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops renewing and its hold expires. The client tells the candidate that the attempt is open in another window and does not show the task.
The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a candidate who closes a page, reloads, or opens the attempt on another device can continue when the hold is released or has expired (at most two minutes after the last renewal). It is not a security boundary: a client that never calls this operation is refused only while another page holds the session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound to the attempt; it never stores or returns either value. A change of the User-Agent digest during an attempt is a weak server signal for a manual review, never an automatic decision.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the hold (409 state_conflict).
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: '#/components/parameters/AssessmentAttemptId'
- $ref: '#/components/parameters/AttemptClientRequired'
responses:
'200':
description: The page holds the work session until `held_until`.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
content:
application/json:
schema:
$ref: '#/components/schemas/AssessmentWorkSession'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'404':
$ref: '#/components/responses/NotFound'
'409':
$ref: '#/components/responses/StateConflict'
default:
$ref: '#/components/responses/Problem'
delete:
operationId: ReleaseMyAssessmentWorkSession
summary: Release the work session that this page holds.
description: |-
Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can open the attempt in another window at once instead of waiting for the hold to expire. The request is idempotent and reveals nothing: it answers 204 whether this page held the session, another page holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the release (204).
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: '#/components/parameters/AssessmentAttemptId'
- $ref: '#/components/parameters/AttemptClientRequired'
responses:
'204':
description: This page no longer holds the work session.
headers:
Cache-Control:
$ref: '#/components/headers/CacheControlNoStore'
'400':
$ref: '#/components/responses/ValidationFailed'
'401':
$ref: '#/components/responses/Unauthenticated'
'403':
$ref: '#/components/responses/CsrfCheckFailedOrForbidden'
'404':
$ref: '#/components/responses/NotFound'
default:
$ref: '#/components/responses/Problem'
/api/v1/me/assessment-attempts/{attempt_id}/answers:
post:
operationId: SubmitMyAssessmentAnswer
@@ -1129,6 +1207,8 @@ paths:
Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation.
One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not stored under the Idempotency-Key and is checked before the stored answer is replayed.
Repeats and conflicts, per item:
- A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
- Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice.
@@ -1146,6 +1226,7 @@ paths:
parameters:
- $ref: '#/components/parameters/AssessmentAttemptId'
- $ref: '#/components/parameters/IdempotencyKey'
- $ref: '#/components/parameters/AttemptClient'
requestBody:
required: true
content:
@@ -5806,6 +5887,7 @@ components:
- $ref: '#/components/schemas/AssessmentFocusLossSignal'
- $ref: '#/components/schemas/AssessmentClipboardSignal'
- $ref: '#/components/schemas/AssessmentFullscreenExitSignal'
- $ref: '#/components/schemas/AssessmentCaptureSignal'
discriminator:
propertyName: kind
mapping:
@@ -5814,6 +5896,8 @@ components:
paste: '#/components/schemas/AssessmentClipboardSignal'
cut: '#/components/schemas/AssessmentClipboardSignal'
fullscreen_exit: '#/components/schemas/AssessmentFullscreenExitSignal'
screenshot_key: '#/components/schemas/AssessmentCaptureSignal'
devtools_open: '#/components/schemas/AssessmentCaptureSignal'
AssessmentFocusLossSignal:
type: object
additionalProperties: false
@@ -10773,6 +10857,40 @@ components:
- task_language
- root_attempt_id
- chain_deadline
AssessmentCaptureSignal:
type: object
description: 'A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.'
additionalProperties: false
required:
- kind
- item_instance_id
- occurred_at
properties:
kind:
type: string
enum:
- screenshot_key
- devtools_open
item_instance_id:
$ref: '#/components/schemas/AssessmentItemId'
occurred_at:
$ref: '#/components/schemas/Timestamp'
AssessmentWorkSession:
type: object
description: The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for the attempt, not a score or a signal, and it changes no result.
additionalProperties: false
required:
- held_until
- renew_after_seconds
properties:
held_until:
$ref: '#/components/schemas/Timestamp'
renew_after_seconds:
type: integer
format: int32
minimum: 1
maximum: 3600
description: How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed down in the background still renews before its hold expires.
AssessmentFinalizeConflictProblem:
type: object
description: A finalize state conflict. `pending_item_ids` is present only when the attempt still has required questions without answers; it is omitted for other state conflicts and idempotency conflicts.
@@ -11719,6 +11837,31 @@ components:
type: string
format: uuid
example: 01928f7a-8b9c-7d0e-9f1a-2b3c4d5e6f70
AttemptClient:
name: X-Attempt-Client
in: header
required: false
description: |-
Random identifier that one open page of the assessment attempt generates when it loads and keeps until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a one-way keyed digest bound to the attempt, never the value.
A request that omits the header counts as one anonymous client. It is refused with 409 `state_conflict` while another page holds the work session, and it is accepted while nobody does, so a client that predates the header keeps working until a page holds the session.
schema:
type: string
minLength: 16
maxLength: 64
pattern: ^[A-Za-z0-9_-]+$
example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG
AttemptClientRequired:
name: X-Attempt-Client
in: header
required: true
description: The page identifier described at AttemptClient. It is required here because the operation exists to hold or release the work session of one page.
schema:
type: string
minLength: 16
maxLength: 64
pattern: ^[A-Za-z0-9_-]+$
example: 7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG
CandidateHandle:
name: candidate_handle
in: path
+2
View File
@@ -135,6 +135,8 @@ paths:
$ref: ./routes/candidate_assessment_attempt_sessions.yml
/api/v1/me/assessment-attempts/{attempt_id}/signals:
$ref: ./routes/candidate_assessment_signals.yml
/api/v1/me/assessment-attempts/{attempt_id}/work-session:
$ref: ./routes/candidate_assessment_attempt_work_session.yml
/api/v1/me/assessment-attempts/{attempt_id}/answers:
$ref: ./routes/candidate_assessment_attempt_answers.yml
/api/v1/me/assessment-attempts/{attempt_id}/finalize:
@@ -10,6 +10,8 @@ post:
Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation.
One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not stored under the Idempotency-Key and is checked before the stored answer is replayed.
Repeats and conflicts, per item:
- A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
- Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice.
@@ -27,6 +29,7 @@ post:
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
- $ref: ../components/parameters.yml#/IdempotencyKey
- $ref: ../components/parameters.yml#/AttemptClient
requestBody:
required: true
content:
@@ -8,6 +8,8 @@ post:
If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it.
One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in another window. That refusal is not stored under the Idempotency-Key, because it lasts only until the other page closes or stops renewing. A real attempt that nobody holds is not refused.
The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history.
security:
- sessionCookie: []
@@ -17,6 +19,7 @@ post:
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
- $ref: ../components/parameters.yml#/IdempotencyKey
- $ref: ../components/parameters.yml#/AttemptClient
requestBody:
required: true
content:
@@ -0,0 +1,74 @@
put:
operationId: HoldMyAssessmentWorkSession
summary: Hold the single active work session of a real assessment attempt for this page.
description: |-
Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page at a time. The page that works on the attempt calls this operation when the candidate starts or resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until `held_until`.
- If nobody holds the work session, the previous holder released it, or its hold expired, the page becomes the holder and the answer is 200.
- If the same page holds it, the hold is renewed and the answer is 200.
- If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops renewing and its hold expires. The client tells the candidate that the attempt is open in another window and does not show the task.
The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a candidate who closes a page, reloads, or opens the attempt on another device can continue when the hold is released or has expired (at most two minutes after the last renewal). It is not a security boundary: a client that never calls this operation is refused only while another page holds the session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound to the attempt; it never stores or returns either value. A change of the User-Agent digest during an attempt is a weak server signal for a manual review, never an automatic decision.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the hold (409 state_conflict).
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
- $ref: ../components/parameters.yml#/AttemptClientRequired
responses:
"200":
description: The page holds the work session until `held_until`.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
content:
application/json:
schema:
$ref: ../components/schemas.yml#/AssessmentWorkSession
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
"409":
$ref: ../components/responses.yml#/StateConflict
default:
$ref: ../components/responses.yml#/Problem
delete:
operationId: ReleaseMyAssessmentWorkSession
summary: Release the work session that this page holds.
description: |-
Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can open the attempt in another window at once instead of waiting for the hold to expire. The request is idempotent and reveals nothing: it answers 204 whether this page held the session, another page holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the release (204).
security:
- sessionCookie: []
sessionCsrf: []
tags:
- assessment
parameters:
- $ref: ../components/parameters.yml#/AssessmentAttemptId
- $ref: ../components/parameters.yml#/AttemptClientRequired
responses:
"204":
description: This page no longer holds the work session.
headers:
Cache-Control:
$ref: ../components/headers.yml#/CacheControlNoStore
"400":
$ref: ../components/responses.yml#/ValidationFailed
"401":
$ref: ../components/responses.yml#/Unauthenticated
"403":
$ref: ../components/responses.yml#/CsrfCheckFailedOrForbidden
"404":
$ref: ../components/responses.yml#/NotFound
default:
$ref: ../components/responses.yml#/Problem
+1 -1
View File
@@ -122,7 +122,7 @@ The candidate-only `POST /api/v1/me/assessment-attempts/{attempt_id}/signals` ac
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 (`CurrentSignalNoticeVersion`, now 3: version 2 added the measures the page applies during an attempt to the signal list, and version 3 describes the watermark of the task screen and text); an acknowledgement is stored per version, so one given for an earlier version stays stored but never counts for the current one and a new text needs no migration. 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.
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 (`CurrentSignalNoticeVersion`, now 4: version 2 added the measures the page applies during an attempt to the signal list, version 3 described the watermark of the task screen and text, and version 4 added the capture hints, the User-Agent digest, and the one-window rule); an acknowledgement is stored per version, so one given for an earlier version stays stored but never counts for the current one and a new text needs no migration. 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
+1 -1
View File
@@ -122,7 +122,7 @@
Операция ограничивает тело 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). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 3: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки, а версия 3 описывает водяной знак экрана и текста задания); подтверждение хранится для каждой версии отдельно, поэтому данное для более ранней версии остается в таблице, но для текущей не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
Уведомление о собираемых сигналах хранится отдельно. `GET` и `PUT /api/v1/me/assessment-signal-notice` читают и записывают подтверждение ознакомления кандидата с версией текста (`usecase/assessment/signal_notice.go`, таблица `assessment_signal_notice_acknowledgements`, миграция 34). Версию текста задает сервер (`CurrentSignalNoticeVersion`, сейчас 4: версия 2 добавила к перечню сигналов меры, которые страница применяет во время попытки, версия 3 описала водяной знак экрана и текста задания, а версия 4 добавила подсказки о съемке, отпечаток User-Agent и правило одного окна); подтверждение хранится для каждой версии отдельно, поэтому данное для более ранней версии остается в таблице, но для текущей не засчитывается, а новый текст не требует миграции. `PUT` с другой версией отвечает 409 и ничего не сохраняет, а повтор сохраняет время первого подтверждения. Подтверждение не является согласием: операция приема сигналов его не читает и по-прежнему требует действующего C3, поэтому уведомление нельзя использовать, чтобы скрыть согласие. Создание попытки подтверждение на сервере не проверяет; требование задает экран кандидата. Строки удаляются каскадом вместе с пользователем.
## Анонимная проекция профиля
@@ -0,0 +1,145 @@
-- +goose Up
-- Three additive pieces of the attempt proctoring that needs no camera:
--
-- 1. The hold of the single active work session of a real attempt. One open
-- page at a time holds it; the holder is a keyed digest of an identifier the
-- page generated, never the identifier. The row is one per attempt and is
-- changed in place under the attempt row lock that the usecase already takes.
-- 2. Two weak client signals: a screenshot key and open developer tools. They
-- carry no measurement.
-- 3. A keyed digest of the User-Agent in the origin marks and three counters in
-- the review. The raw User-Agent is never stored.
CREATE TABLE assessment_attempt_work_leases (
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
holder_digest bytea NOT NULL,
key_version smallint NOT NULL,
acquired_at timestamptz NOT NULL,
renewed_at timestamptz NOT NULL,
released_at timestamptz,
CONSTRAINT assessment_attempt_work_leases_pkey PRIMARY KEY (attempt_id),
CONSTRAINT assessment_attempt_work_leases_holder CHECK (octet_length(holder_digest) = 32),
CONSTRAINT assessment_attempt_work_leases_key_version CHECK (key_version > 0),
CONSTRAINT assessment_attempt_work_leases_times CHECK (
renewed_at >= acquired_at AND (released_at IS NULL OR released_at >= acquired_at)
)
);
-- The two new kinds are facts without a measurement, like a fullscreen exit.
ALTER TABLE assessment_signal_events
DROP CONSTRAINT assessment_signal_events_kind,
DROP CONSTRAINT assessment_signal_events_measurement;
ALTER TABLE assessment_signal_events
ADD CONSTRAINT assessment_signal_events_kind CHECK (
kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit', 'screenshot_key', 'devtools_open')
),
ADD CONSTRAINT assessment_signal_events_measurement CHECK (
(kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL)
OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647)
OR (kind IN ('fullscreen_exit', 'screenshot_key', 'devtools_open') AND duration_ms IS NULL AND size_bytes IS NULL)
);
-- The mark of a request that holds the work session is written like the marks
-- of answers and signal batches, when the session, the network, or the
-- User-Agent differs from the last mark.
ALTER TABLE assessment_attempt_origin_marks
ADD COLUMN agent_digest bytea,
DROP CONSTRAINT assessment_attempt_origin_marks_source;
ALTER TABLE assessment_attempt_origin_marks
ADD CONSTRAINT assessment_attempt_origin_marks_source CHECK (source IN ('answer', 'signals', 'work_session')),
ADD CONSTRAINT assessment_attempt_origin_marks_agent CHECK (
agent_digest IS NULL OR octet_length(agent_digest) = 32
);
ALTER TABLE assessment_attempt_reviews
ADD COLUMN extra_agents integer NOT NULL DEFAULT 0,
ADD COLUMN client_screenshot_keys integer NOT NULL DEFAULT 0,
ADD COLUMN client_devtools_opens integer NOT NULL DEFAULT 0,
DROP CONSTRAINT assessment_attempt_reviews_reasons,
DROP CONSTRAINT assessment_attempt_reviews_counts;
ALTER TABLE assessment_attempt_reviews
ADD CONSTRAINT assessment_attempt_reviews_reasons CHECK (
reasons <@ ARRAY['fast_answers', 'deviating_answers', 'parallel_sessions', 'extra_networks',
'extra_agents', 'duplicate_answers', 'client_signals']::text[]
),
ADD CONSTRAINT assessment_attempt_reviews_counts CHECK (
answered_items >= 0 AND fast_answers >= 0 AND deviating_answers >= 0 AND parallel_alternations >= 0
AND extra_networks >= 0 AND matched_integer_items >= 0 AND matched_sequence_items >= 0
AND duplicate_evidence_bits >= 0 AND client_focus_loss_ms >= 0 AND client_clipboard_events >= 0
AND client_fullscreen_exits >= 0 AND extra_agents >= 0 AND client_screenshot_keys >= 0
AND client_devtools_opens >= 0
);
-- +goose Down
-- The new facts are evidence of a manual review. Rolling the schema back must
-- not drop them as a side effect: an operator exports or resolves them first.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM assessment_signal_events WHERE kind IN ('screenshot_key', 'devtools_open')
) OR EXISTS (
SELECT 1 FROM assessment_attempt_origin_marks WHERE source = 'work_session' OR agent_digest IS NOT NULL
) OR EXISTS (
SELECT 1 FROM assessment_attempt_reviews
WHERE extra_agents > 0 OR client_screenshot_keys > 0 OR client_devtools_opens > 0
OR 'extra_agents' = ANY (reasons)
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'assessment_capture_signals_retained',
MESSAGE = 'capture signal facts must be retained before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
ALTER TABLE assessment_attempt_reviews
DROP CONSTRAINT assessment_attempt_reviews_reasons,
DROP CONSTRAINT assessment_attempt_reviews_counts;
ALTER TABLE assessment_attempt_reviews
DROP COLUMN extra_agents,
DROP COLUMN client_screenshot_keys,
DROP COLUMN client_devtools_opens;
ALTER TABLE assessment_attempt_reviews
ADD CONSTRAINT assessment_attempt_reviews_reasons CHECK (
reasons <@ ARRAY['fast_answers', 'deviating_answers', 'parallel_sessions', 'extra_networks',
'duplicate_answers', 'client_signals']::text[]
),
ADD CONSTRAINT assessment_attempt_reviews_counts CHECK (
answered_items >= 0 AND fast_answers >= 0 AND deviating_answers >= 0 AND parallel_alternations >= 0
AND extra_networks >= 0 AND matched_integer_items >= 0 AND matched_sequence_items >= 0
AND duplicate_evidence_bits >= 0 AND client_focus_loss_ms >= 0 AND client_clipboard_events >= 0
AND client_fullscreen_exits >= 0
);
ALTER TABLE assessment_attempt_origin_marks
DROP CONSTRAINT assessment_attempt_origin_marks_agent,
DROP CONSTRAINT assessment_attempt_origin_marks_source;
ALTER TABLE assessment_attempt_origin_marks
DROP COLUMN agent_digest;
ALTER TABLE assessment_attempt_origin_marks
ADD CONSTRAINT assessment_attempt_origin_marks_source CHECK (source IN ('answer', 'signals'));
ALTER TABLE assessment_signal_events
DROP CONSTRAINT assessment_signal_events_kind,
DROP CONSTRAINT assessment_signal_events_measurement;
ALTER TABLE assessment_signal_events
ADD CONSTRAINT assessment_signal_events_kind CHECK (
kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit')
),
ADD CONSTRAINT assessment_signal_events_measurement CHECK (
(kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL)
OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647)
OR (kind = 'fullscreen_exit' AND duration_ms IS NULL AND size_bytes IS NULL)
);
DROP TABLE assessment_attempt_work_leases;
@@ -33,6 +33,7 @@ INSERT INTO assessment_attempt_origin_marks (
observed_at,
session_digest,
network_digest,
agent_digest,
key_version
) VALUES (
sqlc.arg(id),
@@ -41,6 +42,7 @@ INSERT INTO assessment_attempt_origin_marks (
sqlc.arg(observed_at),
sqlc.arg(session_digest),
sqlc.narg(network_digest),
sqlc.narg(agent_digest),
sqlc.arg(key_version)
);
@@ -55,7 +57,7 @@ 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
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = sqlc.arg(attempt_id)
ORDER BY observed_at, id
@@ -63,7 +65,7 @@ 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
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = sqlc.arg(attempt_id)
ORDER BY observed_at DESC, id DESC
@@ -144,7 +146,9 @@ WHERE id = sqlc.arg(attempt_id) AND kind IN ('root', 'corrective');
SELECT
COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms,
(count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events,
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits,
(count(*) FILTER (WHERE kind = 'screenshot_key'))::integer AS screenshot_keys,
(count(*) FILTER (WHERE kind = 'devtools_open'))::integer AS devtools_opens
FROM assessment_signal_events
WHERE attempt_id = sqlc.arg(attempt_id);
@@ -169,6 +173,9 @@ INSERT INTO assessment_attempt_reviews (
client_focus_loss_ms,
client_clipboard_events,
client_fullscreen_exits,
extra_agents,
client_screenshot_keys,
client_devtools_opens,
evaluated_at,
updated_at
) VALUES (
@@ -187,6 +194,9 @@ INSERT INTO assessment_attempt_reviews (
sqlc.arg(client_focus_loss_ms),
sqlc.arg(client_clipboard_events),
sqlc.arg(client_fullscreen_exits),
sqlc.arg(extra_agents),
sqlc.arg(client_screenshot_keys),
sqlc.arg(client_devtools_opens),
clock_timestamp(),
clock_timestamp()
)
@@ -205,6 +215,9 @@ ON CONFLICT (attempt_id) DO UPDATE SET
client_focus_loss_ms = EXCLUDED.client_focus_loss_ms,
client_clipboard_events = EXCLUDED.client_clipboard_events,
client_fullscreen_exits = EXCLUDED.client_fullscreen_exits,
extra_agents = EXCLUDED.extra_agents,
client_screenshot_keys = EXCLUDED.client_screenshot_keys,
client_devtools_opens = EXCLUDED.client_devtools_opens,
updated_at = greatest(
clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at
);
@@ -236,6 +249,9 @@ SELECT
review.client_focus_loss_ms,
review.client_clipboard_events,
review.client_fullscreen_exits,
review.extra_agents,
review.client_screenshot_keys,
review.client_devtools_opens,
review.evaluated_at,
review.updated_at
FROM assessment_attempt_reviews AS review
@@ -0,0 +1,30 @@
-- The hold of the single active work session of a real attempt. The caller
-- holds the row lock of the attempt, so one attempt's lease is changed by one
-- transaction at a time.
-- name: GetAssessmentWorkLease :one
SELECT attempt_id, holder_digest, key_version, acquired_at, renewed_at, released_at
FROM assessment_attempt_work_leases
WHERE attempt_id = sqlc.arg(attempt_id);
-- name: UpsertAssessmentWorkLease :exec
INSERT INTO assessment_attempt_work_leases (
attempt_id,
holder_digest,
key_version,
acquired_at,
renewed_at,
released_at
) VALUES (
sqlc.arg(attempt_id),
sqlc.arg(holder_digest),
sqlc.arg(key_version),
sqlc.arg(acquired_at),
sqlc.arg(renewed_at),
sqlc.narg(released_at)
)
ON CONFLICT (attempt_id) DO UPDATE SET
holder_digest = EXCLUDED.holder_digest,
key_version = EXCLUDED.key_version,
acquired_at = EXCLUDED.acquired_at,
renewed_at = EXCLUDED.renewed_at,
released_at = EXCLUDED.released_at;
@@ -580,11 +580,17 @@ func newAssessmentAttemptHTTPHarnessWithMiddleware(
t.Fatalf("NewSignalObserver() error = %v", err)
}
attemptService.WithSignalObserver(signalObserver)
workSessions, err := assessment.NewWorkSessions(transactor, keyring)
if err != nil {
t.Fatalf("NewWorkSessions() error = %v", err)
}
workSessions.WithSignalObserver(signalObserver)
attemptService.WithWorkSessions(workSessions)
watermarker, err := assessment.NewWatermarker(keyring)
if err != nil {
t.Fatalf("NewWatermarker() error = %v", err)
}
attemptHandler := v1.NewAssessmentHandler(attemptService).WithPresenter(watermarker)
attemptHandler := v1.NewAssessmentHandler(attemptService).WithPresenter(watermarker).WithWorkSessions(workSessions)
signalService, err := assessment.NewSignalService(transactor, keyring, clock.Now)
if err != nil {
t.Fatalf("NewSignalService() error = %v", err)
@@ -937,6 +943,19 @@ func assessmentAttemptHTTPRequestWithTimeout(
harness *assessmentAttemptHTTPHarness,
method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string,
timeout time.Duration,
) *httptest.ResponseRecorder {
t.Helper()
return assessmentAttemptHTTPRequestWithHeaders(t, harness, method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr, timeout, nil)
}
// assessmentAttemptHTTPRequestWithHeaders is the request of a candidate with
// extra headers, such as the page identifier or a User-Agent.
func assessmentAttemptHTTPRequestWithHeaders(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
method, path, body, origin, cookie, csrf, idempotencyKey, remoteAddr string,
timeout time.Duration,
headers map[string]string,
) *httptest.ResponseRecorder {
t.Helper()
requestContext, cancel := context.WithTimeout(context.Background(), timeout)
@@ -957,6 +976,9 @@ func assessmentAttemptHTTPRequestWithTimeout(
if idempotencyKey != "" {
request.Header.Set("Idempotency-Key", idempotencyKey)
}
for name, value := range headers {
request.Header.Set(name, value)
}
request.RemoteAddr = remoteAddr
recorder := httptest.NewRecorder()
harness.router.ServeHTTP(recorder, request)
@@ -0,0 +1,267 @@
//go:build integration
package integration_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
const (
workPageOne = "page-one-AAAAAAAAAAAAAAAA"
workPageTwo = "page-two-BBBBBBBBBBBBBBBB"
workAgentOne = "TestBrowser/1.0 (Desktop; Workstation)"
workAgentTwo = "TestBrowser/2.0 (Phone; Handheld)"
workAgentThree = "TestBrowser/3.0 (Tablet; Slate)"
)
func workSessionRequest(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
method string,
attemptID uuid.UUID,
candidate reviewCandidate,
client, agent string,
) *httptest.ResponseRecorder {
t.Helper()
headers := map[string]string{"User-Agent": agent}
if client != "" {
headers["X-Attempt-Client"] = client
}
return assessmentAttemptHTTPRequestWithHeaders(t, harness, method,
"/api/v1/me/assessment-attempts/"+attemptID.String()+"/work-session", "", sessionHTTPTestOrigin,
candidate.cookies[0].Value, candidate.csrf[0], "", "192.0.2.40:4321", 20*time.Second, headers)
}
func startSessionRequest(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
attempt assessmentAnswerHTTPAttempt,
candidate reviewCandidate,
key, client string,
) *httptest.ResponseRecorder {
t.Helper()
headers := map[string]string{"User-Agent": workAgentOne}
if client != "" {
headers["X-Attempt-Client"] = client
}
return assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/sessions", `{"expected_version":1}`, sessionHTTPTestOrigin,
candidate.cookies[0].Value, candidate.csrf[0], key, "192.0.2.41:4321", 20*time.Second, headers)
}
func answerRequest(
t *testing.T,
harness *assessmentAttemptHTTPHarness,
attempt assessmentAnswerHTTPAttempt,
body []byte,
candidate reviewCandidate,
key, client string,
) *httptest.ResponseRecorder {
t.Helper()
headers := map[string]string{"User-Agent": workAgentOne}
if client != "" {
headers["X-Attempt-Client"] = client
}
return assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPost,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/answers", string(body), sessionHTTPTestOrigin,
candidate.cookies[0].Value, candidate.csrf[0], key, "192.0.2.42:4321", 20*time.Second, headers)
}
// TestAssessmentWorkSessionOverHTTP checks, with PostgreSQL, that one open page
// holds the work session of a real attempt: a second page is refused for the
// session and the answer until the first one releases it or stops renewing, the
// refusal is not stored under an idempotency key, the page and the User-Agent
// are kept only as keyed digests, and the weak capture signals and extra
// User-Agents reach the review band at attention at most.
func TestAssessmentWorkSessionOverHTTP(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), assessmentAttemptHTTPTimeout)
defer cancel()
signals := reviewTestSignalPolicy()
signals.ClientScreenshotKeysAttention, signals.ClientDevtoolsAttention = 2, 1
signals.ExtraAgentsAttention, signals.ExtraAgentsReview = 2, 3
harness := newReviewHarness(ctx, t, signals)
candidate := newReviewCandidate(ctx, t, harness, "work-session@example.test", "192.0.2", 1)
attempt := candidate.createAttempt(t, harness, "work-session-create", "192.0.2.30:1234")
items := readAssessmentAnswerHTTPItems(t, ctx, harness, attempt.ID)
answer := assessmentAnswerHTTPBody(t, 1, items[0])
// The first page holds the session; the answer carries no page identifier.
held := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentOne)
var lease struct {
HeldUntil time.Time `json:"held_until"`
RenewAfterSeconds int `json:"renew_after_seconds"`
}
if held.Code != http.StatusOK || json.Unmarshal(held.Body.Bytes(), &lease) != nil || lease.RenewAfterSeconds != 15 ||
!lease.HeldUntil.After(time.Now()) || held.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("hold = %d %s, want a no-store lease that renews every 15 seconds", held.Code, held.Body.String())
}
if strings.Contains(held.Body.String(), workPageOne) {
t.Fatalf("the lease %s repeats the page identifier", held.Body.String())
}
if renewed := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentOne); renewed.Code != http.StatusOK {
t.Fatalf("renewal by the holder = %d %s", renewed.Code, renewed.Body.String())
}
// A second page is refused with an explanation-free 409 that changes nothing.
requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo),
http.StatusConflict, "state_conflict")
requireSessionProblem(t, startSessionRequest(t, harness, attempt, candidate, "work-start", workPageTwo), http.StatusConflict, "state_conflict")
requireSessionProblem(t, startSessionRequest(t, harness, attempt, candidate, "work-start-anonymous", ""), http.StatusConflict, "state_conflict")
requireSessionProblem(t, answerRequest(t, harness, attempt, answer, candidate, "work-answer", workPageTwo), http.StatusConflict, "state_conflict")
requireSessionProblem(t, answerRequest(t, harness, attempt, answer, candidate, "work-answer-anonymous", ""), http.StatusConflict, "state_conflict")
if stored := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_items WHERE attempt_id = $1 AND answer IS NOT NULL", attempt.ID); stored != 0 {
t.Fatalf("a refused answer was stored: %d answered items", stored)
}
// The refusal was not stored under the key: the holder reuses both keys.
if resumed := startSessionRequest(t, harness, attempt, candidate, "work-start", workPageOne); resumed.Code != http.StatusOK {
t.Fatalf("session of the holder under the refused key = %d %s", resumed.Code, resumed.Body.String())
}
var answered assessmentAnswerHTTPAttempt
first := answerRequest(t, harness, attempt, answer, candidate, "work-answer", workPageOne)
if first.Code != http.StatusOK || json.Unmarshal(first.Body.Bytes(), &answered) != nil || answered.Version != 2 {
t.Fatalf("answer of the holder under the refused key = %d %s", first.Code, first.Body.String())
}
// Another page cannot release the session of the holder, and a release
// never says whether it did anything.
if released := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageTwo, workAgentTwo); released.Code != http.StatusNoContent {
t.Fatalf("release by another page = %d %s, want 204", released.Code, released.Body.String())
}
requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo),
http.StatusConflict, "state_conflict")
// The first page closes: the second takes over at once, with another browser.
if released := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageOne, workAgentOne); released.Code != http.StatusNoContent {
t.Fatalf("release by the holder = %d %s", released.Code, released.Body.String())
}
if repeat := workSessionRequest(t, harness, http.MethodDelete, attempt.ID, candidate, workPageOne, workAgentOne); repeat.Code != http.StatusNoContent {
t.Fatalf("repeated release = %d %s, want 204", repeat.Code, repeat.Body.String())
}
if taken := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageTwo, workAgentTwo); taken.Code != http.StatusOK {
t.Fatalf("hold by the second page after the release = %d %s", taken.Code, taken.Body.String())
}
second := answerRequest(t, harness, answered, answer, candidate, "work-answer-after", workPageOne)
requireSessionProblem(t, second, http.StatusConflict, "state_conflict")
// A page that is killed stops renewing: its hold ends by itself.
if _, err := harness.pool.Exec(ctx, `UPDATE assessment_attempt_work_leases
SET acquired_at = acquired_at - INTERVAL '10 minutes', renewed_at = renewed_at - INTERVAL '10 minutes' WHERE attempt_id = $1`, attempt.ID); err != nil {
t.Fatalf("age the lease: %v", err)
}
if retaken := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, workPageOne, workAgentThree); retaken.Code != http.StatusOK {
t.Fatalf("hold after the other page stopped renewing = %d %s", retaken.Code, retaken.Body.String())
}
// Malformed identifiers, a foreign attempt, and a training run.
for _, bad := range []string{"short", strings.Repeat("a", 65), "has space has space"} {
response := workSessionRequest(t, harness, http.MethodPut, attempt.ID, candidate, bad, workAgentOne)
if response.Code != http.StatusBadRequest {
t.Fatalf("hold with page identifier %q = %d %s, want 400", bad, response.Code, response.Body.String())
}
}
requireSessionProblem(t, workSessionRequest(t, harness, http.MethodPut, uuid.New(), candidate, workPageOne, workAgentOne), http.StatusNotFound, "not_found")
missing := assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPut,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/work-session", "", sessionHTTPTestOrigin,
candidate.cookies[0].Value, candidate.csrf[0], "", "192.0.2.43:4321", 20*time.Second, nil)
if missing.Code != http.StatusBadRequest {
t.Fatalf("hold without a page identifier = %d %s, want 400", missing.Code, missing.Body.String())
}
noCSRF := assessmentAttemptHTTPRequestWithHeaders(t, harness, http.MethodPut,
"/api/v1/me/assessment-attempts/"+attempt.ID.String()+"/work-session", "", sessionHTTPTestOrigin,
candidate.cookies[0].Value, "", "", "192.0.2.43:4321", 20*time.Second, map[string]string{"X-Attempt-Client": workPageOne})
requireSessionProblem(t, noCSRF, http.StatusForbidden, "csrf_check_failed")
// Only digests are stored: no column holds a page identifier or a User-Agent.
if rows := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_work_leases WHERE attempt_id = $1", attempt.ID); rows != 1 {
t.Fatalf("lease rows = %d, want one per attempt", rows)
}
for _, table := range []string{"assessment_attempt_work_leases", "assessment_attempt_origin_marks"} {
var dump string
if err := harness.pool.QueryRow(ctx, "SELECT coalesce(string_agg(t::text, ' '), '') FROM "+table+" AS t WHERE attempt_id = $1", attempt.ID).Scan(&dump); err != nil {
t.Fatalf("dump %s: %v", table, err)
}
for _, secret := range []string{workPageOne, workPageTwo, "TestBrowser", "Desktop", "Handheld"} {
if strings.Contains(dump, secret) {
t.Fatalf("%s holds %q, want only keyed digests", table, secret)
}
}
}
for _, agent := range []string{workAgentOne, workAgentTwo, workAgentThree} {
digest := harness.keyring.AssessmentAgentDigest(attempt.ID, agent)
if rows := countRows(t, ctx, harness, "SELECT count(*) FROM assessment_attempt_origin_marks WHERE attempt_id = $1 AND agent_digest = $2 AND source = 'work_session'", attempt.ID, digest[:]); rows == 0 {
t.Fatalf("no work session mark carries the digest of %q", agent)
}
}
// The weak capture signals are stored without a measurement and refused with one.
itemID := items[0].ID
at := time.Now().UTC().Truncate(time.Microsecond)
batch := func(events ...map[string]any) string {
encoded, err := json.Marshal(map[string]any{"events": events})
if err != nil {
t.Fatalf("marshal capture batch: %v", err)
}
return string(encoded)
}
event := func(kind string, offset time.Duration) map[string]any {
return map[string]any{"kind": kind, "item_instance_id": itemID, "occurred_at": at.Add(offset).Format(time.RFC3339Nano)}
}
accepted := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-batch",
batch(event("screenshot_key", 0), event("screenshot_key", time.Second), event("devtools_open", 2*time.Second)), "192.0.2.44:4321")
assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 3)
withSize := event("screenshot_key", 3*time.Second)
withSize["size_bytes"] = 10
if rejected := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-size", batch(withSize), "192.0.2.45:4321"); rejected.Code != http.StatusBadRequest {
t.Fatalf("screenshot key with a size = %d %s, want 400", rejected.Code, rejected.Body.String())
}
if unknown := submitAssessmentSignal(t, harness, attempt.ID, candidate.cookies[0], candidate.csrf[0], "capture-kind", batch(event("screen_recording", 0)), "192.0.2.46:4321"); unknown.Code != http.StatusBadRequest {
t.Fatalf("unknown signal kind = %d %s, want 400", unknown.Code, unknown.Body.String())
}
if kinds := countRows(t, ctx, harness, "SELECT count(DISTINCT kind) FROM assessment_signal_events WHERE attempt_id = $1 AND kind IN ('screenshot_key', 'devtools_open')", attempt.ID); kinds != 2 {
t.Fatalf("stored capture kinds = %d, want both", kinds)
}
// The band: three User-Agents, two screenshot keys, and open developer tools
// are only weak signals, so the band is attention and never review.
worker := reviewJobWorker(t, harness, reviewFarFuture, 10)
runReviewJobs(ctx, t, worker)
var band string
var reasons []string
var extraAgents, screenshotKeys, devtoolsOpens int32
if err := harness.pool.QueryRow(ctx, `SELECT band, reasons, extra_agents, client_screenshot_keys, client_devtools_opens
FROM assessment_attempt_reviews WHERE attempt_id = $1`, attempt.ID).Scan(&band, &reasons, &extraAgents, &screenshotKeys, &devtoolsOpens); err != nil {
t.Fatalf("read the review: %v", err)
}
if band != string(domain.AssessmentReviewBandAttention) || extraAgents != 2 || screenshotKeys != 2 || devtoolsOpens != 1 {
t.Fatalf("review = band %s, %d extra agents, %d screenshot keys, %d detections; want attention, 2, 2, 1", band, extraAgents, screenshotKeys, devtoolsOpens)
}
for _, reason := range []string{string(domain.AssessmentReviewReasonExtraAgents), string(domain.AssessmentReviewReasonClientSignals)} {
found := false
for _, got := range reasons {
found = found || got == reason
}
if !found {
t.Fatalf("review reasons = %v, want %s among them", reasons, reason)
}
}
}
func countRows(t *testing.T, ctx context.Context, harness *assessmentAttemptHTTPHarness, query string, args ...any) int64 {
t.Helper()
var count int64
if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil {
t.Fatalf("count rows (%s): %v", query, err)
}
return count
}
@@ -105,16 +105,18 @@ func Execute(ctx context.Context, command Command, operator Operator, output io.
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"+
"answered_items: %d\nfast_answers: %d\ndeviating_answers: %d\nparallel_alternations: %d\nextra_networks: %d\nextra_agents: %d\n"+
"matched_integer_items: %d\nmatched_sequence_items: %d\nduplicate_evidence_bits: %d\n"+
"client_focus_loss_ms: %d\nclient_clipboard_events: %d\nclient_fullscreen_exits: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged\n",
"client_screenshot_keys: %d\nclient_devtools_opens: %d\n"+
"note: a hint for a manual check; it changes no result, category, or quota, and browser signals can be forged; "+
"a screenshot or a phone photo cannot be prevented or seen by the page\n",
review.AttemptID, review.Outcome.Band, strings.Join(reasons, ","), review.PolicyVersion,
review.EvaluatedAt.UTC().Format(time.RFC3339), review.UpdatedAt.UTC().Format(time.RFC3339),
measures.AnsweredItems, measures.FastAnswers, measures.DeviatingAnswers, measures.ParallelAlternations,
measures.ExtraNetworks, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.ExtraNetworks, measures.ExtraAgents, measures.MatchedIntegerItems, measures.MatchedSequenceItems,
measures.DuplicateEvidenceBits, measures.ClientFocusLossMS, measures.ClientClipboardEvents,
measures.ClientFullscreenExits,
measures.ClientFullscreenExits, measures.ClientScreenshotKeys, measures.ClientDevtoolsOpens,
); err != nil {
return errors.New("could not write the review")
}
@@ -8147,6 +8147,253 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
}
}
// handleHoldMyAssessmentWorkSessionRequest handles HoldMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page
// at a time. The page that works on the attempt calls this operation when the candidate starts or
// resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until
// `held_until`.
//
// - If nobody holds the work session, the previous holder released it, or its hold expired, the page
// becomes the holder and the answer is 200.
// - If the same page holds it, the hold is renewed and the answer is 200.
// - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page
// is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops
// renewing and its hold expires. The client tells the candidate that the attempt is open in another
// window and does not show the task.
//
// The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no
// protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a
// candidate who closes a page, reloads, or opens the attempt on another device can continue when the
// hold is released or has expired (at most two minutes after the last renewal). It is not a security
// boundary: a client that never calls this operation is refused only while another page holds the
// session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound
// to the attempt; it never stores or returns either value. A change of the User-Agent digest during an
// attempt is a weak server signal for a manual review, never an automatic decision.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the hold (409 state_conflict).
//
// PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (s *Server) handleHoldMyAssessmentWorkSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("HoldMyAssessmentWorkSession"),
semconv.HTTPRequestMethodKey.String("PUT"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/work-session"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), HoldMyAssessmentWorkSessionOperation,
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: HoldMyAssessmentWorkSessionOperation,
ID: "HoldMyAssessmentWorkSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, HoldMyAssessmentWorkSessionOperation, 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, HoldMyAssessmentWorkSessionOperation, 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
}
}
params, err := decodeHoldMyAssessmentWorkSessionParams(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 HoldMyAssessmentWorkSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: HoldMyAssessmentWorkSessionOperation,
OperationSummary: "Hold the single active work session of a real assessment attempt for this page.",
OperationID: "HoldMyAssessmentWorkSession",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
type (
Request = struct{}
Params = HoldMyAssessmentWorkSessionParams
Response = HoldMyAssessmentWorkSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackHoldMyAssessmentWorkSessionParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.HoldMyAssessmentWorkSession(ctx, params)
return response, err
},
)
} else {
response, err = s.h.HoldMyAssessmentWorkSession(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 := encodeHoldMyAssessmentWorkSessionResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyAssessmentResultsRequest handles ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
@@ -12599,6 +12846,237 @@ func (s *Server) handleRegisterAccountRequest(args [0]string, argsEscaped bool,
}
}
// handleReleaseMyAssessmentWorkSessionRequest handles ReleaseMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can
// open the attempt in another window at once instead of waiting for the hold to expire. The request is
// idempotent and reveals nothing: it answers 204 whether this page held the session, another page
// holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a
// lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the release (204).
//
// DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (s *Server) handleReleaseMyAssessmentWorkSessionRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ReleaseMyAssessmentWorkSession"),
semconv.HTTPRequestMethodKey.String("DELETE"),
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/work-session"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ReleaseMyAssessmentWorkSessionOperation,
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: ReleaseMyAssessmentWorkSessionOperation,
ID: "ReleaseMyAssessmentWorkSession",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ReleaseMyAssessmentWorkSessionOperation, 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, ReleaseMyAssessmentWorkSessionOperation, 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
}
}
params, err := decodeReleaseMyAssessmentWorkSessionParams(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 ReleaseMyAssessmentWorkSessionRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ReleaseMyAssessmentWorkSessionOperation,
OperationSummary: "Release the work session that this page holds.",
OperationID: "ReleaseMyAssessmentWorkSession",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "attempt_id",
In: "path",
}: params.AttemptID,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
type (
Request = struct{}
Params = ReleaseMyAssessmentWorkSessionParams
Response = ReleaseMyAssessmentWorkSessionRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackReleaseMyAssessmentWorkSessionParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ReleaseMyAssessmentWorkSession(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ReleaseMyAssessmentWorkSession(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 := encodeReleaseMyAssessmentWorkSessionResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleRequestMyAccountDeletionRequest handles RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
@@ -15244,6 +15722,12 @@ func (s *Server) handleSetMySearchStatusRequest(args [0]string, argsEscaped bool
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in
// another window. That refusal is not stored under the Idempotency-Key, because it lasts only until
// the other page closes or stops renewing. A real attempt that nobody holds is not refused.
//
// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404
// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
@@ -15430,6 +15914,10 @@ func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, ar
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
@@ -15510,6 +15998,11 @@ func (s *Server) handleStartMyAssessmentAttemptSessionRequest(args [1]string, ar
// public examples are unlimited apart from the sandbox rate limit and never show hidden group results;
// they are planned as a separate operation.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not
// stored under the Idempotency-Key and is checked before the stored answer is replayed.
//
// Repeats and conflicts, per item:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
@@ -15723,6 +16216,10 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
{
Name: "X-Attempt-Client",
In: "header",
}: params.XAttemptClient,
},
Raw: r,
}
@@ -137,6 +137,10 @@ type HideOrganizationRes interface {
hideOrganizationRes()
}
type HoldMyAssessmentWorkSessionRes interface {
holdMyAssessmentWorkSessionRes()
}
type ListMyAssessmentResultsRes interface {
listMyAssessmentResultsRes()
}
@@ -217,6 +221,10 @@ type RegisterAccountRes interface {
registerAccountRes()
}
type ReleaseMyAssessmentWorkSessionRes interface {
releaseMyAssessmentWorkSessionRes()
}
type RequestMyAccountDeletionRes interface {
requestMyAccountDeletionRes()
}
@@ -2173,6 +2173,170 @@ func (s *AssessmentAvailability) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentCaptureSignal) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *AssessmentCaptureSignal) encodeFields(e *jx.Encoder) {
{
e.FieldStart("kind")
s.Kind.Encode(e)
}
{
e.FieldStart("item_instance_id")
s.ItemInstanceID.Encode(e)
}
{
e.FieldStart("occurred_at")
s.OccurredAt.Encode(e)
}
}
var jsonFieldsNameOfAssessmentCaptureSignal = [3]string{
0: "kind",
1: "item_instance_id",
2: "occurred_at",
}
// Decode decodes AssessmentCaptureSignal from json.
func (s *AssessmentCaptureSignal) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentCaptureSignal to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "kind":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.Kind.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"kind\"")
}
case "item_instance_id":
requiredBitSet[0] |= 1 << 1
if err := func() error {
if err := s.ItemInstanceID.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"item_instance_id\"")
}
case "occurred_at":
requiredBitSet[0] |= 1 << 2
if err := func() error {
if err := s.OccurredAt.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"occurred_at\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode AssessmentCaptureSignal")
}
// 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(jsonFieldsNameOfAssessmentCaptureSignal) {
name = jsonFieldsNameOfAssessmentCaptureSignal[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 *AssessmentCaptureSignal) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentCaptureSignal) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes AssessmentCaptureSignalKind as json.
func (s AssessmentCaptureSignalKind) Encode(e *jx.Encoder) {
e.Str(string(s))
}
// Decode decodes AssessmentCaptureSignalKind from json.
func (s *AssessmentCaptureSignalKind) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentCaptureSignalKind to nil")
}
v, err := d.StrBytes()
if err != nil {
return err
}
// Try to use constant string.
switch AssessmentCaptureSignalKind(v) {
case AssessmentCaptureSignalKindScreenshotKey:
*s = AssessmentCaptureSignalKindScreenshotKey
case AssessmentCaptureSignalKindDevtoolsOpen:
*s = AssessmentCaptureSignalKindDevtoolsOpen
default:
*s = AssessmentCaptureSignalKind(v)
}
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s AssessmentCaptureSignalKind) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentCaptureSignalKind) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentCategoryDecisionView) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -9878,6 +10042,26 @@ func (s AssessmentSignalEvent) encodeFields(e *jx.Encoder) {
s.OccurredAt.Encode(e)
}
}
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
switch s.Type {
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent:
e.FieldStart("kind")
e.Str("devtools_open")
case AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
e.FieldStart("kind")
e.Str("screenshot_key")
}
{
s := s.AssessmentCaptureSignal
{
e.FieldStart("item_instance_id")
s.ItemInstanceID.Encode(e)
}
{
e.FieldStart("occurred_at")
s.OccurredAt.Encode(e)
}
}
}
}
@@ -9919,6 +10103,12 @@ func (s *AssessmentSignalEvent) Decode(d *jx.Decoder) error {
case "fullscreen_exit":
s.Type = AssessmentFullscreenExitSignalAssessmentSignalEvent
found = true
case "devtools_open":
s.Type = AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent
found = true
case "screenshot_key":
s.Type = AssessmentSignalEventScreenshotKeyAssessmentSignalEvent
found = true
default:
return errors.Errorf("unknown type %s", typ)
}
@@ -9945,6 +10135,10 @@ func (s *AssessmentSignalEvent) Decode(d *jx.Decoder) error {
if err := s.AssessmentFullscreenExitSignal.Decode(d); err != nil {
return err
}
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
if err := s.AssessmentCaptureSignal.Decode(d); err != nil {
return err
}
default:
return errors.Errorf("inferred invalid type: %s", s.Type)
}
@@ -11003,6 +11197,117 @@ func (s *AssessmentWatermark) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *AssessmentWorkSession) Encode(e *jx.Encoder) {
e.ObjStart()
s.encodeFields(e)
e.ObjEnd()
}
// encodeFields encodes fields.
func (s *AssessmentWorkSession) encodeFields(e *jx.Encoder) {
{
e.FieldStart("held_until")
s.HeldUntil.Encode(e)
}
{
e.FieldStart("renew_after_seconds")
e.Int32(s.RenewAfterSeconds)
}
}
var jsonFieldsNameOfAssessmentWorkSession = [2]string{
0: "held_until",
1: "renew_after_seconds",
}
// Decode decodes AssessmentWorkSession from json.
func (s *AssessmentWorkSession) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode AssessmentWorkSession to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "held_until":
requiredBitSet[0] |= 1 << 0
if err := func() error {
if err := s.HeldUntil.Decode(d); err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"held_until\"")
}
case "renew_after_seconds":
requiredBitSet[0] |= 1 << 1
if err := func() error {
v, err := d.Int32()
s.RenewAfterSeconds = int32(v)
if err != nil {
return err
}
return nil
}(); err != nil {
return errors.Wrap(err, "decode field \"renew_after_seconds\"")
}
default:
return errors.Errorf("unexpected field %q", k)
}
return nil
}); err != nil {
return errors.Wrap(err, "decode AssessmentWorkSession")
}
// 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(jsonFieldsNameOfAssessmentWorkSession) {
name = jsonFieldsNameOfAssessmentWorkSession[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 *AssessmentWorkSession) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *AssessmentWorkSession) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *BasicScore) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -24455,6 +24760,196 @@ func (s *HideOrganizationUnauthorized) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionBadRequest as json.
func (s *HoldMyAssessmentWorkSessionBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionBadRequest from json.
func (s *HoldMyAssessmentWorkSessionBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionBadRequest 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 = HoldMyAssessmentWorkSessionBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionConflict as json.
func (s *HoldMyAssessmentWorkSessionConflict) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionConflict from json.
func (s *HoldMyAssessmentWorkSessionConflict) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionConflict 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 = HoldMyAssessmentWorkSessionConflict(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionConflict) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionConflict) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionForbidden as json.
func (s *HoldMyAssessmentWorkSessionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionForbidden from json.
func (s *HoldMyAssessmentWorkSessionForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionForbidden 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 = HoldMyAssessmentWorkSessionForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionNotFound as json.
func (s *HoldMyAssessmentWorkSessionNotFound) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionNotFound from json.
func (s *HoldMyAssessmentWorkSessionNotFound) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionNotFound 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 = HoldMyAssessmentWorkSessionNotFound(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionNotFound) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionNotFound) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes HoldMyAssessmentWorkSessionUnauthorized as json.
func (s *HoldMyAssessmentWorkSessionUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes HoldMyAssessmentWorkSessionUnauthorized from json.
func (s *HoldMyAssessmentWorkSessionUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode HoldMyAssessmentWorkSessionUnauthorized 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 = HoldMyAssessmentWorkSessionUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *HoldMyAssessmentWorkSessionUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *HoldMyAssessmentWorkSessionUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode implements json.Marshaler.
func (s *IdentityRequestAccepted) Encode(e *jx.Encoder) {
e.ObjStart()
@@ -57146,6 +57641,158 @@ func (s *RegistrationRequest) UnmarshalJSON(data []byte) error {
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionBadRequest as json.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionBadRequest from json.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionBadRequest 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 = ReleaseMyAssessmentWorkSessionBadRequest(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionBadRequest) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionForbidden as json.
func (s *ReleaseMyAssessmentWorkSessionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionForbidden from json.
func (s *ReleaseMyAssessmentWorkSessionForbidden) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionForbidden 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 = ReleaseMyAssessmentWorkSessionForbidden(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionForbidden) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionForbidden) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionNotFound as json.
func (s *ReleaseMyAssessmentWorkSessionNotFound) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionNotFound from json.
func (s *ReleaseMyAssessmentWorkSessionNotFound) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionNotFound 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 = ReleaseMyAssessmentWorkSessionNotFound(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionNotFound) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionNotFound) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes ReleaseMyAssessmentWorkSessionUnauthorized as json.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
unwrapped.Encode(e)
}
// Decode decodes ReleaseMyAssessmentWorkSessionUnauthorized from json.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode ReleaseMyAssessmentWorkSessionUnauthorized 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 = ReleaseMyAssessmentWorkSessionUnauthorized(unwrapped)
return nil
}
// MarshalJSON implements stdjson.Marshaler.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) MarshalJSON() ([]byte, error) {
e := jx.Encoder{}
s.Encode(&e)
return e.Bytes(), nil
}
// UnmarshalJSON implements stdjson.Unmarshaler.
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) UnmarshalJSON(data []byte) error {
d := jx.DecodeBytes(data)
return s.Decode(d)
}
// Encode encodes RequestMyAccountDeletionForbidden as json.
func (s *RequestMyAccountDeletionForbidden) Encode(e *jx.Encoder) {
unwrapped := (*Problem)(s)
@@ -42,6 +42,7 @@ const (
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
GrantMyConsentOperation OperationName = "GrantMyConsent"
HideOrganizationOperation OperationName = "HideOrganization"
HoldMyAssessmentWorkSessionOperation OperationName = "HoldMyAssessmentWorkSession"
ListMyAssessmentResultsOperation OperationName = "ListMyAssessmentResults"
ListMyCardAccessHistoryOperation OperationName = "ListMyCardAccessHistory"
ListMyConsentsOperation OperationName = "ListMyConsents"
@@ -62,6 +63,7 @@ const (
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
ReleaseMyAssessmentWorkSessionOperation OperationName = "ReleaseMyAssessmentWorkSession"
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
RequestMyRepositoryChecksOperation OperationName = "RequestMyRepositoryChecks"
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
@@ -2666,6 +2666,138 @@ func decodeHideOrganizationParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// HoldMyAssessmentWorkSessionParams is parameters of HoldMyAssessmentWorkSession operation.
type HoldMyAssessmentWorkSessionParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
AttemptID uuid.UUID
// The page identifier described at AttemptClient. It is required here because the operation exists to
// hold or release the work session of one page.
XAttemptClient string
}
func unpackHoldMyAssessmentWorkSessionParams(packed middleware.Parameters) (params HoldMyAssessmentWorkSessionParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
params.XAttemptClient = packed[key].(string)
}
return params
}
func decodeHoldMyAssessmentWorkSessionParams(args [1]string, argsEscaped bool, r *http.Request) (params HoldMyAssessmentWorkSessionParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode path: attempt_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "attempt_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.AttemptID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "attempt_id",
In: "path",
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.XAttemptClient = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.XAttemptClient)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
// ListMyAssessmentResultsParams is parameters of ListMyAssessmentResults operation.
type ListMyAssessmentResultsParams struct {
// Maximum number of results per page.
@@ -5833,6 +5965,138 @@ func decodeRegisterAccountParams(args [0]string, argsEscaped bool, r *http.Reque
return params, nil
}
// ReleaseMyAssessmentWorkSessionParams is parameters of ReleaseMyAssessmentWorkSession operation.
type ReleaseMyAssessmentWorkSessionParams struct {
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
AttemptID uuid.UUID
// The page identifier described at AttemptClient. It is required here because the operation exists to
// hold or release the work session of one page.
XAttemptClient string
}
func unpackReleaseMyAssessmentWorkSessionParams(packed middleware.Parameters) (params ReleaseMyAssessmentWorkSessionParams) {
{
key := middleware.ParameterKey{
Name: "attempt_id",
In: "path",
}
params.AttemptID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
params.XAttemptClient = packed[key].(string)
}
return params
}
func decodeReleaseMyAssessmentWorkSessionParams(args [1]string, argsEscaped bool, r *http.Request) (params ReleaseMyAssessmentWorkSessionParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode path: attempt_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "attempt_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.AttemptID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "attempt_id",
In: "path",
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.XAttemptClient = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.XAttemptClient)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
// RevokeMyConsentParams is parameters of RevokeMyConsent operation.
type RevokeMyConsentParams struct {
// Consent being revoked. C1 has a deletion-request operation and C4 requires an organization scope.
@@ -6274,6 +6538,15 @@ type StartMyAssessmentAttemptSessionParams struct {
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
// Random identifier that one open page of the assessment attempt generates when it loads and keeps
// until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single
// active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a
// one-way keyed digest bound to the attempt, never the value.
//
// A request that omits the header counts as one anonymous client. It is refused with 409
// `state_conflict` while another page holds the work session, and it is accepted while nobody does, so
// a client that predates the header keeps working until a page holds the session.
XAttemptClient OptString `json:",omitempty,omitzero"`
}
func unpackStartMyAssessmentAttemptSessionParams(packed middleware.Parameters) (params StartMyAssessmentAttemptSessionParams) {
@@ -6291,6 +6564,15 @@ func unpackStartMyAssessmentAttemptSessionParams(packed middleware.Parameters) (
}
params.IdempotencyKey = packed[key].(string)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
if v, ok := packed[key]; ok {
params.XAttemptClient = v.(OptString)
}
}
return params
}
@@ -6395,6 +6677,72 @@ func decodeStartMyAssessmentAttemptSessionParams(args [1]string, argsEscaped boo
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotXAttemptClientVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotXAttemptClientVal = c
return nil
}(); err != nil {
return err
}
params.XAttemptClient.SetTo(paramsDotXAttemptClientVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.XAttemptClient.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(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: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
@@ -6423,6 +6771,15 @@ type SubmitMyAssessmentAnswerParams struct {
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
// Random identifier that one open page of the assessment attempt generates when it loads and keeps
// until it closes, 16 to 64 characters of `A-Za-z0-9_-`. It names the page that holds the single
// active work session of the attempt (see HoldMyAssessmentWorkSession). The server keeps only a
// one-way keyed digest bound to the attempt, never the value.
//
// A request that omits the header counts as one anonymous client. It is refused with 409
// `state_conflict` while another page holds the work session, and it is accepted while nobody does, so
// a client that predates the header keeps working until a page holds the session.
XAttemptClient OptString `json:",omitempty,omitzero"`
}
func unpackSubmitMyAssessmentAnswerParams(packed middleware.Parameters) (params SubmitMyAssessmentAnswerParams) {
@@ -6440,6 +6797,15 @@ func unpackSubmitMyAssessmentAnswerParams(packed middleware.Parameters) (params
}
params.IdempotencyKey = packed[key].(string)
}
{
key := middleware.ParameterKey{
Name: "X-Attempt-Client",
In: "header",
}
if v, ok := packed[key]; ok {
params.XAttemptClient = v.(OptString)
}
}
return params
}
@@ -6544,6 +6910,72 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
Err: err,
}
}
// Decode header: X-Attempt-Client.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "X-Attempt-Client",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotXAttemptClientVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotXAttemptClientVal = c
return nil
}(); err != nil {
return err
}
params.XAttemptClient.SetTo(paramsDotXAttemptClientVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.XAttemptClient.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 16,
MinLengthSet: true,
MaxLength: 64,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(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: "X-Attempt-Client",
In: "header",
Err: err,
}
}
return params, nil
}
@@ -3122,6 +3122,101 @@ func encodeHideOrganizationResponse(response HideOrganizationRes, w http.Respons
}
}
func encodeHoldMyAssessmentWorkSessionResponse(response HoldMyAssessmentWorkSessionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentWorkSessionHeaders:
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 *HoldMyAssessmentWorkSessionBadRequest:
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 *HoldMyAssessmentWorkSessionUnauthorized:
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 *HoldMyAssessmentWorkSessionForbidden:
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 *HoldMyAssessmentWorkSessionNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *HoldMyAssessmentWorkSessionConflict:
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 encodeListMyAssessmentResultsResponse(response ListMyAssessmentResultsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *AssessmentResultHistoryPageHeaders:
@@ -4874,6 +4969,82 @@ func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseW
}
}
func encodeReleaseMyAssessmentWorkSessionResponse(response ReleaseMyAssessmentWorkSessionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ReleaseMyAssessmentWorkSessionNoContent:
// 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(204)
return nil
case *ReleaseMyAssessmentWorkSessionBadRequest:
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 *ReleaseMyAssessmentWorkSessionUnauthorized:
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 *ReleaseMyAssessmentWorkSessionForbidden:
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 *ReleaseMyAssessmentWorkSessionNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
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 encodeRequestMyAccountDeletionResponse(response RequestMyAccountDeletionRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *ConsentDeletionRequestHeaders:
@@ -11,7 +11,7 @@ import (
)
var (
rn85AllowedHeaders = map[string]string{
rn86AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
@@ -20,37 +20,41 @@ var (
rn10AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn80AllowedHeaders = map[string]string{
rn81AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn70AllowedHeaders = map[string]string{
rn71AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn28AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn82AllowedHeaders = map[string]string{
rn83AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn12AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
rn97AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token",
}
rn23AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn95AllowedHeaders = map[string]string{
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Attempt-Client,X-Csrf-Token",
}
rn80AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
rn58AllowedHeaders = map[string]string{
"DELETE": "X-Attempt-Client,X-Csrf-Token",
"PUT": "X-Attempt-Client,X-Csrf-Token",
}
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn87AllowedHeaders = map[string]string{
rn88AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn54AllowedHeaders = map[string]string{
@@ -66,26 +70,26 @@ var (
rn20AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn97AllowedHeaders = map[string]string{
rn98AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn73AllowedHeaders = map[string]string{
rn74AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn57AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn92AllowedHeaders = map[string]string{
rn93AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn93AllowedHeaders = map[string]string{
rn94AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn39AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn83AllowedHeaders = map[string]string{
rn84AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn40AllowedHeaders = map[string]string{
@@ -106,16 +110,16 @@ var (
rn47AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn78AllowedHeaders = map[string]string{
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn90AllowedHeaders = map[string]string{
rn91AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn98AllowedHeaders = map[string]string{
rn99AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn88AllowedHeaders = map[string]string{
rn89AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn19AllowedHeaders = map[string]string{
@@ -124,7 +128,7 @@ var (
rn50AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn76AllowedHeaders = map[string]string{
rn77AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
)
@@ -281,7 +285,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn85AllowedHeaders,
allowedHeaders: rn86AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -384,7 +388,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn80AllowedHeaders,
allowedHeaders: rn81AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -408,7 +412,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn70AllowedHeaders,
allowedHeaders: rn71AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -488,7 +492,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn82AllowedHeaders,
allowedHeaders: rn83AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -610,7 +614,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn96AllowedHeaders,
allowedHeaders: rn97AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -703,7 +707,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn95AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -730,7 +734,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn79AllowedHeaders,
allowedHeaders: rn80AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -741,6 +745,37 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'w': // Prefix: "work-session"
if l := len("work-session"); len(elem) >= l && elem[0:l] == "work-session" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "DELETE":
s.handleReleaseMyAssessmentWorkSessionRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
case "PUT":
s.handleHoldMyAssessmentWorkSessionRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE,PUT",
allowedHeaders: rn58AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
@@ -941,7 +976,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn87AllowedHeaders,
allowedHeaders: rn88AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1183,7 +1218,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn97AllowedHeaders,
allowedHeaders: rn98AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1261,7 +1296,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn73AllowedHeaders,
allowedHeaders: rn74AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1530,7 +1565,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn92AllowedHeaders,
allowedHeaders: rn93AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1557,7 +1592,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn93AllowedHeaders,
allowedHeaders: rn94AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1612,7 +1647,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn83AllowedHeaders,
allowedHeaders: rn84AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -2001,7 +2036,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn78AllowedHeaders,
allowedHeaders: rn79AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2029,7 +2064,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn90AllowedHeaders,
allowedHeaders: rn91AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2059,7 +2094,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn98AllowedHeaders,
allowedHeaders: rn99AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2092,7 +2127,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn88AllowedHeaders,
allowedHeaders: rn89AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -2253,7 +2288,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn76AllowedHeaders,
allowedHeaders: rn77AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -2953,6 +2988,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'w': // Prefix: "work-session"
if l := len("work-session"); len(elem) >= l && elem[0:l] == "work-session" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "DELETE":
r.name = ReleaseMyAssessmentWorkSessionOperation
r.summary = "Release the work session that this page holds."
r.operationID = "ReleaseMyAssessmentWorkSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/work-session"
r.args = args
r.count = 1
return r, true
case "PUT":
r.name = HoldMyAssessmentWorkSessionOperation
r.summary = "Hold the single active work session of a real assessment attempt for this page."
r.operationID = "HoldMyAssessmentWorkSession"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/work-session"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
@@ -1053,6 +1053,92 @@ func (s *AssessmentAvailabilityHeaders) SetResponse(val AssessmentAvailability)
func (*AssessmentAvailabilityHeaders) getMyAssessmentAvailabilityRes() {}
// A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination
// that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on
// macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer
// tools are open (a docked panel changes the window size, or the console reads an object). Both are
// weak: a browser does not see every screenshot, an operating system can take one without a key the
// page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They
// lead to attention in a manual review at most, never to a score change, and they carry no
// measurement.
// Ref: #/components/schemas/AssessmentCaptureSignal
type AssessmentCaptureSignal struct {
Kind AssessmentCaptureSignalKind `json:"kind"`
ItemInstanceID AssessmentItemId `json:"item_instance_id"`
OccurredAt Timestamp `json:"occurred_at"`
}
// GetKind returns the value of Kind.
func (s *AssessmentCaptureSignal) GetKind() AssessmentCaptureSignalKind {
return s.Kind
}
// GetItemInstanceID returns the value of ItemInstanceID.
func (s *AssessmentCaptureSignal) GetItemInstanceID() AssessmentItemId {
return s.ItemInstanceID
}
// GetOccurredAt returns the value of OccurredAt.
func (s *AssessmentCaptureSignal) GetOccurredAt() Timestamp {
return s.OccurredAt
}
// SetKind sets the value of Kind.
func (s *AssessmentCaptureSignal) SetKind(val AssessmentCaptureSignalKind) {
s.Kind = val
}
// SetItemInstanceID sets the value of ItemInstanceID.
func (s *AssessmentCaptureSignal) SetItemInstanceID(val AssessmentItemId) {
s.ItemInstanceID = val
}
// SetOccurredAt sets the value of OccurredAt.
func (s *AssessmentCaptureSignal) SetOccurredAt(val Timestamp) {
s.OccurredAt = val
}
type AssessmentCaptureSignalKind string
const (
AssessmentCaptureSignalKindScreenshotKey AssessmentCaptureSignalKind = "screenshot_key"
AssessmentCaptureSignalKindDevtoolsOpen AssessmentCaptureSignalKind = "devtools_open"
)
// AllValues returns all AssessmentCaptureSignalKind values.
func (AssessmentCaptureSignalKind) AllValues() []AssessmentCaptureSignalKind {
return []AssessmentCaptureSignalKind{
AssessmentCaptureSignalKindScreenshotKey,
AssessmentCaptureSignalKindDevtoolsOpen,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s AssessmentCaptureSignalKind) MarshalText() ([]byte, error) {
switch s {
case AssessmentCaptureSignalKindScreenshotKey:
return []byte(s), nil
case AssessmentCaptureSignalKindDevtoolsOpen:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *AssessmentCaptureSignalKind) UnmarshalText(data []byte) error {
switch AssessmentCaptureSignalKind(data) {
case AssessmentCaptureSignalKindScreenshotKey:
*s = AssessmentCaptureSignalKindScreenshotKey
return nil
case AssessmentCaptureSignalKindDevtoolsOpen:
*s = AssessmentCaptureSignalKindDevtoolsOpen
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// 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.
@@ -5118,6 +5204,7 @@ type AssessmentSignalEvent struct {
AssessmentFocusLossSignal AssessmentFocusLossSignal
AssessmentClipboardSignal AssessmentClipboardSignal
AssessmentFullscreenExitSignal AssessmentFullscreenExitSignal
AssessmentCaptureSignal AssessmentCaptureSignal
}
// AssessmentSignalEventType is oneOf type of AssessmentSignalEvent.
@@ -5125,11 +5212,13 @@ type AssessmentSignalEventType string
// Possible values for AssessmentSignalEventType.
const (
AssessmentFocusLossSignalAssessmentSignalEvent AssessmentSignalEventType = "focus_loss"
AssessmentSignalEventCopyAssessmentSignalEvent AssessmentSignalEventType = "copy"
AssessmentSignalEventCutAssessmentSignalEvent AssessmentSignalEventType = "cut"
AssessmentSignalEventPasteAssessmentSignalEvent AssessmentSignalEventType = "paste"
AssessmentFullscreenExitSignalAssessmentSignalEvent AssessmentSignalEventType = "fullscreen_exit"
AssessmentFocusLossSignalAssessmentSignalEvent AssessmentSignalEventType = "focus_loss"
AssessmentSignalEventCopyAssessmentSignalEvent AssessmentSignalEventType = "copy"
AssessmentSignalEventCutAssessmentSignalEvent AssessmentSignalEventType = "cut"
AssessmentSignalEventPasteAssessmentSignalEvent AssessmentSignalEventType = "paste"
AssessmentFullscreenExitSignalAssessmentSignalEvent AssessmentSignalEventType = "fullscreen_exit"
AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent AssessmentSignalEventType = "devtools_open"
AssessmentSignalEventScreenshotKeyAssessmentSignalEvent AssessmentSignalEventType = "screenshot_key"
)
// IsAssessmentFocusLossSignal reports whether AssessmentSignalEvent is AssessmentFocusLossSignal.
@@ -5152,6 +5241,16 @@ func (s AssessmentSignalEvent) IsAssessmentFullscreenExitSignal() bool {
return s.Type == AssessmentFullscreenExitSignalAssessmentSignalEvent
}
// IsAssessmentCaptureSignal reports whether AssessmentSignalEvent is AssessmentCaptureSignal.
func (s AssessmentSignalEvent) IsAssessmentCaptureSignal() bool {
switch s.Type {
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
return true
default:
return false
}
}
// SetAssessmentFocusLossSignal sets AssessmentSignalEvent to AssessmentFocusLossSignal.
func (s *AssessmentSignalEvent) SetAssessmentFocusLossSignal(v AssessmentFocusLossSignal) {
s.Type = AssessmentFocusLossSignalAssessmentSignalEvent
@@ -5233,6 +5332,38 @@ func NewAssessmentFullscreenExitSignalAssessmentSignalEvent(v AssessmentFullscre
return s
}
// SetAssessmentCaptureSignal sets AssessmentSignalEvent to AssessmentCaptureSignal.
// panics if `t` is not associated with AssessmentCaptureSignal
func (s *AssessmentSignalEvent) SetAssessmentCaptureSignal(t AssessmentSignalEventType, v AssessmentCaptureSignal) {
s.Type = t
s.AssessmentCaptureSignal = v
if !s.IsAssessmentCaptureSignal() {
panic(fmt.Errorf("invariant: %v is not AssessmentCaptureSignal", t))
}
}
// GetAssessmentCaptureSignal returns AssessmentCaptureSignal and true boolean if AssessmentSignalEvent is AssessmentCaptureSignal.
func (s AssessmentSignalEvent) GetAssessmentCaptureSignal() (v AssessmentCaptureSignal, ok bool) {
if !s.IsAssessmentCaptureSignal() {
return v, false
}
return s.AssessmentCaptureSignal, true
}
// NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentCaptureSignal.
func NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent(v AssessmentCaptureSignal) AssessmentSignalEvent {
var s AssessmentSignalEvent
s.SetAssessmentCaptureSignal(AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, v)
return s
}
// NewAssessmentSignalEventScreenshotKeyAssessmentSignalEvent returns new AssessmentSignalEvent from AssessmentCaptureSignal.
func NewAssessmentSignalEventScreenshotKeyAssessmentSignalEvent(v AssessmentCaptureSignal) AssessmentSignalEvent {
var s AssessmentSignalEvent
s.SetAssessmentCaptureSignal(AssessmentSignalEventScreenshotKeyAssessmentSignalEvent, v)
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
@@ -5668,6 +5799,64 @@ func (s *AssessmentWatermark) SetCode(val string) {
s.Code = val
}
// The work session of a real attempt that the calling page holds. It is a one-page-at-a-time rule for
// the attempt, not a score or a signal, and it changes no result.
// Ref: #/components/schemas/AssessmentWorkSession
type AssessmentWorkSession struct {
HeldUntil Timestamp `json:"held_until"`
// How often the page repeats the hold. It is well below the hold time, so a page whose timer is slowed
// down in the background still renews before its hold expires.
RenewAfterSeconds int32 `json:"renew_after_seconds"`
}
// GetHeldUntil returns the value of HeldUntil.
func (s *AssessmentWorkSession) GetHeldUntil() Timestamp {
return s.HeldUntil
}
// GetRenewAfterSeconds returns the value of RenewAfterSeconds.
func (s *AssessmentWorkSession) GetRenewAfterSeconds() int32 {
return s.RenewAfterSeconds
}
// SetHeldUntil sets the value of HeldUntil.
func (s *AssessmentWorkSession) SetHeldUntil(val Timestamp) {
s.HeldUntil = val
}
// SetRenewAfterSeconds sets the value of RenewAfterSeconds.
func (s *AssessmentWorkSession) SetRenewAfterSeconds(val int32) {
s.RenewAfterSeconds = val
}
// AssessmentWorkSessionHeaders wraps AssessmentWorkSession with response headers.
type AssessmentWorkSessionHeaders struct {
CacheControl CacheControlNoStore
Response AssessmentWorkSession
}
// GetCacheControl returns the value of CacheControl.
func (s *AssessmentWorkSessionHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *AssessmentWorkSessionHeaders) GetResponse() AssessmentWorkSession {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *AssessmentWorkSessionHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *AssessmentWorkSessionHeaders) SetResponse(val AssessmentWorkSession) {
s.Response = val
}
func (*AssessmentWorkSessionHeaders) holdMyAssessmentWorkSessionRes() {}
// Raw score of a demo_basic attempt and the pass mark of the recorded basic grading policy. The pass
// mark comes from that policy version and never from the handler.
// Ref: #/components/schemas/BasicScore
@@ -11245,6 +11434,26 @@ type HideOrganizationUnauthorized Problem
func (*HideOrganizationUnauthorized) hideOrganizationRes() {}
type HoldMyAssessmentWorkSessionBadRequest Problem
func (*HoldMyAssessmentWorkSessionBadRequest) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionConflict Problem
func (*HoldMyAssessmentWorkSessionConflict) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionForbidden Problem
func (*HoldMyAssessmentWorkSessionForbidden) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionNotFound Problem
func (*HoldMyAssessmentWorkSessionNotFound) holdMyAssessmentWorkSessionRes() {}
type HoldMyAssessmentWorkSessionUnauthorized Problem
func (*HoldMyAssessmentWorkSessionUnauthorized) holdMyAssessmentWorkSessionRes() {}
// Neutral acknowledgement. Its content is identical whether or not the address belongs to an account
// or is already verified, so the response does not enumerate accounts. The client tells the user to
// check the mailbox.
@@ -28930,6 +29139,39 @@ func (s *RegistrationRequest) SetConsentC1(val PersonalDataConsentAcceptance) {
s.ConsentC1 = val
}
type ReleaseMyAssessmentWorkSessionBadRequest Problem
func (*ReleaseMyAssessmentWorkSessionBadRequest) releaseMyAssessmentWorkSessionRes() {}
type ReleaseMyAssessmentWorkSessionForbidden Problem
func (*ReleaseMyAssessmentWorkSessionForbidden) releaseMyAssessmentWorkSessionRes() {}
// ReleaseMyAssessmentWorkSessionNoContent is response for ReleaseMyAssessmentWorkSession operation.
type ReleaseMyAssessmentWorkSessionNoContent struct {
CacheControl CacheControlNoStore
}
// GetCacheControl returns the value of CacheControl.
func (s *ReleaseMyAssessmentWorkSessionNoContent) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// SetCacheControl sets the value of CacheControl.
func (s *ReleaseMyAssessmentWorkSessionNoContent) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
func (*ReleaseMyAssessmentWorkSessionNoContent) releaseMyAssessmentWorkSessionRes() {}
type ReleaseMyAssessmentWorkSessionNotFound Problem
func (*ReleaseMyAssessmentWorkSessionNotFound) releaseMyAssessmentWorkSessionRes() {}
type ReleaseMyAssessmentWorkSessionUnauthorized Problem
func (*ReleaseMyAssessmentWorkSessionUnauthorized) releaseMyAssessmentWorkSessionRes() {}
type RequestMyAccountDeletionForbidden Problem
func (*RequestMyAccountDeletionForbidden) requestMyAccountDeletionRes() {}
@@ -87,6 +87,7 @@ var operationRolesSessionCookie = map[string][]string{
GetOrganizationNeedOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
HoldMyAssessmentWorkSessionOperation: []string{},
ListMyAssessmentResultsOperation: []string{},
ListMyCardAccessHistoryOperation: []string{},
ListMyConsentsOperation: []string{},
@@ -105,6 +106,7 @@ var operationRolesSessionCookie = map[string][]string{
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
ReleaseMyAssessmentWorkSessionOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RequestMyRepositoryChecksOperation: []string{},
RevokeMyConsentOperation: []string{},
@@ -160,11 +162,13 @@ var operationRolesSessionCsrf = map[string][]string{
FinalizeMyAssessmentAttemptOperation: []string{},
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
HoldMyAssessmentWorkSessionOperation: []string{},
LogoutOperation: []string{},
MarkMyNotificationReadOperation: []string{},
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
ReleaseMyAssessmentWorkSessionOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
RequestMyRepositoryChecksOperation: []string{},
RevokeMyConsentOperation: []string{},
@@ -1086,6 +1086,37 @@ type Handler interface {
//
// PUT /api/v1/me/privacy/hidden-organizations/{org_id}
HideOrganization(ctx context.Context, params HideOrganizationParams) (HideOrganizationRes, error)
// HoldMyAssessmentWorkSession implements HoldMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page
// at a time. The page that works on the attempt calls this operation when the candidate starts or
// resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until
// `held_until`.
//
// - If nobody holds the work session, the previous holder released it, or its hold expired, the page
// becomes the holder and the answer is 200.
// - If the same page holds it, the hold is renewed and the answer is 200.
// - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page
// is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops
// renewing and its hold expires. The client tells the candidate that the attempt is open in another
// window and does not show the task.
//
// The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no
// protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a
// candidate who closes a page, reloads, or opens the attempt on another device can continue when the
// hold is released or has expired (at most two minutes after the last renewal). It is not a security
// boundary: a client that never calls this operation is refused only while another page holds the
// session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound
// to the attempt; it never stores or returns either value. A change of the User-Agent digest during an
// attempt is a weak server signal for a manual review, never an automatic decision.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the hold (409 state_conflict).
//
// PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session
HoldMyAssessmentWorkSession(ctx context.Context, params HoldMyAssessmentWorkSessionParams) (HoldMyAssessmentWorkSessionRes, error)
// ListMyAssessmentResults implements ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
@@ -1546,6 +1577,21 @@ type Handler interface {
//
// POST /api/v1/identity/registrations
RegisterAccount(ctx context.Context, req *RegistrationRequest, params RegisterAccountParams) (RegisterAccountRes, error)
// ReleaseMyAssessmentWorkSession implements ReleaseMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can
// open the attempt in another window at once instead of waiting for the hold to expire. The request is
// idempotent and reveals nothing: it answers 204 whether this page held the session, another page
// holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a
// lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the release (204).
//
// DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session
ReleaseMyAssessmentWorkSession(ctx context.Context, params ReleaseMyAssessmentWorkSessionParams) (ReleaseMyAssessmentWorkSessionRes, error)
// RequestMyAccountDeletion implements RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
@@ -1915,6 +1961,12 @@ type Handler interface {
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in
// another window. That refusal is not stored under the Idempotency-Key, because it lasts only until
// the other page closes or stops renewing. A real attempt that nobody holds is not refused.
//
// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404
// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
@@ -1950,6 +2002,11 @@ type Handler interface {
// public examples are unlimited apart from the sandbox rate limit and never show hidden group results;
// they are planned as a separate operation.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not
// stored under the Idempotency-Key and is checked before the stored answer is replayed.
//
// Repeats and conflicts, per item:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
@@ -1199,6 +1199,40 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg
return r, ht.ErrNotImplemented
}
// HoldMyAssessmentWorkSession implements HoldMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page
// at a time. The page that works on the attempt calls this operation when the candidate starts or
// resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until
// `held_until`.
//
// - If nobody holds the work session, the previous holder released it, or its hold expired, the page
// becomes the holder and the answer is 200.
// - If the same page holds it, the hold is renewed and the answer is 200.
// - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page
// is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops
// renewing and its hold expires. The client tells the candidate that the attempt is open in another
// window and does not show the task.
//
// The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no
// protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a
// candidate who closes a page, reloads, or opens the attempt on another device can continue when the
// hold is released or has expired (at most two minutes after the last renewal). It is not a security
// boundary: a client that never calls this operation is refused only while another page holds the
// session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound
// to the attempt; it never stores or returns either value. A change of the User-Agent digest during an
// attempt is a weak server signal for a manual review, never an automatic decision.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the hold (409 state_conflict).
//
// PUT /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (UnimplementedHandler) HoldMyAssessmentWorkSession(ctx context.Context, params HoldMyAssessmentWorkSessionParams) (r HoldMyAssessmentWorkSessionRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMyAssessmentResults implements ListMyAssessmentResults operation.
//
// Requires a candidate session. Returns only completed root and corrective results owned by this
@@ -1719,6 +1753,24 @@ func (UnimplementedHandler) RegisterAccount(ctx context.Context, req *Registrati
return r, ht.ErrNotImplemented
}
// ReleaseMyAssessmentWorkSession implements ReleaseMyAssessmentWorkSession operation.
//
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the
// `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can
// open the attempt in another window at once instead of waiting for the hold to expire. The request is
// idempotent and reveals nothing: it answers 204 whether this page held the session, another page
// holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a
// lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of
// another candidate), then the release (204).
//
// DELETE /api/v1/me/assessment-attempts/{attempt_id}/work-session
func (UnimplementedHandler) ReleaseMyAssessmentWorkSession(ctx context.Context, params ReleaseMyAssessmentWorkSessionParams) (r ReleaseMyAssessmentWorkSessionRes, _ error) {
return r, ht.ErrNotImplemented
}
// RequestMyAccountDeletion implements RequestMyAccountDeletion operation.
//
// Requires a verified session, its CSRF token in X-CSRF-Token, and the exact configured Origin. The
@@ -2121,6 +2173,12 @@ func (UnimplementedHandler) SetMySearchStatus(ctx context.Context, req *SearchSt
// start a session or commit a due transition. A background transition may persist a due outcome
// independently; after that, this command returns the stored terminal attempt without changing it.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in
// another window. That refusal is not stored under the Idempotency-Key, because it lasts only until
// the other page closes or stops renewing. A real attempt that nobody holds is not refused.
//
// The attempt must belong to the candidate of the session. An attempt of another candidate answers 404
// not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no
// operation gives an employer answers, qualification evidence, or attempt history.
@@ -2159,6 +2217,11 @@ func (UnimplementedHandler) StartMyAssessmentAttemptSession(ctx context.Context,
// public examples are unlimited apart from the sandbox rate limit and never show hidden group results;
// they are planned as a separate operation.
//
// One page at a time. While another page holds the work session of this attempt
// (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers
// 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not
// stored under the Idempotency-Key and is checked before the stored answer is replayed.
//
// Repeats and conflicts, per item:
//
// - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
@@ -785,6 +785,40 @@ func (s *AssessmentAvailabilityHeaders) Validate() error {
return nil
}
func (s *AssessmentCaptureSignal) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Kind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "kind",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s AssessmentCaptureSignalKind) Validate() error {
switch s {
case "screenshot_key":
return nil
case "devtools_open":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *AssessmentCategoryDecisionView) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -4340,6 +4374,11 @@ func (s AssessmentSignalEvent) Validate() error {
return err
}
return nil
case AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent, AssessmentSignalEventScreenshotKeyAssessmentSignalEvent:
if err := s.AssessmentCaptureSignal.Validate(); err != nil {
return err
}
return nil
default:
return errors.Errorf("invalid type %q", s.Type)
}
@@ -4824,6 +4863,73 @@ func (s *AssessmentWatermark) Validate() error {
return nil
}
func (s *AssessmentWorkSession) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 3600,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(s.RenewAfterSeconds)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "renew_after_seconds",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *AssessmentWorkSessionHeaders) 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 *BasicScore) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -10603,6 +10709,46 @@ func (s *HideOrganizationUnauthorized) Validate() error {
return nil
}
func (s *HoldMyAssessmentWorkSessionBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionConflict) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *HoldMyAssessmentWorkSessionUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *IdentityRequestAccepted) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -22964,6 +23110,61 @@ func (s *RegistrationRequest) Validate() error {
return nil
}
func (s *ReleaseMyAssessmentWorkSessionBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionNoContent) 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 len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ReleaseMyAssessmentWorkSessionUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *RequestMyAccountDeletionForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -12,10 +12,15 @@ const SessionCookieName = "__Host-lincodex_session"
type sessionRequestMetadataKey struct{}
// maxUserAgentBytes bounds the User-Agent that is kept for the request. A
// browser sends a few hundred bytes; the rest is not a browser.
const maxUserAgentBytes = 512
type sessionRequestMetadata struct {
origin string
originValid bool
incomingToken domain.SecretToken
userAgent string
}
// SessionRequestMetadata records the browser Origin and an optional incoming
@@ -24,7 +29,7 @@ type sessionRequestMetadata struct {
func SessionRequestMetadata() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
metadata := sessionRequestMetadata{}
metadata := sessionRequestMetadata{userAgent: boundedUserAgent(r.Header.Get("User-Agent"))}
origins := r.Header.Values("Origin")
if len(origins) == 1 {
metadata.origin = origins[0]
@@ -55,6 +60,21 @@ func RequestOrigin(ctx context.Context) (string, bool) {
return metadata.origin, ok && metadata.originValid
}
// RequestUserAgent returns the User-Agent of the request, cut to a safe length,
// or an empty string when it had none. It exists to be hashed with a key into a
// signal of the attempt; callers never store or log it.
func RequestUserAgent(ctx context.Context) string {
metadata, _ := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata)
return metadata.userAgent
}
func boundedUserAgent(value string) string {
if len(value) > maxUserAgentBytes {
return value[:maxUserAgentBytes]
}
return value
}
// IncomingSessionToken returns a parsed token from exactly one session cookie.
// The zero value means missing, malformed, or duplicated input.
func IncomingSessionToken(ctx context.Context) domain.SecretToken {
@@ -3,6 +3,7 @@ package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"lincodex/backend/internal/domain"
@@ -94,3 +95,32 @@ func TestSessionCookieMatchesOnlyTheBoundaryToken(t *testing.T) {
t.Fatalf("SessionCookieMatches() = %v", matches)
}
}
func TestRequestUserAgentIsBoundedAndAbsentWithoutTheMiddleware(t *testing.T) {
var seen string
handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
seen = RequestUserAgent(request.Context())
}))
request := httptest.NewRequest(http.MethodGet, "/api/v1/me/assessment-attempts", nil)
request.Header.Set("User-Agent", "TestBrowser/1.0")
handler.ServeHTTP(httptest.NewRecorder(), request)
if seen != "TestBrowser/1.0" {
t.Fatalf("RequestUserAgent() = %q, want the header value", seen)
}
request = httptest.NewRequest(http.MethodGet, "/api/v1/me/assessment-attempts", nil)
request.Header.Set("User-Agent", strings.Repeat("A", 4*maxUserAgentBytes))
handler.ServeHTTP(httptest.NewRecorder(), request)
if len(seen) != maxUserAgentBytes {
t.Fatalf("RequestUserAgent() length = %d, want it cut to %d bytes", len(seen), maxUserAgentBytes)
}
request = httptest.NewRequest(http.MethodGet, "/api/v1/me/assessment-attempts", nil)
handler.ServeHTTP(httptest.NewRecorder(), request)
if seen != "" {
t.Fatalf("RequestUserAgent() = %q, want empty for a request without the header", seen)
}
if got := RequestUserAgent(request.Context()); got != "" {
t.Fatalf("RequestUserAgent() without the middleware = %q, want empty", got)
}
}
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math"
"time"
"github.com/google/uuid"
@@ -29,10 +30,18 @@ type AssessmentPresenter interface {
Present(snapshot domain.AssessmentAttemptPublicSnapshot) (domain.AssessmentAttemptPublicSnapshot, error)
}
// AssessmentWorkSessions holds and releases the single active work session of a
// real attempt for the open page that calls.
type AssessmentWorkSessions interface {
Hold(ctx context.Context, command assessmentusecase.HoldWorkSessionCommand) (assessmentusecase.WorkSessionHold, error)
Release(ctx context.Context, command assessmentusecase.ReleaseWorkSessionCommand) error
}
// AssessmentHandler serves the candidate's frozen assessment attempts.
type AssessmentHandler struct {
operations AssessmentOperations
presenter AssessmentPresenter
operations AssessmentOperations
presenter AssessmentPresenter
workSessions AssessmentWorkSessions
}
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
@@ -49,6 +58,13 @@ func (handler *AssessmentHandler) WithPresenter(presenter AssessmentPresenter) *
return handler
}
// WithWorkSessions enables the hold and release operations of the work session.
// Without it they answer as not implemented.
func (handler *AssessmentHandler) WithWorkSessions(sessions AssessmentWorkSessions) *AssessmentHandler {
handler.workSessions = sessions
return handler
}
// attemptResponse presents the snapshot and maps it to the response. Every
// operation that returns an attempt goes through it.
func (handler *AssessmentHandler) attemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
@@ -114,6 +130,26 @@ func (handler *Handler) SubmitMyAssessmentAnswer(
return handler.assessment.SubmitMyAssessmentAnswer(ctx, request, params)
}
func (handler *Handler) HoldMyAssessmentWorkSession(
ctx context.Context,
params api.HoldMyAssessmentWorkSessionParams,
) (api.HoldMyAssessmentWorkSessionRes, error) {
if handler.assessment == nil || handler.assessment.workSessions == nil {
return handler.UnimplementedHandler.HoldMyAssessmentWorkSession(ctx, params)
}
return handler.assessment.HoldMyAssessmentWorkSession(ctx, params)
}
func (handler *Handler) ReleaseMyAssessmentWorkSession(
ctx context.Context,
params api.ReleaseMyAssessmentWorkSessionParams,
) (api.ReleaseMyAssessmentWorkSessionRes, error) {
if handler.assessment == nil || handler.assessment.workSessions == nil {
return handler.UnimplementedHandler.ReleaseMyAssessmentWorkSession(ctx, params)
}
return handler.assessment.ReleaseMyAssessmentWorkSession(ctx, params)
}
func (handler *Handler) FinalizeMyAssessmentAttempt(
ctx context.Context,
request *api.AssessmentFinalization,
@@ -199,6 +235,7 @@ func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
result, err := handler.operations.StartSession(ctx, assessmentusecase.StartAttemptSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
Client: params.XAttemptClient.Or(""),
})
if err != nil {
return assessmentSessionFailure(ctx, err)
@@ -236,6 +273,7 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion),
IdempotencyKey: params.IdempotencyKey, Answer: answer, Origin: assessmentRequestOrigin(ctx),
Client: params.XAttemptClient.Or(""),
})
if err != nil {
return assessmentAnswerFailure(ctx, err)
@@ -250,6 +288,46 @@ func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
}
func (handler *AssessmentHandler) HoldMyAssessmentWorkSession(
ctx context.Context,
params api.HoldMyAssessmentWorkSessionParams,
) (api.HoldMyAssessmentWorkSessionRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.HoldMyAssessmentWorkSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
hold, err := handler.workSessions.Hold(ctx, assessmentusecase.HoldWorkSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
Client: params.XAttemptClient, Origin: assessmentRequestOrigin(ctx),
})
if err != nil {
return assessmentHoldFailure(ctx, err)
}
return &api.AssessmentWorkSessionHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.AssessmentWorkSession{
HeldUntil: api.Timestamp(hold.HeldUntil), RenewAfterSeconds: int32(math.Ceil(hold.RenewEvery.Seconds())),
},
}, nil
}
func (handler *AssessmentHandler) ReleaseMyAssessmentWorkSession(
ctx context.Context,
params api.ReleaseMyAssessmentWorkSessionParams,
) (api.ReleaseMyAssessmentWorkSessionRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ReleaseMyAssessmentWorkSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
err := handler.workSessions.Release(ctx, assessmentusecase.ReleaseWorkSessionCommand{
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID), Client: params.XAttemptClient,
})
if err != nil {
return assessmentReleaseFailure(ctx, err)
}
return &api.ReleaseMyAssessmentWorkSessionNoContent{CacheControl: api.CacheControlNoStoreNoStore}, nil
}
func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
ctx context.Context,
request *api.AssessmentFinalization,
@@ -407,6 +485,8 @@ func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssess
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
return (*api.StartMyAssessmentAttemptSessionPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptWorkSessionBusy):
return (*api.StartMyAssessmentAttemptSessionConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.StartMyAssessmentAttemptSessionUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
@@ -418,6 +498,35 @@ func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssess
}
}
func assessmentHoldFailure(ctx context.Context, err error) (api.HoldMyAssessmentWorkSessionRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
return (*api.HoldMyAssessmentWorkSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.HoldMyAssessmentWorkSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptWorkSessionBusy), errors.Is(err, assessmentusecase.ErrAttemptWorkSessionState):
return (*api.HoldMyAssessmentWorkSessionConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidWorkSessionClient):
return (*api.HoldMyAssessmentWorkSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/X-Attempt-Client").Response), nil
default:
return nil, err
}
}
func assessmentReleaseFailure(ctx context.Context, err error) (api.ReleaseMyAssessmentWorkSessionRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
return (*api.ReleaseMyAssessmentWorkSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
return (*api.ReleaseMyAssessmentWorkSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, assessmentusecase.ErrInvalidWorkSessionClient):
return (*api.ReleaseMyAssessmentWorkSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/X-Attempt-Client").Response), nil
default:
return nil, err
}
}
func assessmentAnswerFailure(ctx context.Context, err error) (api.SubmitMyAssessmentAnswerRes, error) {
switch {
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
@@ -428,7 +537,7 @@ func assessmentAnswerFailure(ctx context.Context, err error) (api.SubmitMyAssess
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
return (*api.SubmitMyAssessmentAnswerPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict), errors.Is(err, assessmentusecase.ErrAttemptWorkSessionBusy):
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
return (*api.SubmitMyAssessmentAnswerUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
@@ -3,16 +3,19 @@ package v1
import (
"context"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
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.
// assessmentRequestOrigin hands the authenticated session, the limiter key of
// the client address, and the User-Agent to the server signals. The usecase
// turns them into keyed digests; no 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)}
return assessmentusecase.RequestOrigin{
SessionID: session.SessionID, ClientKey: clientKey(ctx), UserAgent: httpmiddleware.RequestUserAgent(ctx),
}
}
@@ -105,6 +105,9 @@ func assessmentSignalEventInput(requestEvent api.AssessmentSignalEvent) (domain.
return assessmentClipboardInput(requestEvent)
case api.AssessmentFullscreenExitSignalAssessmentSignalEvent:
return assessmentFullscreenExitInput(requestEvent)
case api.AssessmentSignalEventScreenshotKeyAssessmentSignalEvent,
api.AssessmentSignalEventDevtoolsOpenAssessmentSignalEvent:
return assessmentCaptureInput(requestEvent)
default:
return domain.AssessmentSignalEventInput{}, false
}
@@ -149,6 +152,20 @@ func assessmentFullscreenExitInput(requestEvent api.AssessmentSignalEvent) (doma
}, true
}
func assessmentCaptureInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
value, ok := requestEvent.GetAssessmentCaptureSignal()
if !ok {
return domain.AssessmentSignalEventInput{}, false
}
kind := domain.AssessmentSignalKind(value.Kind)
if kind != domain.AssessmentSignalKind(requestEvent.Type) {
return domain.AssessmentSignalEventInput{}, false
}
return domain.AssessmentSignalEventInput{
Kind: kind, ItemInstanceID: uuid.UUID(value.ItemInstanceID), OccurredAt: time.Time(value.OccurredAt),
}, true
}
func signalInvalidBody(ctx context.Context) *api.RecordMyAssessmentAttemptSignalsBadRequest {
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response,
@@ -55,8 +55,14 @@ func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: at,
}),
api.NewAssessmentSignalEventScreenshotKeyAssessmentSignalEvent(api.AssessmentCaptureSignal{
Kind: api.AssessmentCaptureSignalKindScreenshotKey, ItemInstanceID: api.AssessmentItemId(itemID), OccurredAt: at,
}),
api.NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent(api.AssessmentCaptureSignal{
Kind: api.AssessmentCaptureSignalKindDevtoolsOpen, ItemInstanceID: api.AssessmentItemId(itemID), OccurredAt: at,
}),
}}
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 5, time.Now())
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 7, time.Now())
if err != nil {
t.Fatalf("NewAssessmentSignalReceipt() error = %v", err)
}
@@ -71,18 +77,19 @@ func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
if !ok {
t.Fatalf("RecordMyAssessmentAttemptSignals() result = %T, want receipt headers", result)
}
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 5 ||
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 7 ||
response.Response.Status != api.AssessmentSignalReceiptStatusAccepted {
t.Fatalf("receipt response = %+v", response)
}
command := operations.command
if operations.calls != 1 || command.ActorID != actorID || command.AttemptID != domain.AssessmentAttemptID(attemptID) ||
command.IdempotencyKey != "event-batch" || len(command.Events) != 5 {
command.IdempotencyKey != "event-batch" || len(command.Events) != 7 {
t.Fatalf("record command = %+v, calls %d", command, operations.calls)
}
wantKinds := []domain.AssessmentSignalKind{
domain.AssessmentSignalFocusLoss, domain.AssessmentSignalCopy, domain.AssessmentSignalPaste,
domain.AssessmentSignalCut, domain.AssessmentSignalFullscreenExit,
domain.AssessmentSignalScreenshotKey, domain.AssessmentSignalDevtoolsOpen,
}
for index, event := range command.Events {
if event.Kind() != wantKinds[index] || event.ItemInstanceID() != itemID || !event.OccurredAt().Equal(time.Time(at)) {
@@ -99,6 +106,25 @@ func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
}
}
func TestAssessmentSignalHandlerRefusesACaptureEventWhoseKindDisagreesWithItsVariant(t *testing.T) {
itemID := uuid.New()
mismatched := api.NewAssessmentSignalEventDevtoolsOpenAssessmentSignalEvent(api.AssessmentCaptureSignal{
Kind: api.AssessmentCaptureSignalKindScreenshotKey, ItemInstanceID: api.AssessmentItemId(itemID),
OccurredAt: api.Timestamp(time.Now().UTC()),
})
operations := &assessmentSignalOperationsStub{}
handler := NewAssessmentSignalHandler(operations)
result, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()),
&api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{mismatched}},
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "mismatch"})
if err != nil {
t.Fatalf("RecordMyAssessmentAttemptSignals() error = %v", err)
}
if _, ok := result.(*api.RecordMyAssessmentAttemptSignalsBadRequest); !ok || operations.calls != 0 {
t.Fatalf("mismatched capture event result = %T, calls %d, want a 400 before the usecase", result, operations.calls)
}
}
func TestAssessmentSignalHandlerMapsAuthorizationAndBusinessProblems(t *testing.T) {
for _, testCase := range []struct {
name string
@@ -3,6 +3,7 @@ package v1
import (
"context"
"errors"
"strings"
"testing"
"time"
@@ -305,3 +306,150 @@ func TestAPresenterFailureIsAServerErrorNotAnUnmarkedAttempt(t *testing.T) {
t.Fatal("GetMyAssessmentAttempt() succeeded, want an error so that the task text is never served unmarked")
}
}
type workSessionsStub struct {
holdCommand assessmentusecase.HoldWorkSessionCommand
hold assessmentusecase.WorkSessionHold
holdErr error
releaseCommand assessmentusecase.ReleaseWorkSessionCommand
releaseErr error
}
func (stub *workSessionsStub) Hold(_ context.Context, command assessmentusecase.HoldWorkSessionCommand) (assessmentusecase.WorkSessionHold, error) {
stub.holdCommand = command
return stub.hold, stub.holdErr
}
func (stub *workSessionsStub) Release(_ context.Context, command assessmentusecase.ReleaseWorkSessionCommand) error {
stub.releaseCommand = command
return stub.releaseErr
}
const testPageClient = "page-one-AAAAAAAAAAAAAAAA"
func TestHoldWorkSessionAnswersTheLeaseWithoutTheClientIdentifier(t *testing.T) {
userID, attemptID := uuid.New(), uuid.New()
until := time.Date(2026, time.October, 11, 9, 2, 0, 0, time.UTC)
stub := &workSessionsStub{hold: assessmentusecase.WorkSessionHold{HeldUntil: until, RenewEvery: 15 * time.Second}}
handler := NewAssessmentHandler(&assessmentOperationsStub{}).WithWorkSessions(stub)
response, err := handler.HoldMyAssessmentWorkSession(principalForTest(userID),
api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if err != nil {
t.Fatalf("HoldMyAssessmentWorkSession() error = %v", err)
}
headers, ok := response.(*api.AssessmentWorkSessionHeaders)
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore ||
!time.Time(headers.Response.HeldUntil).Equal(until) || headers.Response.RenewAfterSeconds != 15 {
t.Fatalf("hold response = %T %+v, want a no-store lease that ends at %s", response, response, until)
}
if stub.holdCommand.ActorID != userID || stub.holdCommand.AttemptID != domain.AssessmentAttemptID(attemptID) || stub.holdCommand.Client != testPageClient {
t.Fatalf("hold command = %+v, want the verified principal, the attempt, and the page identifier", stub.holdCommand)
}
encoded, err := headers.Response.MarshalJSON()
if err != nil || strings.Contains(string(encoded), testPageClient) {
t.Fatalf("the response %s repeats the page identifier (error %v)", encoded, err)
}
}
func TestHoldAndReleaseWorkSessionMapTheirFailures(t *testing.T) {
attemptID := uuid.New()
stub := &workSessionsStub{}
handler := NewAssessmentHandler(&assessmentOperationsStub{}).WithWorkSessions(stub)
hold := func(err error) api.HoldMyAssessmentWorkSessionRes {
t.Helper()
stub.holdErr = err
response, handleErr := handler.HoldMyAssessmentWorkSession(principalForTest(uuid.New()),
api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if handleErr != nil {
t.Fatalf("HoldMyAssessmentWorkSession(%v) error = %v", err, handleErr)
}
return response
}
if _, ok := hold(assessmentusecase.ErrAttemptWorkSessionBusy).(*api.HoldMyAssessmentWorkSessionConflict); !ok {
t.Fatal("a held session did not answer 409")
}
if _, ok := hold(assessmentusecase.ErrAttemptWorkSessionState).(*api.HoldMyAssessmentWorkSessionConflict); !ok {
t.Fatal("an attempt with no work session did not answer 409")
}
if _, ok := hold(assessmentusecase.ErrAttemptNotFound).(*api.HoldMyAssessmentWorkSessionNotFound); !ok {
t.Fatal("an unknown attempt did not answer 404")
}
if _, ok := hold(assessmentusecase.ErrAttemptConsentRequired).(*api.HoldMyAssessmentWorkSessionForbidden); !ok {
t.Fatal("a missing consent did not answer 403")
}
if _, ok := hold(assessmentusecase.ErrInvalidWorkSessionClient).(*api.HoldMyAssessmentWorkSessionBadRequest); !ok {
t.Fatal("a malformed page identifier did not answer 400")
}
stub.holdErr = errors.New("private database detail")
if _, err := handler.HoldMyAssessmentWorkSession(principalForTest(uuid.New()),
api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient}); err == nil || err.Error() != "private database detail" {
t.Fatalf("internal error mapping = %v", err)
}
stub.holdErr = nil
release, err := handler.ReleaseMyAssessmentWorkSession(principalForTest(uuid.New()),
api.ReleaseMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if err != nil {
t.Fatalf("ReleaseMyAssessmentWorkSession() error = %v", err)
}
if noContent, ok := release.(*api.ReleaseMyAssessmentWorkSessionNoContent); !ok || noContent.CacheControl != api.CacheControlNoStoreNoStore {
t.Fatalf("release response = %T, want no-store 204", release)
}
if stub.releaseCommand.Client != testPageClient || stub.releaseCommand.AttemptID != domain.AssessmentAttemptID(attemptID) {
t.Fatalf("release command = %+v", stub.releaseCommand)
}
stub.releaseErr = assessmentusecase.ErrAttemptNotFound
missing, err := handler.ReleaseMyAssessmentWorkSession(principalForTest(uuid.New()),
api.ReleaseMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if _, ok := missing.(*api.ReleaseMyAssessmentWorkSessionNotFound); !ok || err != nil {
t.Fatalf("release of an unknown attempt = %T, %v, want 404", missing, err)
}
guest, err := handler.HoldMyAssessmentWorkSession(context.Background(), api.HoldMyAssessmentWorkSessionParams{AttemptID: attemptID, XAttemptClient: testPageClient})
if _, ok := guest.(*api.HoldMyAssessmentWorkSessionUnauthorized); !ok || err != nil {
t.Fatalf("guest hold = %T, %v, want 401", guest, err)
}
}
func TestStartSessionAndAnswerPassThePageAndRefuseAHeldAttemptWith409(t *testing.T) {
snapshot := assessmentPublicSnapshot()
operations := &assessmentOperationsStub{start: outbound.AssessmentAttemptSessionResult{Response: snapshot}}
handler := NewAssessmentHandler(operations)
ctx := principalForTest(uuid.New())
params := api.StartMyAssessmentAttemptSessionParams{
AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key", XAttemptClient: api.NewOptString(testPageClient),
}
if _, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7}, params); err != nil {
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
}
if operations.startCommand.Client != testPageClient {
t.Fatalf("StartSession() client = %q, want the page identifier", operations.startCommand.Client)
}
operations.startErr = assessmentusecase.ErrAttemptWorkSessionBusy
response, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7}, params)
if err != nil {
t.Fatalf("StartMyAssessmentAttemptSession(held) error = %v", err)
}
conflict, ok := response.(*api.StartMyAssessmentAttemptSessionConflict)
if !ok || api.Problem(*conflict).Code != api.ProblemCodeStateConflict {
t.Fatalf("held attempt response = %T, want 409 state_conflict", response)
}
// Without the header the request is one anonymous page.
params.XAttemptClient = api.OptString{}
operations.startErr = nil
if _, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{ExpectedVersion: 7}, params); err != nil || operations.startCommand.Client != "" {
t.Fatalf("StartSession() without a header: client %q, error %v, want an empty client", operations.startCommand.Client, err)
}
if _, ok := assessmentAnswerFailureOf(t, assessmentusecase.ErrAttemptWorkSessionBusy).(*api.SubmitMyAssessmentAnswerConflict); !ok {
t.Fatal("a held attempt did not answer 409 to an answer")
}
}
func assessmentAnswerFailureOf(t *testing.T, err error) api.SubmitMyAssessmentAnswerRes {
t.Helper()
response, mapped := assessmentAnswerFailure(context.Background(), err)
if mapped != nil {
t.Fatalf("assessmentAnswerFailure(%v) error = %v", err, mapped)
}
return response
}
@@ -43,14 +43,17 @@ func (repository assessmentSignalRepository) SaveOriginMark(ctx context.Context,
if err := mark.Validate(); err != nil {
return fmt.Errorf("%s - mark is invalid: %w", location, err)
}
var network []byte
var network, agent []byte
if !mark.NetworkDigest.IsZero() {
network = mark.NetworkDigest[:]
}
if !mark.AgentDigest.IsZero() {
agent = mark.AgentDigest[:]
}
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,
AgentDigest: agent, KeyVersion: mark.KeyVersion,
}); err != nil {
return fmt.Errorf("%s - insert origin mark: %w", location, mapAssessmentError(err))
}
@@ -102,7 +105,8 @@ func (repository assessmentSignalRepository) ReviewInputs(
}
inputs := outbound.AssessmentReviewInputs{
ClientFocusLossMS: totals.FocusLossMs, ClientClipboardCount: totals.ClipboardEvents,
ClientFullscreenExit: totals.FullscreenExits,
ClientFullscreenExit: totals.FullscreenExits, ClientScreenshotKeys: totals.ScreenshotKeys,
ClientDevtoolsOpens: totals.DevtoolsOpens,
}
for _, row := range times {
inputs.Answers = append(inputs.Answers, domain.AssessmentResponseSample{
@@ -121,7 +125,8 @@ func (repository assessmentSignalRepository) ReviewInputs(
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{}) {
len(row.NetworkDigest) != 0 && len(row.NetworkDigest) != len(domain.AssessmentDigest{}) ||
len(row.AgentDigest) != 0 && len(row.AgentDigest) != len(domain.AssessmentDigest{}) {
return domain.AssessmentOriginMark{}, domain.ErrInvalidAssessmentReview
}
mark := domain.AssessmentOriginMark{
@@ -131,6 +136,7 @@ func restoreAssessmentOriginMark(row sqlc.AssessmentAttemptOriginMark) (domain.A
}
copy(mark.SessionDigest[:], row.SessionDigest)
copy(mark.NetworkDigest[:], row.NetworkDigest)
copy(mark.AgentDigest[:], row.AgentDigest)
if err := mark.Validate(); err != nil {
return domain.AssessmentOriginMark{}, err
}
@@ -219,6 +225,8 @@ func (repository assessmentSignalRepository) SaveReview(ctx context.Context, rev
MatchedIntegerItems: measures.MatchedIntegerItems, MatchedSequenceItems: measures.MatchedSequenceItems,
DuplicateEvidenceBits: measures.DuplicateEvidenceBits, ClientFocusLossMs: measures.ClientFocusLossMS,
ClientClipboardEvents: measures.ClientClipboardEvents, ClientFullscreenExits: measures.ClientFullscreenExits,
ExtraAgents: measures.ExtraAgents, ClientScreenshotKeys: measures.ClientScreenshotKeys,
ClientDevtoolsOpens: measures.ClientDevtoolsOpens,
}); err != nil {
return fmt.Errorf("%s - upsert review: %w", location, mapAssessmentError(err))
}
@@ -262,7 +270,8 @@ func restoreAssessmentAttemptReview(row sqlc.GetAssessmentAttemptReviewRow) (dom
Measures: domain.AssessmentReviewMeasures{
AnsweredItems: row.AnsweredItems, FastAnswers: row.FastAnswers, DeviatingAnswers: row.DeviatingAnswers,
ParallelAlternations: row.ParallelAlternations, ExtraNetworks: row.ExtraNetworks,
MatchedIntegerItems: row.MatchedIntegerItems, MatchedSequenceItems: row.MatchedSequenceItems,
ExtraAgents: row.ExtraAgents, ClientScreenshotKeys: row.ClientScreenshotKeys,
ClientDevtoolsOpens: row.ClientDevtoolsOpens, MatchedIntegerItems: row.MatchedIntegerItems, MatchedSequenceItems: row.MatchedSequenceItems,
DuplicateEvidenceBits: row.DuplicateEvidenceBits,
ClientFocusLossMS: row.ClientFocusLossMs, ClientClipboardEvents: row.ClientClipboardEvents,
ClientFullscreenExits: row.ClientFullscreenExits,
@@ -0,0 +1,74 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var _ outbound.AssessmentWorkLeaseRepository = assessmentWorkLeaseRepository{}
func (unit *UnitOfWork) AssessmentWorkLeases() outbound.AssessmentWorkLeaseRepository {
return assessmentWorkLeaseRepository{queries: unit.queries}
}
type assessmentWorkLeaseRepository struct {
queries *sqlc.Queries
}
func (repository assessmentWorkLeaseRepository) Get(
ctx context.Context,
attemptID domain.AssessmentAttemptID,
) (domain.AssessmentWorkLease, bool, error) {
const location = "assessmentWorkLeaseRepository.Get"
if attemptID.IsZero() {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentWorkLease)
}
row, err := repository.queries.GetAssessmentWorkLease(ctx, pgUUID(attemptID.UUID()))
if errors.Is(err, pgx.ErrNoRows) {
return domain.AssessmentWorkLease{}, false, nil
}
if err != nil {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - read lease: %w", location, mapAssessmentError(err))
}
if !row.AttemptID.Valid || !row.AcquiredAt.Valid || !row.RenewedAt.Valid || len(row.HolderDigest) != len(domain.AssessmentDigest{}) {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - stored lease is incomplete: %w", location, domain.ErrInvalidAssessmentWorkLease)
}
lease := domain.AssessmentWorkLease{
AttemptID: domain.AssessmentAttemptID(row.AttemptID.Bytes), KeyVersion: row.KeyVersion,
AcquiredAt: row.AcquiredAt.Time.UTC(), RenewedAt: row.RenewedAt.Time.UTC(),
}
copy(lease.Holder[:], row.HolderDigest)
if row.ReleasedAt.Valid {
lease.ReleasedAt = row.ReleasedAt.Time.UTC()
}
if err := lease.Validate(); err != nil {
return domain.AssessmentWorkLease{}, false, fmt.Errorf("%s - restore lease: %w", location, err)
}
return lease, true, nil
}
func (repository assessmentWorkLeaseRepository) Save(ctx context.Context, lease domain.AssessmentWorkLease) error {
const location = "assessmentWorkLeaseRepository.Save"
if err := lease.Validate(); err != nil {
return fmt.Errorf("%s - lease is invalid: %w", location, err)
}
released := pgtype.Timestamptz{}
if !lease.ReleasedAt.IsZero() {
released = pgTime(lease.ReleasedAt)
}
if err := repository.queries.UpsertAssessmentWorkLease(ctx, sqlc.UpsertAssessmentWorkLeaseParams{
AttemptID: pgUUID(lease.AttemptID.UUID()), HolderDigest: lease.Holder[:], KeyVersion: lease.KeyVersion,
AcquiredAt: pgTime(lease.AcquiredAt), RenewedAt: pgTime(lease.RenewedAt), ReleasedAt: released,
}); err != nil {
return fmt.Errorf("%s - upsert lease: %w", location, mapAssessmentError(err))
}
return nil
}
@@ -29,6 +29,9 @@ SELECT
review.client_focus_loss_ms,
review.client_clipboard_events,
review.client_fullscreen_exits,
review.extra_agents,
review.client_screenshot_keys,
review.client_devtools_opens,
review.evaluated_at,
review.updated_at
FROM assessment_attempt_reviews AS review
@@ -53,6 +56,9 @@ type GetAssessmentAttemptReviewRow struct {
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
@@ -77,6 +83,9 @@ func (q *Queries) GetAssessmentAttemptReview(ctx context.Context, attemptID pgty
&i.ClientFocusLossMs,
&i.ClientClipboardEvents,
&i.ClientFullscreenExits,
&i.ExtraAgents,
&i.ClientScreenshotKeys,
&i.ClientDevtoolsOpens,
&i.EvaluatedAt,
&i.UpdatedAt,
)
@@ -87,7 +96,9 @@ const getAssessmentClientSignalTotals = `-- name: GetAssessmentClientSignalTotal
SELECT
COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms,
(count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events,
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits,
(count(*) FILTER (WHERE kind = 'screenshot_key'))::integer AS screenshot_keys,
(count(*) FILTER (WHERE kind = 'devtools_open'))::integer AS devtools_opens
FROM assessment_signal_events
WHERE attempt_id = $1
`
@@ -96,12 +107,20 @@ type GetAssessmentClientSignalTotalsRow struct {
FocusLossMs int64
ClipboardEvents int32
FullscreenExits int32
ScreenshotKeys int32
DevtoolsOpens 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)
err := row.Scan(
&i.FocusLossMs,
&i.ClipboardEvents,
&i.FullscreenExits,
&i.ScreenshotKeys,
&i.DevtoolsOpens,
)
return i, err
}
@@ -120,7 +139,7 @@ func (q *Queries) GetAssessmentReviewSubject(ctx context.Context, attemptID pgty
}
const getLastAssessmentOriginMark = `-- name: GetLastAssessmentOriginMark :one
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at DESC, id DESC
@@ -139,6 +158,7 @@ func (q *Queries) GetLastAssessmentOriginMark(ctx context.Context, attemptID pgt
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
&i.AgentDigest,
)
return i, err
}
@@ -210,6 +230,7 @@ INSERT INTO assessment_attempt_origin_marks (
observed_at,
session_digest,
network_digest,
agent_digest,
key_version
) VALUES (
$1,
@@ -218,7 +239,8 @@ INSERT INTO assessment_attempt_origin_marks (
$4,
$5,
$6,
$7
$7,
$8
)
`
@@ -229,6 +251,7 @@ type InsertAssessmentOriginMarkParams struct {
ObservedAt pgtype.Timestamptz
SessionDigest []byte
NetworkDigest []byte
AgentDigest []byte
KeyVersion int16
}
@@ -240,6 +263,7 @@ func (q *Queries) InsertAssessmentOriginMark(ctx context.Context, arg InsertAsse
arg.ObservedAt,
arg.SessionDigest,
arg.NetworkDigest,
arg.AgentDigest,
arg.KeyVersion,
)
return err
@@ -423,7 +447,7 @@ func (q *Queries) ListAssessmentDuplicatePairs(ctx context.Context, arg ListAsse
}
const listAssessmentOriginMarks = `-- name: ListAssessmentOriginMarks :many
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at, id
@@ -449,6 +473,7 @@ func (q *Queries) ListAssessmentOriginMarks(ctx context.Context, attemptID pgtyp
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
&i.AgentDigest,
); err != nil {
return nil, err
}
@@ -492,6 +517,9 @@ INSERT INTO assessment_attempt_reviews (
client_focus_loss_ms,
client_clipboard_events,
client_fullscreen_exits,
extra_agents,
client_screenshot_keys,
client_devtools_opens,
evaluated_at,
updated_at
) VALUES (
@@ -510,6 +538,9 @@ INSERT INTO assessment_attempt_reviews (
$13,
$14,
$15,
$16,
$17,
$18,
clock_timestamp(),
clock_timestamp()
)
@@ -528,6 +559,9 @@ ON CONFLICT (attempt_id) DO UPDATE SET
client_focus_loss_ms = EXCLUDED.client_focus_loss_ms,
client_clipboard_events = EXCLUDED.client_clipboard_events,
client_fullscreen_exits = EXCLUDED.client_fullscreen_exits,
extra_agents = EXCLUDED.extra_agents,
client_screenshot_keys = EXCLUDED.client_screenshot_keys,
client_devtools_opens = EXCLUDED.client_devtools_opens,
updated_at = greatest(
clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at
)
@@ -549,6 +583,9 @@ type UpsertAssessmentAttemptReviewParams struct {
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// The times come from the database clock, never from a caller, and the update
@@ -572,6 +609,9 @@ func (q *Queries) UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertA
arg.ClientFocusLossMs,
arg.ClientClipboardEvents,
arg.ClientFullscreenExits,
arg.ExtraAgents,
arg.ClientScreenshotKeys,
arg.ClientDevtoolsOpens,
)
return err
}
@@ -0,0 +1,80 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_work_leases.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentWorkLease = `-- name: GetAssessmentWorkLease :one
SELECT attempt_id, holder_digest, key_version, acquired_at, renewed_at, released_at
FROM assessment_attempt_work_leases
WHERE attempt_id = $1
`
// The hold of the single active work session of a real attempt. The caller
// holds the row lock of the attempt, so one attempt's lease is changed by one
// transaction at a time.
func (q *Queries) GetAssessmentWorkLease(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptWorkLease, error) {
row := q.db.QueryRow(ctx, getAssessmentWorkLease, attemptID)
var i AssessmentAttemptWorkLease
err := row.Scan(
&i.AttemptID,
&i.HolderDigest,
&i.KeyVersion,
&i.AcquiredAt,
&i.RenewedAt,
&i.ReleasedAt,
)
return i, err
}
const upsertAssessmentWorkLease = `-- name: UpsertAssessmentWorkLease :exec
INSERT INTO assessment_attempt_work_leases (
attempt_id,
holder_digest,
key_version,
acquired_at,
renewed_at,
released_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6
)
ON CONFLICT (attempt_id) DO UPDATE SET
holder_digest = EXCLUDED.holder_digest,
key_version = EXCLUDED.key_version,
acquired_at = EXCLUDED.acquired_at,
renewed_at = EXCLUDED.renewed_at,
released_at = EXCLUDED.released_at
`
type UpsertAssessmentWorkLeaseParams struct {
AttemptID pgtype.UUID
HolderDigest []byte
KeyVersion int16
AcquiredAt pgtype.Timestamptz
RenewedAt pgtype.Timestamptz
ReleasedAt pgtype.Timestamptz
}
func (q *Queries) UpsertAssessmentWorkLease(ctx context.Context, arg UpsertAssessmentWorkLeaseParams) error {
_, err := q.db.Exec(ctx, upsertAssessmentWorkLease,
arg.AttemptID,
arg.HolderDigest,
arg.KeyVersion,
arg.AcquiredAt,
arg.RenewedAt,
arg.ReleasedAt,
)
return err
}
@@ -109,6 +109,7 @@ type AssessmentAttemptOriginMark struct {
SessionDigest []byte
NetworkDigest []byte
KeyVersion int16
AgentDigest []byte
}
type AssessmentAttemptResult struct {
@@ -156,6 +157,18 @@ type AssessmentAttemptReview struct {
ClientFullscreenExits int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
type AssessmentAttemptWorkLease struct {
AttemptID pgtype.UUID
HolderDigest []byte
KeyVersion int16
AcquiredAt pgtype.Timestamptz
RenewedAt pgtype.Timestamptz
ReleasedAt pgtype.Timestamptz
}
type AssessmentCategoryCatalogBinding struct {
@@ -320,6 +320,10 @@ type Querier interface {
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)
// The hold of the single active work session of a real attempt. The caller
// holds the row lock of the attempt, so one attempt's lease is changed by one
// transaction at a time.
GetAssessmentWorkLease(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptWorkLease, error)
GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error)
// Reads one hiding of the candidate with the current name of the
// organization.
@@ -1251,6 +1255,7 @@ type Querier interface {
// 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
UpsertAssessmentWorkLease(ctx context.Context, arg UpsertAssessmentWorkLeaseParams) error
}
var _ Querier = (*Queries)(nil)
+10 -1
View File
@@ -56,6 +56,15 @@ func newAssessmentHandler(
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create signal observer: %w", err)
}
service.WithSignalObserver(observer)
// One open page per real attempt: the work session lease keeps its holder as
// a keyed digest, and the same observer records the origin of every hold.
workSessions, err := assessment.NewWorkSessions(transactor, keyring)
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create work sessions: %w", err)
}
workSessions.WithSignalObserver(observer)
service.WithWorkSessions(workSessions)
// The watermark is derived from the identity keyring like the signal
// digests: the same secret, a key of its own, and no new setting.
watermarker, err := assessment.NewWatermarker(keyring)
@@ -63,5 +72,5 @@ func newAssessmentHandler(
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create watermarker: %w", err)
}
return v1.NewAssessmentHandler(service).WithPresenter(watermarker), pool.Close, nil
return v1.NewAssessmentHandler(service).WithPresenter(watermarker).WithWorkSessions(workSessions), pool.Close, nil
}
+16 -8
View File
@@ -27,12 +27,18 @@ const (
AssessmentSignalPaste AssessmentSignalKind = "paste"
AssessmentSignalCut AssessmentSignalKind = "cut"
AssessmentSignalFullscreenExit AssessmentSignalKind = "fullscreen_exit"
// AssessmentSignalScreenshotKey and AssessmentSignalDevtoolsOpen are weak
// hints that the screen may be captured or inspected. They carry no
// measurement and lead to attention in a manual review at most.
AssessmentSignalScreenshotKey AssessmentSignalKind = "screenshot_key"
AssessmentSignalDevtoolsOpen AssessmentSignalKind = "devtools_open"
)
func (kind AssessmentSignalKind) IsKnown() bool {
switch kind {
case AssessmentSignalFocusLoss, AssessmentSignalCopy, AssessmentSignalPaste,
AssessmentSignalCut, AssessmentSignalFullscreenExit:
AssessmentSignalCut, AssessmentSignalFullscreenExit,
AssessmentSignalScreenshotKey, AssessmentSignalDevtoolsOpen:
return true
default:
return false
@@ -75,8 +81,8 @@ func newAssessmentSignalEvent(input AssessmentSignalEventInput, occurredAt time.
return assessmentFocusLossEvent(input, occurredAt)
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
return assessmentClipboardEvent(input, occurredAt)
case AssessmentSignalFullscreenExit:
return assessmentFullscreenExitEvent(input, occurredAt)
case AssessmentSignalFullscreenExit, AssessmentSignalScreenshotKey, AssessmentSignalDevtoolsOpen:
return assessmentBareEvent(input, occurredAt)
default:
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - event kind is unknown: %w", ErrInvalidAssessmentSignal)
}
@@ -102,9 +108,11 @@ func assessmentClipboardEvent(input AssessmentSignalEventInput, occurredAt time.
}, nil
}
func assessmentFullscreenExitEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
// assessmentBareEvent builds an event that is only a fact: a fullscreen exit, a
// screenshot key, or open developer tools. It has no measurement.
func assessmentBareEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
if input.DurationMS != nil || input.SizeBytes != nil {
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - fullscreen exit has no measurements: %w", ErrInvalidAssessmentSignal)
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - %s has no measurements: %w", input.Kind, ErrInvalidAssessmentSignal)
}
return AssessmentSignalEvent{kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt}, nil
}
@@ -162,8 +170,8 @@ func validateAssessmentSignalBatchEvent(event AssessmentSignalEvent) error {
return validateAssessmentSignalFocusLoss(event)
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
return validateAssessmentSignalClipboard(event)
case AssessmentSignalFullscreenExit:
return validateAssessmentSignalFullscreenExit(event)
case AssessmentSignalFullscreenExit, AssessmentSignalScreenshotKey, AssessmentSignalDevtoolsOpen:
return validateAssessmentSignalBare(event)
default:
return ErrInvalidAssessmentSignal
}
@@ -183,7 +191,7 @@ func validateAssessmentSignalClipboard(event AssessmentSignalEvent) error {
return nil
}
func validateAssessmentSignalFullscreenExit(event AssessmentSignalEvent) error {
func validateAssessmentSignalBare(event AssessmentSignalEvent) error {
if event.hasDuration || event.hasSize {
return ErrInvalidAssessmentSignal
}
@@ -56,6 +56,21 @@ type AssessmentSignalPolicy struct {
ClientFocusLossAttentionMS int32
ClientClipboardEventsAttention int32
ClientFullscreenExitsAttention int32
// The signals below were added after the policy section was first
// published, so a stored version does not carry them. A zero threshold
// leaves the signal out of the band, and a version never acquires a
// default: the facts are stored and counted for the operator either way.
//
// ClientScreenshotKeysAttention and ClientDevtoolsAttention are client
// thresholds, so they raise a normal band to attention only.
ClientScreenshotKeysAttention int32
ClientDevtoolsAttention int32
// ExtraAgents counts the distinct User-Agent digests of the attempt beyond
// the first. It joins the weak group of parallel sessions and extra
// networks, so alone it reaches attention at most.
ExtraAgentsAttention int32
ExtraAgentsReview int32
}
// Sanity bounds of the signal section. They reject a value in the wrong unit;
@@ -99,6 +114,20 @@ func DemoAssessmentSignalPolicy() AssessmentSignalPolicy {
}
}
// DemoAssessmentSignalPolicyWithCaptureHints is the demonstration policy with
// the optional signals switched on: three screenshot keys, one detection of
// open developer tools, and two extra User-Agents reach attention. Like the
// other demo values they are agreed starting points that no study supports.
// DemoAssessmentSignalPolicy itself stays as it was published, because a stored
// version never changes.
func DemoAssessmentSignalPolicyWithCaptureHints() AssessmentSignalPolicy {
policy := DemoAssessmentSignalPolicy()
policy.ClientScreenshotKeysAttention = 3
policy.ClientDevtoolsAttention = 1
policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 2, 4
return policy
}
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy AssessmentSignalPolicy) Validate() error {
const location = "AssessmentSignalPolicy.Validate"
@@ -115,6 +144,21 @@ func (policy AssessmentSignalPolicy) Validate() error {
); err != nil {
return err
}
if err := firstError(
checkOptionalRange(location, "assessment.signals.client_screenshot_keys_attention", policy.ClientScreenshotKeysAttention, maxSignalCount),
checkOptionalRange(location, "assessment.signals.client_devtools_attention", policy.ClientDevtoolsAttention, maxSignalCount),
checkOptionalRange(location, "assessment.signals.extra_agents_attention", policy.ExtraAgentsAttention, maxSignalCount),
); err != nil {
return err
}
if policy.ExtraAgentsAttention == 0 && policy.ExtraAgentsReview != 0 {
return invalidPolicy(location, "assessment.signals.extra_agents_review needs extra_agents_attention")
}
if policy.ExtraAgentsAttention != 0 {
if err := checkRange(location, "assessment.signals.extra_agents_review", policy.ExtraAgentsReview, policy.ExtraAgentsAttention, maxSignalCount); err != nil {
return err
}
}
for _, pair := range []struct {
field string
attention, review int32
@@ -135,3 +179,12 @@ func (policy AssessmentSignalPolicy) Validate() error {
}
return nil
}
// checkOptionalRange accepts zero, which leaves an optional signal out, or a
// value from 1 to maximum.
func checkOptionalRange(location, field string, value, maximum int32) error {
if value == 0 {
return nil
}
return checkRange(location, field, value, 1, maximum)
}
@@ -2,6 +2,7 @@ package domain
import (
"errors"
"strings"
"testing"
)
@@ -78,3 +79,66 @@ func TestSignalPolicyRejectsOutOfRangeAndInconsistentValues(t *testing.T) {
})
}
}
// A version published before the capture hints existed carries none of their
// fields. It must decode with the hints switched off and encode back to the same
// document, so its content hash and the bands of its attempts never change.
func TestPolicyWithoutCaptureThresholdsDecodesOffAndEncodesUnchanged(t *testing.T) {
policy := DemoProductPolicyV3()
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
for _, field := range []string{"client_screenshot_keys_attention", "client_devtools_attention", "extra_agents_attention", "extra_agents_review"} {
if strings.Contains(string(encoded), field) {
t.Fatalf("the document of the published policy holds %q, want it absent", field)
}
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
signals := decoded.Assessment.Signals
if signals == nil || signals.ClientScreenshotKeysAttention != 0 || signals.ClientDevtoolsAttention != 0 || signals.ExtraAgentsAttention != 0 || signals.ExtraAgentsReview != 0 {
t.Fatalf("decoded signals = %+v, want the capture hints off", signals)
}
again, _, err := encodeProductPolicy(decoded)
if err != nil || string(again) != string(encoded) {
t.Fatalf("re-encoded document differs from the stored one (error %v)", err)
}
}
func TestCaptureThresholdsRoundTripAndAreValidated(t *testing.T) {
signals := DemoAssessmentSignalPolicyWithCaptureHints()
if signals.ClientScreenshotKeysAttention == 0 || signals.ClientDevtoolsAttention == 0 || signals.ExtraAgentsAttention == 0 {
t.Fatalf("DemoAssessmentSignalPolicyWithCaptureHints() = %+v, want the hints switched on", signals)
}
policy := DemoProductPolicyV3()
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.Signals != signals {
t.Fatalf("decoded signals = %+v, error %v, want the thresholds back", decoded.Assessment.Signals, err)
}
if DemoAssessmentSignalPolicy().ClientScreenshotKeysAttention != 0 {
t.Fatal("DemoAssessmentSignalPolicy gained a capture threshold; a stored version must not change")
}
for name, change := range map[string]func(*AssessmentSignalPolicy){
"negative threshold": func(policy *AssessmentSignalPolicy) { policy.ClientDevtoolsAttention = -1 },
"threshold beyond the bound": func(policy *AssessmentSignalPolicy) { policy.ClientScreenshotKeysAttention = maxSignalCount + 1 },
"review without attention": func(policy *AssessmentSignalPolicy) { policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 0, 3 },
"review below attention": func(policy *AssessmentSignalPolicy) { policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 4, 3 },
"attention without a review": func(policy *AssessmentSignalPolicy) { policy.ExtraAgentsAttention, policy.ExtraAgentsReview = 2, 0 },
} {
t.Run(name, func(t *testing.T) {
policy := DemoAssessmentSignalPolicyWithCaptureHints()
change(&policy)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
@@ -49,6 +49,7 @@ const (
AssessmentReviewReasonDeviatingAnswers AssessmentReviewReason = "deviating_answers"
AssessmentReviewReasonParallelSessions AssessmentReviewReason = "parallel_sessions"
AssessmentReviewReasonExtraNetworks AssessmentReviewReason = "extra_networks"
AssessmentReviewReasonExtraAgents AssessmentReviewReason = "extra_agents"
AssessmentReviewReasonDuplicateAnswers AssessmentReviewReason = "duplicate_answers"
AssessmentReviewReasonClientSignals AssessmentReviewReason = "client_signals"
)
@@ -57,7 +58,7 @@ const (
func (reason AssessmentReviewReason) IsKnown() bool {
switch reason {
case AssessmentReviewReasonFastAnswers, AssessmentReviewReasonDeviatingAnswers,
AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks,
AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks, AssessmentReviewReasonExtraAgents,
AssessmentReviewReasonDuplicateAnswers, AssessmentReviewReasonClientSignals:
return true
default:
@@ -129,15 +130,17 @@ func (observation AssessmentAnswerObservation) Validate() error {
type AssessmentOriginSource string
const (
AssessmentOriginAnswer AssessmentOriginSource = "answer"
AssessmentOriginSignals AssessmentOriginSource = "signals"
AssessmentOriginAnswer AssessmentOriginSource = "answer"
AssessmentOriginSignals AssessmentOriginSource = "signals"
AssessmentOriginWorkSession AssessmentOriginSource = "work_session"
)
// 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.
// authenticated session, of the client network, and of the User-Agent. 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 and AgentDigest when
// the request had no User-Agent; the raw User-Agent is never stored.
type AssessmentOriginMark struct {
ID uuid.UUID
AttemptID AssessmentAttemptID
@@ -145,6 +148,7 @@ type AssessmentOriginMark struct {
ObservedAt time.Time
SessionDigest AssessmentDigest
NetworkDigest AssessmentDigest
AgentDigest AssessmentDigest
KeyVersion int16
}
@@ -154,7 +158,7 @@ func (mark AssessmentOriginMark) Validate() error {
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 {
if mark.Source != AssessmentOriginAnswer && mark.Source != AssessmentOriginSignals && mark.Source != AssessmentOriginWorkSession {
return fmt.Errorf("%s - source is unknown: %w", location, ErrInvalidAssessmentReview)
}
return nil
@@ -243,6 +247,11 @@ type AssessmentOriginAnomalies struct {
// ExtraNetworks counts the distinct network digests beyond the first. A
// move to another network and back is one extra network.
ExtraNetworks int32
// ExtraAgents counts the distinct User-Agent digests beyond the first, so
// a switch to another browser or device and back is one extra agent. A
// browser that updates itself during an attempt can add one without any
// change of device.
ExtraAgents int32
}
// CountOriginAnomalies orders the marks by time and then by ID and counts
@@ -258,6 +267,7 @@ func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalie
var anomalies AssessmentOriginAnomalies
seenSessions := map[AssessmentDigest]struct{}{}
networks := map[AssessmentDigest]struct{}{}
agents := map[AssessmentDigest]struct{}{}
var previousSession AssessmentDigest
for _, mark := range ordered {
_, seen := seenSessions[mark.SessionDigest]
@@ -269,8 +279,12 @@ func CountOriginAnomalies(marks []AssessmentOriginMark) AssessmentOriginAnomalie
if !mark.NetworkDigest.IsZero() {
networks[mark.NetworkDigest] = struct{}{}
}
if !mark.AgentDigest.IsZero() {
agents[mark.AgentDigest] = struct{}{}
}
}
anomalies.ExtraNetworks = int32(max(len(networks)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list.
anomalies.ExtraAgents = int32(max(len(agents)-1, 0)) //nolint:gosec // The number of marks of an attempt is bounded by its stored list.
return anomalies
}
@@ -283,12 +297,16 @@ type AssessmentReviewMeasures struct {
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
ExtraAgents int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMS int64
ClientClipboardEvents int32
ClientFullscreenExits int32
// ClientScreenshotKeys and ClientDevtoolsOpens count the weak capture hints.
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// AssessmentReviewOutcome is the computed band with the groups behind it.
@@ -297,12 +315,15 @@ type AssessmentReviewOutcome struct {
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.
// Evaluate computes the band. Server signals decide it. Parallel sessions,
// extra networks, and extra User-Agents are weak and correlated (a phone and a
// laptop produce all three), 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, the weak capture hints (screenshot keys and open developer tools)
// among them, can only raise a normal band to attention, because a browser
// reports them and anyone can forge or suppress them. A threshold of the
// optional signals that is zero in the policy leaves that signal out.
func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures) AssessmentReviewOutcome {
type signal struct {
reason AssessmentReviewReason
@@ -314,6 +335,7 @@ func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures)
{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},
{AssessmentReviewReasonExtraAgents, optionalSignalLevel(measures.ExtraAgents, policy.ExtraAgentsAttention, policy.ExtraAgentsReview), true},
{AssessmentReviewReasonDuplicateAnswers, signalLevel(measures.DuplicateEvidenceBits, policy.DuplicateAttentionBits, policy.DuplicateReviewBits), false},
}
strongRaised := false
@@ -336,9 +358,7 @@ func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures)
outcome.Band = band
}
}
if measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) ||
measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention ||
measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention {
if policy.clientSignalsRaised(measures) {
outcome.Reasons = append(outcome.Reasons, AssessmentReviewReasonClientSignals)
if outcome.Band == AssessmentReviewBandNormal {
outcome.Band = AssessmentReviewBandAttention
@@ -347,6 +367,37 @@ func (policy AssessmentSignalPolicy) Evaluate(measures AssessmentReviewMeasures)
return outcome
}
// clientSignalsRaised reports whether any browser-reported measure reaches its
// threshold. The capture hints have thresholds only in a policy version that
// opted in to them.
func (policy AssessmentSignalPolicy) clientSignalsRaised(measures AssessmentReviewMeasures) bool {
return measures.ClientFocusLossMS >= int64(policy.ClientFocusLossAttentionMS) ||
measures.ClientClipboardEvents >= policy.ClientClipboardEventsAttention ||
measures.ClientFullscreenExits >= policy.ClientFullscreenExitsAttention ||
optionalSignalReached(measures.ClientScreenshotKeys, policy.ClientScreenshotKeysAttention) ||
optionalSignalReached(measures.ClientDevtoolsOpens, policy.ClientDevtoolsAttention)
}
// optionalSignalReached is false for a threshold of zero, which switches the
// signal off.
func optionalSignalReached(value, threshold int32) bool {
return threshold > 0 && value >= threshold
}
// optionalSignalLevel is signalLevel for a signal that an older policy version
// does not carry: a zero attention threshold switches it off, and a zero review
// threshold leaves it at attention.
func optionalSignalLevel(value, attention, review int32) AssessmentReviewBand {
switch {
case attention == 0 || value < attention:
return AssessmentReviewBandNormal
case review > 0 && value >= review:
return AssessmentReviewBandReview
default:
return AssessmentReviewBandAttention
}
}
func signalLevel(value, attention, review int32) AssessmentReviewBand {
switch {
case value >= review:
@@ -141,6 +141,88 @@ func TestEvaluateBandFollowsThePolicyAndClientSignalsOnlyRaiseToAttention(t *tes
}
}
func TestWeakCaptureSignalsNeverRaiseTheBandAboveAttention(t *testing.T) {
policy := DemoAssessmentSignalPolicyWithCaptureHints()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoAssessmentSignalPolicyWithCaptureHints().Validate() error = %v", err)
}
huge := int32(1_000_000)
tests := []struct {
name string
measures AssessmentReviewMeasures
wantBand AssessmentReviewBand
wantReasons []AssessmentReviewReason
}{
{"one screenshot key is below the threshold", AssessmentReviewMeasures{ClientScreenshotKeys: policy.ClientScreenshotKeysAttention - 1}, AssessmentReviewBandNormal, nil},
{"screenshot keys at the threshold reach attention", AssessmentReviewMeasures{ClientScreenshotKeys: policy.ClientScreenshotKeysAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"open developer tools reach attention", AssessmentReviewMeasures{ClientDevtoolsOpens: policy.ClientDevtoolsAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"however many screenshot keys and detections, attention is the ceiling", AssessmentReviewMeasures{ClientScreenshotKeys: huge, ClientDevtoolsOpens: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonClientSignals}},
{"capture hints do not lift a server signal to review", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ClientScreenshotKeys: huge, ClientDevtoolsOpens: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonClientSignals}},
{"extra agents reach attention", AssessmentReviewMeasures{ExtraAgents: policy.ExtraAgentsAttention}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraAgents}},
{"extra agents alone stop at attention however many", AssessmentReviewMeasures{ExtraAgents: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonExtraAgents}},
{"all weak signals together still stop at attention", AssessmentReviewMeasures{ExtraAgents: huge, ExtraNetworks: huge, ParallelAlternations: huge, ClientScreenshotKeys: huge, ClientDevtoolsOpens: huge}, AssessmentReviewBandAttention, []AssessmentReviewReason{AssessmentReviewReasonParallelSessions, AssessmentReviewReasonExtraNetworks, AssessmentReviewReasonExtraAgents, AssessmentReviewReasonClientSignals}},
{"extra agents reach review only beside a strong signal", AssessmentReviewMeasures{FastAnswers: policy.FastAnswersAttention, ExtraAgents: huge}, AssessmentReviewBandReview, []AssessmentReviewReason{AssessmentReviewReasonFastAnswers, AssessmentReviewReasonExtraAgents}},
}
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)
}
})
}
}
// A policy version published before the capture hints existed has no thresholds
// for them, so the facts are stored and counted but never change its band.
func TestAPolicyWithoutCaptureThresholdsIgnoresTheCaptureHints(t *testing.T) {
policy := DemoAssessmentSignalPolicy()
got := policy.Evaluate(AssessmentReviewMeasures{ClientScreenshotKeys: 1000, ClientDevtoolsOpens: 1000, ExtraAgents: 1000})
if got.Band != AssessmentReviewBandNormal || len(got.Reasons) != 0 {
t.Fatalf("Evaluate() = %+v, want a normal band: the hints have no threshold in this policy", got)
}
}
func TestCountOriginAnomaliesCountsDistinctAgentsBeyondTheFirst(t *testing.T) {
withAgent := func(second int, session, network, agent byte) AssessmentOriginMark {
mark := originMark(second, session, network)
if agent != 0 {
mark.AgentDigest = AssessmentDigest{agent}
}
return mark
}
tests := []struct {
name string
marks []AssessmentOriginMark
want int32
}{
{"one agent", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 1)}, 0},
{"a request without an agent is skipped", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 0), withAgent(3, 1, 1, 1)}, 0},
{"a switch to another browser and back is one extra agent", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 2), withAgent(3, 1, 1, 1)}, 1},
{"three agents", []AssessmentOriginMark{withAgent(1, 1, 1, 1), withAgent(2, 1, 1, 2), withAgent(3, 1, 1, 3)}, 2},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := CountOriginAnomalies(test.marks).ExtraAgents; got != test.want {
t.Fatalf("CountOriginAnomalies().ExtraAgents = %d, want %d", got, test.want)
}
})
}
}
func TestOriginMarkOfAWorkSessionHoldIsValid(t *testing.T) {
mark := originMark(1, 1, 1)
mark.Source = AssessmentOriginWorkSession
mark.AgentDigest = AssessmentDigest{9}
if err := mark.Validate(); err != nil {
t.Fatalf("Validate() error = %v", err)
}
mark.Source = "elsewhere"
if err := mark.Validate(); err == nil {
t.Fatal("Validate() accepted an unknown source")
}
}
func TestEvaluateUsesTheThresholdsOfTheGivenPolicy(t *testing.T) {
measures := AssessmentReviewMeasures{FastAnswers: 4}
strict := DemoAssessmentSignalPolicy()
@@ -25,6 +25,8 @@ func TestAssessmentSignalEventValidatesAllowlistedMeasurements(t *testing.T) {
{name: "paste", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalPaste},
{name: "cut", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCut, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalCut},
{name: "fullscreen exit", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalFullscreenExit},
{name: "screenshot key", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalScreenshotKey, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalScreenshotKey},
{name: "developer tools open", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalDevtoolsOpen, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalDevtoolsOpen},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -62,6 +64,9 @@ func TestAssessmentSignalEventRejectsMismatchedOrUnboundedMeasurements(t *testin
{name: "negative clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCopy, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: func() *int32 { value := int32(-1); return &value }()}},
{name: "focus with clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &size, SizeBytes: &size}},
{name: "fullscreen with measurement", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: &size}},
{name: "screenshot key with a size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalScreenshotKey, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: &size}},
{name: "developer tools with a duration", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalDevtoolsOpen, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &size}},
{name: "screenshot key without an item", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalScreenshotKey, OccurredAt: validTime}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
@@ -0,0 +1,95 @@
package domain
import (
"errors"
"fmt"
"time"
)
// ErrInvalidAssessmentWorkLease reports a malformed work session lease.
var ErrInvalidAssessmentWorkLease = errors.New("invalid assessment work lease")
const (
// AssessmentWorkLeaseDuration is how long a hold of the work session lasts
// after its last renewal. It is long enough for a background tab, whose
// timers a browser slows to about one a minute, to renew in time, and short
// enough that a crashed page frees the attempt for the candidate quickly.
AssessmentWorkLeaseDuration = 2 * time.Minute
// AssessmentWorkLeaseRenewEvery is how often a page repeats the hold.
AssessmentWorkLeaseRenewEvery = 15 * time.Second
)
// AssessmentWorkLease is the hold of the single active work session of a real
// attempt. One open page holds it at a time: it is a rule that keeps one
// attempt from being worked on in two windows, not a lock on the candidate. The
// holder is only a keyed digest of the identifier the page generated, so the
// value never reaches the store.
type AssessmentWorkLease struct {
AttemptID AssessmentAttemptID
Holder AssessmentDigest
KeyVersion int16
// AcquiredAt is when the current holder took the session; a renewal keeps it.
AcquiredAt time.Time
RenewedAt time.Time
// ReleasedAt is set when the holder closed its page, and zero otherwise.
ReleasedAt time.Time
}
// Validate checks that the lease can be stored.
func (lease AssessmentWorkLease) Validate() error {
const location = "AssessmentWorkLease.Validate"
switch {
case lease.AttemptID.IsZero(), lease.Holder.IsZero(), lease.KeyVersion < 1:
return fmt.Errorf("%s - attempt, holder, and key version are required: %w", location, ErrInvalidAssessmentWorkLease)
case lease.AcquiredAt.IsZero(), lease.RenewedAt.Before(lease.AcquiredAt):
return fmt.Errorf("%s - acquisition and renewal times are inconsistent: %w", location, ErrInvalidAssessmentWorkLease)
case !lease.ReleasedAt.IsZero() && lease.ReleasedAt.Before(lease.AcquiredAt):
return fmt.Errorf("%s - release predates acquisition: %w", location, ErrInvalidAssessmentWorkLease)
}
return nil
}
// ActiveAt reports whether the hold is in force at the time: not released and
// renewed within AssessmentWorkLeaseDuration.
func (lease AssessmentWorkLease) ActiveAt(now time.Time) bool {
return lease.ReleasedAt.IsZero() && now.Before(lease.RenewedAt.Add(AssessmentWorkLeaseDuration))
}
// HeldUntil is the end of the hold if it is not renewed.
func (lease AssessmentWorkLease) HeldUntil() time.Time {
return lease.RenewedAt.Add(AssessmentWorkLeaseDuration)
}
// AdmitsHolder reports whether a page with the given holder digest may work on
// the attempt now: nobody holds it, the hold was released or has expired, or
// the page is the holder. An absent lease is passed as the zero value.
func (lease AssessmentWorkLease) AdmitsHolder(holder AssessmentDigest, now time.Time) bool {
return lease.Holder.IsZero() || !lease.ActiveAt(now) || lease.Holder == holder
}
// Held returns the lease after the page took or renewed it at the time. A
// change of holder, a released hold, or an expired hold starts a new
// acquisition; a renewal by the holder keeps the acquisition time.
func (lease AssessmentWorkLease) Held(
attemptID AssessmentAttemptID,
holder AssessmentDigest,
keyVersion int16,
now time.Time,
) AssessmentWorkLease {
renewal := !lease.Holder.IsZero() && lease.Holder == holder && lease.ActiveAt(now)
next := AssessmentWorkLease{AttemptID: attemptID, Holder: holder, KeyVersion: keyVersion, AcquiredAt: now, RenewedAt: now}
if renewal && lease.KeyVersion == keyVersion {
next.AcquiredAt = lease.AcquiredAt
}
return next
}
// ReleasedBy returns the lease released by the holder at the time. Any other
// page, and a lease that is no longer held, leave it as it is.
func (lease AssessmentWorkLease) ReleasedBy(holder AssessmentDigest, now time.Time) AssessmentWorkLease {
if lease.Holder.IsZero() || lease.Holder != holder || !lease.ReleasedAt.IsZero() {
return lease
}
lease.ReleasedAt = now
return lease
}
@@ -0,0 +1,121 @@
package domain
import (
"errors"
"testing"
"time"
"github.com/google/uuid"
)
var leaseStart = time.Date(2026, time.October, 11, 9, 0, 0, 0, time.UTC)
func leaseAttempt() AssessmentAttemptID { return AssessmentAttemptID(uuid.New()) }
func TestOnePageHoldsTheWorkSessionAndAnotherIsRefusedUntilItIsClosed(t *testing.T) {
attempt := leaseAttempt()
first, second := AssessmentDigest{1}, AssessmentDigest{2}
var none AssessmentWorkLease
if !none.AdmitsHolder(first, leaseStart) {
t.Fatal("an attempt that nobody holds refused a page")
}
held := none.Held(attempt, first, 1, leaseStart)
if err := held.Validate(); err != nil {
t.Fatalf("Held().Validate() error = %v", err)
}
if held.AdmitsHolder(second, leaseStart.Add(time.Second)) {
t.Fatal("a second page was admitted while the first one holds the work session")
}
if !held.AdmitsHolder(first, leaseStart.Add(time.Second)) {
t.Fatal("the holder was refused")
}
// Closing the page frees the session at once.
released := held.ReleasedBy(first, leaseStart.Add(5*time.Second))
if released.ActiveAt(leaseStart.Add(6*time.Second)) || !released.AdmitsHolder(second, leaseStart.Add(6*time.Second)) {
t.Fatal("the session is still held after the holder released it")
}
if err := released.Validate(); err != nil {
t.Fatalf("released lease Validate() error = %v", err)
}
// The second page takes it over as a new acquisition.
taken := released.Held(attempt, second, 1, leaseStart.Add(7*time.Second))
if taken.Holder != second || !taken.AcquiredAt.Equal(leaseStart.Add(7*time.Second)) || !taken.ReleasedAt.IsZero() {
t.Fatalf("takeover = %+v, want a fresh hold of the second page", taken)
}
}
func TestAHoldExpiresWhenThePageStopsRenewing(t *testing.T) {
attempt := leaseAttempt()
first, second := AssessmentDigest{1}, AssessmentDigest{2}
held := AssessmentWorkLease{}.Held(attempt, first, 1, leaseStart)
before := leaseStart.Add(AssessmentWorkLeaseDuration - time.Second)
if held.AdmitsHolder(second, before) {
t.Fatal("the hold ended before its duration")
}
if got, want := held.HeldUntil(), leaseStart.Add(AssessmentWorkLeaseDuration); !got.Equal(want) {
t.Fatalf("HeldUntil() = %s, want %s", got, want)
}
// A renewal by the holder moves the end and keeps the acquisition time.
renewed := held.Held(attempt, first, 1, leaseStart.Add(time.Minute))
if !renewed.AcquiredAt.Equal(leaseStart) || !renewed.RenewedAt.Equal(leaseStart.Add(time.Minute)) {
t.Fatalf("renewal = %+v, want the first acquisition time and a new renewal time", renewed)
}
if renewed.AdmitsHolder(second, leaseStart.Add(time.Minute+AssessmentWorkLeaseDuration-time.Second)) {
t.Fatal("a renewed hold ended early")
}
// Without a renewal the session is free once the duration has passed.
if !held.AdmitsHolder(second, leaseStart.Add(AssessmentWorkLeaseDuration)) {
t.Fatal("an expired hold refused another page")
}
// The holder coming back after an expiry is a new acquisition, not a renewal.
again := held.Held(attempt, first, 1, leaseStart.Add(time.Hour))
if !again.AcquiredAt.Equal(leaseStart.Add(time.Hour)) {
t.Fatalf("a hold after expiry kept the old acquisition time: %+v", again)
}
}
func TestOnlyTheHolderReleasesAndAReleaseNeverRevealsAnything(t *testing.T) {
attempt := leaseAttempt()
first, second := AssessmentDigest{1}, AssessmentDigest{2}
held := AssessmentWorkLease{}.Held(attempt, first, 1, leaseStart)
if other := held.ReleasedBy(second, leaseStart.Add(time.Second)); other != held {
t.Fatalf("another page changed the lease: %+v", other)
}
once := held.ReleasedBy(first, leaseStart.Add(time.Second))
if twice := once.ReleasedBy(first, leaseStart.Add(2*time.Second)); twice != once {
t.Fatalf("a second release changed the lease: %+v", twice)
}
var none AssessmentWorkLease
if got := none.ReleasedBy(first, leaseStart); got != none {
t.Fatalf("releasing a lease that does not exist changed it: %+v", got)
}
}
func TestWorkLeaseValidationRejectsIncompleteLeases(t *testing.T) {
attempt := leaseAttempt()
valid := AssessmentWorkLease{}.Held(attempt, AssessmentDigest{1}, 1, leaseStart)
for name, change := range map[string]func(*AssessmentWorkLease){
"no attempt": func(lease *AssessmentWorkLease) { lease.AttemptID = AssessmentAttemptID{} },
"no holder": func(lease *AssessmentWorkLease) { lease.Holder = AssessmentDigest{} },
"no key version": func(lease *AssessmentWorkLease) { lease.KeyVersion = 0 },
"renewed before held": func(lease *AssessmentWorkLease) { lease.RenewedAt = lease.AcquiredAt.Add(-time.Second) },
"released before held": func(lease *AssessmentWorkLease) {
lease.ReleasedAt = lease.AcquiredAt.Add(-time.Second)
},
} {
t.Run(name, func(t *testing.T) {
lease := valid
change(&lease)
if err := lease.Validate(); !errors.Is(err, ErrInvalidAssessmentWorkLease) {
t.Fatalf("Validate() error = %v, want ErrInvalidAssessmentWorkLease", err)
}
})
}
if AssessmentWorkLeaseRenewEvery*4 >= AssessmentWorkLeaseDuration {
t.Fatal("a page renews less than four times within a hold, so one slow timer would lose the session")
}
}
@@ -134,6 +134,13 @@ type assessmentSignalsDocument struct {
ClientFocusLossAttentionMS *int32 `json:"client_focus_loss_attention_ms"`
ClientClipboardEventsAttention *int32 `json:"client_clipboard_events_attention"`
ClientFullscreenExitsAttention *int32 `json:"client_fullscreen_exits_attention"`
// The optional signals are absent from a version published before they
// existed and are written only when set, so the stored document and the
// content hash of such a version never change.
ClientScreenshotKeysAttention *int32 `json:"client_screenshot_keys_attention,omitempty"`
ClientDevtoolsAttention *int32 `json:"client_devtools_attention,omitempty"`
ExtraAgentsAttention *int32 `json:"extra_agents_attention,omitempty"`
ExtraAgentsReview *int32 `json:"extra_agents_review,omitempty"`
}
type assessmentTrainingDocument struct {
@@ -354,6 +361,10 @@ func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSig
ClientFocusLossAttentionMS: pointer(policy.ClientFocusLossAttentionMS),
ClientClipboardEventsAttention: pointer(policy.ClientClipboardEventsAttention),
ClientFullscreenExitsAttention: pointer(policy.ClientFullscreenExitsAttention),
ClientScreenshotKeysAttention: optionalPointer(policy.ClientScreenshotKeysAttention),
ClientDevtoolsAttention: optionalPointer(policy.ClientDevtoolsAttention),
ExtraAgentsAttention: optionalPointer(policy.ExtraAgentsAttention),
ExtraAgentsReview: optionalPointer(policy.ExtraAgentsReview),
}
}
@@ -578,6 +589,10 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
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),
ClientScreenshotKeysAttention: optionalValue(signals.ClientScreenshotKeysAttention),
ClientDevtoolsAttention: optionalValue(signals.ClientDevtoolsAttention),
ExtraAgentsAttention: optionalValue(signals.ExtraAgentsAttention),
ExtraAgentsReview: optionalValue(signals.ExtraAgentsReview),
}
}
policy := ProductPolicy{
@@ -742,3 +757,23 @@ func require[T any](reader *documentReader, field string, value *T) T {
}
func pointer[T any](value T) *T { return &value }
// optionalPointer is pointer for an optional field: a zero value is left out of
// the document, as if the field had never existed.
func optionalPointer[T comparable](value T) *T {
var zero T
if value == zero {
return nil
}
return &value
}
// optionalValue returns the value behind a pointer of an optional field, or
// the zero value when the document does not carry it.
func optionalValue[T any](value *T) T {
if value == nil {
var zero T
return zero
}
return *value
}
@@ -24,6 +24,8 @@ type AssessmentReviewInputs struct {
ClientFocusLossMS int64
ClientClipboardCount int32
ClientFullscreenExit int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// AssessmentDuplicateQuery selects the pairs of attempts that share answers.
@@ -53,6 +55,17 @@ type AssessmentDuplicatePair struct {
type AssessmentSignalRepositories interface {
AssessmentSignals() AssessmentSignalRepository
AssessmentWorkLeases() AssessmentWorkLeaseRepository
}
// AssessmentWorkLeaseRepository keeps the hold of the single active work
// session of a real attempt. The caller holds the row lock of the attempt, so
// the lease of an attempt is read and written by one transaction at a time.
type AssessmentWorkLeaseRepository interface {
// Get returns the lease; found is false when the attempt never had one.
Get(ctx context.Context, attemptID domain.AssessmentAttemptID) (lease domain.AssessmentWorkLease, found bool, err error)
// Save stores the lease, replacing the previous one of the attempt.
Save(ctx context.Context, lease domain.AssessmentWorkLease) error
}
// AssessmentSignalRepository persists event metadata and the immutable
@@ -27,6 +27,10 @@ type SubmitAttemptAnswerCommand struct {
// Origin is the sender of the request. It feeds the server signals only and
// is not part of the idempotency fingerprint.
Origin RequestOrigin
// Client is the identifier of the open page, or empty when the request has
// none. A page that does not hold the work session is refused while another
// page does, and the refusal is not stored under the idempotency key.
Client string
}
type canonicalAttemptAnswerBody struct {
@@ -135,6 +139,9 @@ 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)
if err := service.workSessions.requireHolder(ctx, unit, current, command.Client, databaseTime); err != nil {
return fmt.Errorf("%s - check the holder of the work session: %w", location, err)
}
return service.persistSubmittedAnswer(ctx, unit, repository, scope, command, current, databaseTime, result)
}
@@ -65,6 +65,7 @@ type AttemptService struct {
clock func() time.Time
categoryDecisions AssessmentCategoryDecisionService
signalObserver *SignalObserver
workSessions *WorkSessions
}
// NewAttemptService fails at startup when a required dependency is missing.
@@ -538,6 +539,10 @@ type StartAttemptSessionCommand struct {
AttemptID domain.AssessmentAttemptID
ExpectedVersion int64
IdempotencyKey string
// Client is the identifier of the open page, or empty when the request has
// none. It is not part of the idempotency fingerprint: the refusal that it
// can cause is not stored.
Client string
}
type canonicalAttemptSessionBody struct {
@@ -651,6 +656,9 @@ func (service *AttemptService) startNewSession(
if err != nil {
return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - read database time after attempt lock: %w", location, err)
}
if err := service.workSessions.requireHolder(ctx, unit, current, command.Client, databaseTime.UTC().Truncate(time.Microsecond)); err != nil {
return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - check the holder of the work session: %w", location, err)
}
updated, _, err := repository.StartOrResumeSession(ctx, command.ActorID, command.AttemptID, command.ExpectedVersion, databaseTime)
if errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict) || errors.Is(err, domain.ErrAssessmentAttemptVersionConflict) {
return outbound.AssessmentAttemptSessionResult{}, fmt.Errorf("%s - check expected version: %w", location, ErrAttemptVersionConflict)
@@ -18,10 +18,12 @@ import (
// every candidate acknowledges the new wording. Acknowledgements are stored per
// version, so one given for an earlier version never counts for this one.
//
// Version 3 describes the watermark of the task screen and text, which version
// 2 announced as planned; version 2 added the attempt measures to the text;
// version 1 listed signals only.
const CurrentSignalNoticeVersion int32 = 3
// Version 4 added the screenshot-key and developer-tools hints, the User-Agent
// digest, and the one-open-page rule, and says plainly that a screenshot or a
// photo of the screen cannot be prevented; version 3 described the watermark of
// the task screen and text, which version 2 announced as planned; version 2
// added the attempt measures to the text; version 1 listed signals only.
const CurrentSignalNoticeVersion int32 = 4
// ErrSignalNoticeVersionMismatch reports an acknowledgement for a notice
// version other than the one the server requires.
@@ -18,12 +18,13 @@ import (
)
// 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.
// session, a client network, and a User-Agent 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
AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest
// AssessmentDigestKeyVersion is the key generation of the digests above.
AssessmentDigestKeyVersion() int16
}
@@ -41,13 +42,15 @@ const (
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.
// RequestOrigin is what the HTTP adapter knows about the sender of an answer, a
// signal batch, or a work session hold: the authenticated session, the limiter
// key of the client address, and the User-Agent. It is used only to make
// digests and is never stored or logged. An empty ClientKey means the address
// could not be resolved, and an empty UserAgent that the request had none.
type RequestOrigin struct {
SessionID uuid.UUID
ClientKey string
UserAgent string
}
// SignalObserver records server-side facts of real attempts and schedules the
@@ -150,9 +153,9 @@ func answeredSince(snapshot domain.AssessmentAttemptSnapshot) bool {
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
// recordOrigin stores the session, network, and User-Agent digests of an
// accepted request when they differ from the last stored mark, which is enough
// to count session alternations, distinct networks, and distinct agents. 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,
@@ -178,11 +181,15 @@ func (observer *SignalObserver) recordOrigin(
if origin.ClientKey != "" {
mark.NetworkDigest = observer.digester.AssessmentNetworkDigest(attemptID.UUID(), origin.ClientKey)
}
if origin.UserAgent != "" {
mark.AgentDigest = observer.digester.AssessmentAgentDigest(attemptID.UUID(), origin.UserAgent)
}
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 {
if found && last.SessionDigest == mark.SessionDigest && last.NetworkDigest == mark.NetworkDigest &&
last.AgentDigest == mark.AgentDigest && last.KeyVersion == mark.KeyVersion {
return nil
}
if err := repository.SaveOriginMark(ctx, mark); err != nil {
@@ -409,8 +416,10 @@ func evaluateReview(
measures := domain.AssessmentReviewMeasures{
AnsweredItems: times.Answered, FastAnswers: times.Fast, DeviatingAnswers: times.Deviating,
ParallelAlternations: anomalies.ParallelAlternations, ExtraNetworks: anomalies.ExtraNetworks,
ExtraAgents: anomalies.ExtraAgents,
ClientFocusLossMS: inputs.ClientFocusLossMS, ClientClipboardEvents: inputs.ClientClipboardCount,
ClientFullscreenExits: inputs.ClientFullscreenExit,
ClientFullscreenExits: inputs.ClientFullscreenExit, ClientScreenshotKeys: inputs.ClientScreenshotKeys,
ClientDevtoolsOpens: inputs.ClientDevtoolsOpens,
}
if len(best) > 0 {
measures.DuplicateEvidenceBits = best[0].EvidenceBits
@@ -38,6 +38,14 @@ func (signalDigesterFake) AssessmentNetworkDigest(attemptID uuid.UUID, clientKey
return domain.AssessmentDigest(sha256.Sum256(append(attemptID[:], clientKey...)))
}
func (signalDigesterFake) AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest {
return domain.AssessmentDigest(sha256.Sum256(append(append([]byte("agent:"), attemptID[:]...), userAgent...)))
}
func (signalDigesterFake) AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest {
return domain.AssessmentDigest(sha256.Sum256(append(append([]byte("client:"), attemptID[:]...), clientID...)))
}
func (signalDigesterFake) AssessmentDigestKeyVersion() int16 { return 7 }
// signalRepositoryFake records the writes of the observer and the job. The
@@ -698,3 +706,84 @@ func TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged(t *testing.T) {
}
}
}
func TestOriginMarkKeepsTheUserAgentOnlyAsAKeyedDigestAndMarksOnlyChanges(t *testing.T) {
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
unit := newSignalUnitFake()
const chrome = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/141.0 Safari/537.36"
const phone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148"
origin := RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.77", UserAgent: chrome}
record := func(source domain.AssessmentOriginSource, origin RequestOrigin) {
t.Helper()
if err := observer.recordOrigin(context.Background(), unit.repository, attempt.ID(), source, signalReviewTestTime, origin); err != nil {
t.Fatalf("recordOrigin() error = %v", err)
}
}
record(domain.AssessmentOriginWorkSession, origin)
record(domain.AssessmentOriginAnswer, origin)
if len(unit.repository.marks) != 1 {
t.Fatalf("stored %d marks for two requests of one origin, want one", len(unit.repository.marks))
}
first := unit.repository.marks[0]
if first.Source != domain.AssessmentOriginWorkSession || first.AgentDigest.IsZero() || first.AgentDigest != (signalDigesterFake{}).AssessmentAgentDigest(attempt.ID().UUID(), chrome) {
t.Fatalf("first mark = %+v, want a work session mark with the keyed User-Agent digest", first)
}
// The same session and network with another browser is a change of its own.
switched := origin
switched.UserAgent = phone
record(domain.AssessmentOriginAnswer, switched)
if len(unit.repository.marks) != 2 || unit.repository.marks[1].AgentDigest == first.AgentDigest {
t.Fatalf("marks after a User-Agent change = %d, want a second mark with another digest", len(unit.repository.marks))
}
// A request without a User-Agent stores no agent digest.
bare := origin
bare.UserAgent = ""
unit.repository.marks = nil
record(domain.AssessmentOriginSignals, bare)
if len(unit.repository.marks) != 1 || !unit.repository.marks[0].AgentDigest.IsZero() {
t.Fatalf("marks = %+v, want one mark without an agent digest", unit.repository.marks)
}
stored := fmt.Sprintf("%+v", first)
for _, secret := range []string{"Mozilla", "Macintosh", "Chrome", chrome} {
if strings.Contains(stored, secret) {
t.Fatalf("the stored mark contains %q, want the User-Agent only as a digest", secret)
}
}
}
func TestEvaluateReviewCountsExtraAgentsAndCaptureHintsWithoutRaisingBeyondAttention(t *testing.T) {
signals := domain.DemoAssessmentSignalPolicyWithCaptureHints()
productPolicy := domain.DemoProductPolicyV3()
productPolicy.Assessment.Signals = &signals
policy := signalReviewPolicyVersion(t, 4, productPolicy)
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
repository := &signalRepositoryFake{inputs: outbound.AssessmentReviewInputs{
ClientScreenshotKeys: 500, ClientDevtoolsOpens: 500,
Marks: []domain.AssessmentOriginMark{
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{1}},
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{2}},
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{3}},
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{4}},
{ID: uuid.New(), SessionDigest: domain.AssessmentDigest{1}, AgentDigest: domain.AssessmentDigest{5}},
},
}}
if err := evaluateReview(context.Background(), repository, attempt.ID(), policy, signalReviewTestTime); err != nil {
t.Fatalf("evaluateReview() error = %v", err)
}
if len(repository.reviews) != 1 {
t.Fatalf("stored %d reviews, want one", len(repository.reviews))
}
review := repository.reviews[0]
if review.Measures.ExtraAgents != 4 || review.Measures.ClientScreenshotKeys != 500 || review.Measures.ClientDevtoolsOpens != 500 {
t.Fatalf("measures = %+v, want 4 extra agents and the capture hint counts", review.Measures)
}
if review.Outcome.Band != domain.AssessmentReviewBandAttention {
t.Fatalf("band = %s, want attention: capture hints and extra agents alone never reach review", review.Outcome.Band)
}
}
@@ -0,0 +1,262 @@
package assessment
import (
"context"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var (
// ErrAttemptWorkSessionBusy reports that another open page holds the work
// session of the attempt. It lasts until that page releases the session or
// stops renewing it, so it is never stored under an idempotency key.
ErrAttemptWorkSessionBusy = errors.New("assessment work session is held by another page")
// ErrAttemptWorkSessionState reports an attempt that has no work session to
// hold: a training run, or an attempt that has ended or is past its deadline.
ErrAttemptWorkSessionState = errors.New("assessment attempt has no work session to hold")
// ErrInvalidWorkSessionClient reports a page identifier of the wrong shape.
ErrInvalidWorkSessionClient = errors.New("invalid assessment work session client")
)
const (
minWorkClientBytes = 16
maxWorkClientBytes = 64
)
// WorkSessionDigester derives the keyed digest that stands for an open page in
// the stored lease. The digest binds the attempt and cannot be turned back into
// the identifier the page generated.
type WorkSessionDigester interface {
AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest
AssessmentDigestKeyVersion() int16
}
// WorkSessions keeps one open page per real attempt: the page that holds the
// work session of the attempt works on it, and any other page is refused until
// the holder closes or stops renewing. It does not change an attempt, a result,
// or a score, and it is a convenience rule, not a security boundary: a client
// that never holds the session is refused only while another page does.
type WorkSessions struct {
transactor outbound.Transactor
digester WorkSessionDigester
observer *SignalObserver
}
// NewWorkSessions fails at startup when a dependency is missing.
func NewWorkSessions(transactor outbound.Transactor, digester WorkSessionDigester) (*WorkSessions, error) {
if transactor == nil || digester == nil {
return nil, errors.New("assessment.NewWorkSessions - every dependency must be set")
}
return &WorkSessions{transactor: transactor, digester: digester}, nil
}
// WithSignalObserver makes every hold write an origin mark, which is when a
// switch to another session, network, or User-Agent is noticed.
func (sessions *WorkSessions) WithSignalObserver(observer *SignalObserver) *WorkSessions {
sessions.observer = observer
return sessions
}
// WithWorkSessions makes the answer and session commands refuse a page that
// does not hold the work session while another page does.
func (service *AttemptService) WithWorkSessions(sessions *WorkSessions) *AttemptService {
service.workSessions = sessions
return service
}
// HoldWorkSessionCommand is one hold or renewal from an open page.
type HoldWorkSessionCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
// Client is the identifier the page generated when it loaded.
Client string
Origin RequestOrigin
}
// WorkSessionHold is the answer to a hold: when it ends unless renewed, and how
// often the page renews it.
type WorkSessionHold struct {
HeldUntil time.Time
RenewEvery time.Duration
}
// Hold makes the page the holder of the work session, or renews its hold. It
// refuses with ErrAttemptWorkSessionBusy while another page holds it. The
// request origin of an accepted hold is recorded for the server signals.
func (sessions *WorkSessions) Hold(ctx context.Context, command HoldWorkSessionCommand) (WorkSessionHold, error) {
const location = "WorkSessions.Hold"
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || !validWorkClient(command.Client) {
return WorkSessionHold{}, fmt.Errorf("%s - candidate, attempt, and page identifier are required: %w", location, ErrInvalidWorkSessionClient)
}
var hold WorkSessionHold
err := sessions.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
attempts := unit.AssessmentAttempts()
kind, err := attempts.GetKindForCandidate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - read owner-scoped attempt kind: %w", location, err)
}
if !isRealAttemptKind(kind) {
return fmt.Errorf("%s - a training run has no protected work session: %w", location, ErrAttemptWorkSessionState)
}
if err := lockSessionConsent(ctx, unit, command.ActorID, kind); err != nil {
return fmt.Errorf("%s - authorize work session: %w", location, err)
}
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time after attempt lock: %w", location, err)
}
now := databaseTime.UTC().Truncate(time.Microsecond)
if !attempt.IsActive() || !now.Before(attempt.ExpiresAt()) {
return fmt.Errorf("%s - attempt is terminal or expired: %w", location, ErrAttemptWorkSessionState)
}
hold, err = sessions.holdInTransaction(ctx, unit, attempt.ID(), command, now)
return err
})
if err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - transaction: %w", location, err)
}
return hold, nil
}
func (sessions *WorkSessions) holdInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
attemptID domain.AssessmentAttemptID,
command HoldWorkSessionCommand,
now time.Time,
) (WorkSessionHold, error) {
const location = "WorkSessions.holdInTransaction"
leases := unit.AssessmentWorkLeases()
holder := sessions.digester.AssessmentWorkClientDigest(attemptID.UUID(), command.Client)
current, found, err := leases.Get(ctx, attemptID)
if err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - read lease: %w", location, err)
}
if found && !current.AdmitsHolder(holder, now) {
return WorkSessionHold{}, fmt.Errorf("%s - another page holds the session until %s: %w", location, current.HeldUntil().Format(time.RFC3339), ErrAttemptWorkSessionBusy)
}
next := current.Held(attemptID, holder, sessions.digester.AssessmentDigestKeyVersion(), now)
if err := leases.Save(ctx, next); err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - store lease: %w", location, err)
}
if err := sessions.observer.recordOrigin(ctx, unit.AssessmentSignals(), attemptID, domain.AssessmentOriginWorkSession, now, command.Origin); err != nil {
return WorkSessionHold{}, fmt.Errorf("%s - record request origin: %w", location, err)
}
return WorkSessionHold{HeldUntil: next.HeldUntil(), RenewEvery: domain.AssessmentWorkLeaseRenewEvery}, nil
}
// ReleaseWorkSessionCommand is the release of a page that is closing.
type ReleaseWorkSessionCommand struct {
ActorID uuid.UUID
AttemptID domain.AssessmentAttemptID
Client string
}
// Release frees the work session when the page holds it. It reveals nothing:
// a page that is not the holder, and an attempt that is not held, are no-ops.
func (sessions *WorkSessions) Release(ctx context.Context, command ReleaseWorkSessionCommand) error {
const location = "WorkSessions.Release"
if command.ActorID == uuid.Nil || command.AttemptID.IsZero() || !validWorkClient(command.Client) {
return fmt.Errorf("%s - candidate, attempt, and page identifier are required: %w", location, ErrInvalidWorkSessionClient)
}
err := sessions.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireAttemptCandidate(ctx, unit, command.ActorID, location); err != nil {
return err
}
attempts := unit.AssessmentAttempts()
attempt, err := attempts.GetForCandidateForUpdate(ctx, command.ActorID, command.AttemptID)
if errors.Is(err, outbound.ErrAssessmentAttemptNotFound) {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, ErrAttemptNotFound)
}
if err != nil {
return fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
}
leases := unit.AssessmentWorkLeases()
current, found, err := leases.Get(ctx, attempt.ID())
if err != nil {
return fmt.Errorf("%s - read lease: %w", location, err)
}
if !found {
return nil
}
databaseTime, err := unit.AssessmentBank().DatabaseTime(ctx)
if err != nil {
return fmt.Errorf("%s - read database time: %w", location, err)
}
released := current.ReleasedBy(sessions.digester.AssessmentWorkClientDigest(attempt.ID().UUID(), command.Client), databaseTime.UTC().Truncate(time.Microsecond))
if released.ReleasedAt.Equal(current.ReleasedAt) {
return nil
}
if err := leases.Save(ctx, released); err != nil {
return fmt.Errorf("%s - store released lease: %w", location, err)
}
return nil
})
if err != nil {
return fmt.Errorf("%s - transaction: %w", location, err)
}
return nil
}
// requireHolder refuses a command from a page that does not hold the work
// session while another page does. The caller holds the row lock of the attempt
// and passes the database time read after it. A page that sent no identifier
// counts as one anonymous page, so omitting the header is no way around the
// rule; an attempt that nobody holds accepts every page. A training run, and a
// service without work sessions, are never refused.
func (sessions *WorkSessions) requireHolder(
ctx context.Context,
unit outbound.UnitOfWork,
attempt domain.AssessmentAttempt,
client string,
now time.Time,
) error {
const location = "WorkSessions.requireHolder"
if sessions == nil || !isRealAttemptKind(attempt.Kind()) {
return nil
}
current, found, err := unit.AssessmentWorkLeases().Get(ctx, attempt.ID())
if err != nil {
return fmt.Errorf("%s - read lease: %w", location, err)
}
if !found || current.AdmitsHolder(sessions.digester.AssessmentWorkClientDigest(attempt.ID().UUID(), client), now) {
return nil
}
return fmt.Errorf("%s - another page holds the work session: %w", location, ErrAttemptWorkSessionBusy)
}
// validWorkClient accepts 16 to 64 characters of A-Z, a-z, 0-9, '_' and '-',
// the shape of a random identifier encoded for a header.
func validWorkClient(value string) bool {
if len(value) < minWorkClientBytes || len(value) > maxWorkClientBytes {
return false
}
for index := range len(value) {
character := value[index]
if character >= 'a' && character <= 'z' || character >= 'A' && character <= 'Z' ||
character >= '0' && character <= '9' || character == '_' || character == '-' {
continue
}
return false
}
return true
}
@@ -0,0 +1,201 @@
package assessment
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// leaseRepositoryFake keeps the lease of the attempts in memory.
type leaseRepositoryFake struct {
leases map[domain.AssessmentAttemptID]domain.AssessmentWorkLease
}
func (repository *leaseRepositoryFake) Get(_ context.Context, attemptID domain.AssessmentAttemptID) (domain.AssessmentWorkLease, bool, error) {
lease, found := repository.leases[attemptID]
return lease, found, nil
}
func (repository *leaseRepositoryFake) Save(_ context.Context, lease domain.AssessmentWorkLease) error {
if err := lease.Validate(); err != nil {
return err
}
repository.leases[lease.AttemptID] = lease
return nil
}
// workUnitFake offers the lease and the signal repositories of one unit of work.
type workUnitFake struct {
outbound.UnitOfWork
leases *leaseRepositoryFake
signals *signalRepositoryFake
}
func newWorkUnitFake() *workUnitFake {
return &workUnitFake{
leases: &leaseRepositoryFake{leases: map[domain.AssessmentAttemptID]domain.AssessmentWorkLease{}},
signals: &signalRepositoryFake{},
}
}
func (unit *workUnitFake) AssessmentWorkLeases() outbound.AssessmentWorkLeaseRepository {
return unit.leases
}
func (unit *workUnitFake) AssessmentSignals() outbound.AssessmentSignalRepository {
return unit.signals
}
const (
pageOne = "page-one-AAAAAAAAAAAAAAAA"
pageTwo = "page-two-BBBBBBBBBBBBBBBB"
)
func newTestWorkSessions(t *testing.T) *WorkSessions {
t.Helper()
observer, err := NewSignalObserver(signalDigesterFake{})
if err != nil {
t.Fatalf("NewSignalObserver() error = %v", err)
}
sessions, err := NewWorkSessions(&transactorStub{}, signalDigesterFake{})
if err != nil {
t.Fatalf("NewWorkSessions() error = %v", err)
}
return sessions.WithSignalObserver(observer)
}
// transactorStub is never run: the tests call the steps that take a unit.
type transactorStub struct{ outbound.Transactor }
func hold(t *testing.T, sessions *WorkSessions, unit *workUnitFake, attemptID domain.AssessmentAttemptID, client string, now time.Time) error {
t.Helper()
_, err := sessions.holdInTransaction(context.Background(), unit, attemptID, HoldWorkSessionCommand{
ActorID: uuid.New(), AttemptID: attemptID, Client: client,
Origin: RequestOrigin{SessionID: uuid.New(), ClientKey: "198.51.100.8", UserAgent: "TestBrowser/1.0"},
}, now)
return err
}
func TestASecondPageIsRefusedUntilTheFirstOneIsClosed(t *testing.T) {
sessions := newTestWorkSessions(t)
unit := newWorkUnitFake()
attemptID := domain.AssessmentAttemptID(uuid.New())
now := signalReviewTestTime
if err := hold(t, sessions, unit, attemptID, pageOne, now); err != nil {
t.Fatalf("the first page was refused: %v", err)
}
if err := hold(t, sessions, unit, attemptID, pageOne, now.Add(15*time.Second)); err != nil {
t.Fatalf("the holder was refused its renewal: %v", err)
}
err := hold(t, sessions, unit, attemptID, pageTwo, now.Add(20*time.Second))
if !errors.Is(err, ErrAttemptWorkSessionBusy) {
t.Fatalf("second page error = %v, want ErrAttemptWorkSessionBusy", err)
}
// A refused page changes nothing: the first page still holds the session.
if lease := unit.leases.leases[attemptID]; lease.Holder != (signalDigesterFake{}).AssessmentWorkClientDigest(attemptID.UUID(), pageOne) {
t.Fatalf("the refusal changed the holder: %+v", lease)
}
// The first page closes: the second takes over at once.
lease := unit.leases.leases[attemptID]
unit.leases.leases[attemptID] = lease.ReleasedBy(lease.Holder, now.Add(30*time.Second))
if err := hold(t, sessions, unit, attemptID, pageTwo, now.Add(31*time.Second)); err != nil {
t.Fatalf("the second page was refused after the first one was released: %v", err)
}
if err := hold(t, sessions, unit, attemptID, pageOne, now.Add(40*time.Second)); !errors.Is(err, ErrAttemptWorkSessionBusy) {
t.Fatalf("the closed page got the session back while the second holds it: %v", err)
}
// A page that is killed stops renewing, and its hold ends by itself.
if err := hold(t, sessions, unit, attemptID, pageOne, now.Add(31*time.Second+domain.AssessmentWorkLeaseDuration)); err != nil {
t.Fatalf("the first page was refused after the second one stopped renewing: %v", err)
}
}
func TestEveryHoldRecordsTheOriginWithTheUserAgentDigestOnly(t *testing.T) {
sessions := newTestWorkSessions(t)
unit := newWorkUnitFake()
attemptID := domain.AssessmentAttemptID(uuid.New())
if err := hold(t, sessions, unit, attemptID, pageOne, signalReviewTestTime); err != nil {
t.Fatalf("hold error = %v", err)
}
if len(unit.signals.marks) != 1 {
t.Fatalf("stored %d marks, want one", len(unit.signals.marks))
}
mark := unit.signals.marks[0]
if mark.Source != domain.AssessmentOriginWorkSession || mark.AgentDigest.IsZero() ||
mark.AgentDigest != (signalDigesterFake{}).AssessmentAgentDigest(attemptID.UUID(), "TestBrowser/1.0") {
t.Fatalf("mark = %+v, want a work session mark with the keyed digest of the User-Agent", mark)
}
if strings.Contains(fmt.Sprintf("%+v", mark), "TestBrowser") {
t.Fatal("the mark carries the raw User-Agent")
}
}
func TestACommandFromAPageThatDoesNotHoldTheSessionIsRefusedWhileAnotherDoes(t *testing.T) {
sessions := newTestWorkSessions(t)
unit := newWorkUnitFake()
policy := signalReviewPolicyVersion(t, 3, domain.DemoProductPolicyV3())
attempt := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindRoot)
now := signalReviewTestTime
check := func(client string, at time.Time) error {
return sessions.requireHolder(context.Background(), unit, attempt, client, at)
}
if err := check(pageTwo, now); err != nil {
t.Fatalf("an attempt that nobody holds refused a page: %v", err)
}
if err := hold(t, sessions, unit, attempt.ID(), pageOne, now); err != nil {
t.Fatalf("hold error = %v", err)
}
if err := check(pageOne, now.Add(time.Second)); err != nil {
t.Fatalf("the holder was refused: %v", err)
}
if err := check(pageTwo, now.Add(time.Second)); !errors.Is(err, ErrAttemptWorkSessionBusy) {
t.Fatalf("another page error = %v, want ErrAttemptWorkSessionBusy", err)
}
// Leaving the identifier out is no way around the rule: it is a page of its own.
if err := check("", now.Add(time.Second)); !errors.Is(err, ErrAttemptWorkSessionBusy) {
t.Fatalf("a request without an identifier error = %v, want ErrAttemptWorkSessionBusy", err)
}
if err := check(pageTwo, now.Add(domain.AssessmentWorkLeaseDuration)); err != nil {
t.Fatalf("a page was refused after the hold expired: %v", err)
}
// A training run has no protected work session, and a service without work
// sessions keeps every command as it was.
training := signalReviewAttempt(t, policy, domain.AssessmentAttemptKindDemoExpress)
unit.leases.leases[training.ID()] = domain.AssessmentWorkLease{}.Held(training.ID(), domain.AssessmentDigest{9}, 7, now)
if err := sessions.requireHolder(context.Background(), unit, training, pageTwo, now); err != nil {
t.Fatalf("a training run was refused: %v", err)
}
var none *WorkSessions
if err := none.requireHolder(context.Background(), unit, attempt, pageTwo, now); err != nil {
t.Fatalf("a service without work sessions refused a page: %v", err)
}
}
func TestPageIdentifiersHaveTheShapeOfARandomHeaderValue(t *testing.T) {
for _, valid := range []string{pageOne, strings.Repeat("a", 16), strings.Repeat("Z", 64), "abc_DEF-1234567890"} {
if !validWorkClient(valid) {
t.Errorf("validWorkClient(%q) = false, want true", valid)
}
}
for _, invalid := range []string{"", "short", strings.Repeat("a", 15), strings.Repeat("a", 65), "has space 1234567890", "plus+plus+plus+plus+", "caf\u00e9-caf\u00e9-caf\u00e9-caf\u00e9"} {
if validWorkClient(invalid) {
t.Errorf("validWorkClient(%q) = true, want false", invalid)
}
}
if _, err := NewWorkSessions(nil, signalDigesterFake{}); err == nil {
t.Fatal("NewWorkSessions(nil transactor) succeeded")
}
}
@@ -34,6 +34,8 @@ const (
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
labelWatermark = "lincodex/assessment/watermark/v1"
labelSignalAgent = "lincodex/assessment/signal-agent/v1"
labelWorkClient = "lincodex/assessment/work-client/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
@@ -55,6 +57,8 @@ type Keyring struct {
signalNetworkKey []byte
resultCursorKey []byte
watermarkKey []byte
signalAgentKey []byte
workClientKey []byte
}
// NewKeyring derives the purpose keys from secret.
@@ -76,6 +80,8 @@ func NewKeyring(secret []byte) (*Keyring, error) {
signalNetworkKey: derive(secret, labelSignalNetwork),
resultCursorKey: derive(secret, labelResultCursor),
watermarkKey: derive(secret, labelWatermark),
signalAgentKey: derive(secret, labelSignalAgent),
workClientKey: derive(secret, labelWorkClient),
}, nil
}
@@ -242,3 +248,23 @@ func (keyring *Keyring) AssessmentWatermarkSeed(attemptID uuid.UUID) domain.Asse
mac.Write(attemptID[:])
return domain.AssessmentWatermarkSeed(mac.Sum(nil))
}
// AssessmentAgentDigest identifies the User-Agent of a request inside one
// attempt. The digest changes with the attempt, so it cannot link attempts or
// fingerprint a browser across them, and the raw value is never stored.
func (keyring *Keyring) AssessmentAgentDigest(attemptID uuid.UUID, userAgent string) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.signalAgentKey)
mac.Write(attemptID[:])
mac.Write([]byte(userAgent))
return domain.AssessmentDigest(mac.Sum(nil))
}
// AssessmentWorkClientDigest identifies the open page that holds the work
// session of an attempt from the identifier the page generated. The digest
// binds the attempt, so the value is not reusable and not linkable.
func (keyring *Keyring) AssessmentWorkClientDigest(attemptID uuid.UUID, clientID string) domain.AssessmentDigest {
mac := hmac.New(sha256.New, keyring.workClientKey)
mac.Write(attemptID[:])
mac.Write([]byte(clientID))
return domain.AssessmentDigest(mac.Sum(nil))
}
@@ -147,11 +147,47 @@ func TestAssessmentWatermarkSeedIsKeyedBoundToTheAttemptAndSeparateFromTheDigest
}
// The purpose key is its own: no other digest of the attempt equals the seed.
if seed == domain.AssessmentWatermarkSeed(keyring.AssessmentSessionDigest(attempt, attempt)) ||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentNetworkDigest(attempt, string(attempt[:]))) {
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentNetworkDigest(attempt, string(attempt[:]))) ||
seed == domain.AssessmentWatermarkSeed(keyring.AssessmentAgentDigest(attempt, string(attempt[:]))) {
t.Fatal("the watermark seed shares a key with another assessment digest")
}
}
func TestAssessmentAgentAndWorkClientDigestsAreKeyedBoundToTheAttemptAndSeparate(t *testing.T) {
keyring, err := NewKeyring(bytes.Repeat([]byte{1}, MinKeySecretBytes))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
attempt, otherAttempt := uuid.New(), uuid.New()
const agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/141.0"
agentDigest := keyring.AssessmentAgentDigest(attempt, agent)
if agentDigest != keyring.AssessmentAgentDigest(attempt, agent) {
t.Fatal("the User-Agent digest is not deterministic")
}
if agentDigest == keyring.AssessmentAgentDigest(otherAttempt, agent) {
t.Fatal("one User-Agent has the same digest in two attempts, so attempts could be linked")
}
if agentDigest == keyring.AssessmentAgentDigest(attempt, agent+" ") {
t.Fatal("two User-Agents have the same digest")
}
clientDigest := keyring.AssessmentWorkClientDigest(attempt, "page-one-AAAAAAAAAAAAAAAA")
if clientDigest != keyring.AssessmentWorkClientDigest(attempt, "page-one-AAAAAAAAAAAAAAAA") {
t.Fatal("the page digest is not deterministic")
}
if clientDigest == keyring.AssessmentWorkClientDigest(otherAttempt, "page-one-AAAAAAAAAAAAAAAA") ||
clientDigest == keyring.AssessmentWorkClientDigest(attempt, "page-two-BBBBBBBBBBBBBBBB") {
t.Fatal("the page digest does not separate attempts and pages")
}
// The empty identifier of a request without the header is a digest of its own.
if keyring.AssessmentWorkClientDigest(attempt, "").IsZero() {
t.Fatal("the digest of the anonymous page is empty")
}
// Each purpose has its own key.
if agentDigest == keyring.AssessmentWorkClientDigest(attempt, agent) || agentDigest == keyring.AssessmentNetworkDigest(attempt, agent) {
t.Fatal("the User-Agent digest shares a key with another purpose")
}
}
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
if err != nil {
+15
View File
@@ -710,6 +710,21 @@ Implemented for real attempts (root and corrective). A training run (`demo_expre
- Accessibility. Some speech synthesizers and braille displays may announce zero-width characters or break a word at them; this was not tested with a real screen reader. The page therefore puts every run of invisible characters in an `aria-hidden` element: the accessibility tree holds the words only (a Playwright check reads the tree with `ariaSnapshot`, and a Vitest check strips the hidden elements from the markup), while the document keeps the characters so that anything copied from it carries the mark. The wordings are ordinary words, and no whitespace variants are used, because a non-breaking space is not guaranteed to be silent everywhere.
- What it does not do. A screenshot, a photo of the screen, or retyping cannot be prevented in a browser. The watermark is evidence for a manual review and an appeal, never an automatic decision; no operation shows it to an employer, and the candidate sees only the code of their own attempt.
### Capture hints, one open window, and what they cannot do
Implemented for real attempts (root and corrective). A training run (`demo_express`) has none of it. Hardened proctoring here has no camera, no microphone, no screen recording, no screenshots, and no clipboard contents; it consists of weak signals for a manual review and one rule about open windows. Code: `backend/internal/domain/assessment_signal.go`, `assessment_signal_review.go`, `assessment_signal_policy.go`, and `assessment_work_lease.go`; `backend/internal/usecase/assessment/work_session.go` and the observer in `signal_review.go`; migration `backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql`; the operations `HoldMyAssessmentWorkSession` and `ReleaseMyAssessmentWorkSession`; and `frontend/src/features/assessment-signals/` and `frontend/src/features/assessment-work-session/`.
- A screenshot or a phone photo cannot be prevented. A browser page cannot block the operating system or another program from capturing the screen, cannot see a camera, and cannot see a second device, a remote desktop, or a virtual machine. The page therefore never tries: it does not cancel a key, does not blank the page on a key, and does not read any image. What it can do is report that a screenshot key was pressed, tie a leaked statement or screenshot back to its attempt (see [Watermark of the task text](#watermark-of-the-task-text)), and send both to a manual review.
- Signals lead to a review and an appeal, never to an automatic downgrade. The signals only raise the review band, which changes no result, category, or quota; the employer never sees a signal or a band, and the candidate sees no band. Notice version 4 says all of this plainly.
- Screenshot keys. The page reports `screenshot_key` when it sees PrintScreen (also with Alt), Cmd+Shift+3, 4, or 5 (macOS), or Win+Shift+S, on the key press or release, once per second at most. The operating system takes many of these keys before the page, a key-less screenshot sends nothing, and holding a key is not told from pressing it, so the event proves only that a key was pressed. It carries the item and a client timestamp and no measurement.
- Developer tools. The page reports `devtools_open` when the outer window becomes more than 160 px larger than the page in width or height, which is what a docked panel does, on a resize and on a two-second timer, at most once per minute. It is a heuristic with false positives (a sidebar, zoom, a resized window) and false negatives (a detached panel, other windows), so it too is only a weak hint.
- Policy and band. Both kinds are stored as events (the check constraints of `assessment_signal_events` allow them without a measurement) and counted per attempt (`client_screenshot_keys`, `client_devtools_opens` in `assessment_attempt_reviews`). Thresholds are optional fields of the policy section `assessment.signals`: `client_screenshot_keys_attention` and `client_devtools_attention` are client thresholds, so they raise a normal band to attention and never above it, and `extra_agents_attention` with `extra_agents_review` joins the weak group of parallel sessions and extra networks, which alone reaches attention at most and review only beside a strong signal. A zero or absent threshold leaves the signal out, so a version published before these fields keeps its band, its document, and its content hash (a test checks that its document does not contain the new keys and re-encodes unchanged). The demo policies are not edited; `DemoAssessmentSignalPolicyWithCaptureHints` in `assessment_signal_policy.go` lists agreed starting values (three screenshot keys, one detection, two extra User-Agents), which no study supports, and the integration test publishes them in its own policy version.
- User-Agent digest. The HTTP boundary cuts the User-Agent to 512 bytes and hands it to the usecase, which stores only `HMAC-SHA-256` of it under a key derived from `IDENTITY_KEY_SECRET` (label `lincodex/assessment/signal-agent/v1`) bound to the attempt, in the new column `agent_digest` of `assessment_attempt_origin_marks`. The raw value is never stored or logged. A mark is written when the session, the network, or the User-Agent differs from the last mark, so the list stays short; `extra_agents` counts the distinct digests beyond the first. A browser that updates itself during an attempt, or a candidate who moves to another device, adds one, so it is a weak signal.
- One open window. `assessment_attempt_work_leases` holds one row per real attempt: a keyed digest of an identifier that each open page generates when it loads (`X-Attempt-Client`, 16 to 64 characters of `A-Za-z0-9_-`), when it took the session, when it last renewed it, and when it released it. `PUT .../work-session` holds or renews the session for 120 seconds (`domain.AssessmentWorkLeaseDuration`) and tells the page to renew every 15 seconds; `DELETE .../work-session` releases it and answers 204 whatever it did. The page holds the session before it starts or resumes work, renews it while it works, releases it when it leaves or closes (`pagehide`), and stops with an explanation if a renewal is refused. While another page holds the session, the session start and the answer of any other page, or of a request without the header (one anonymous page), answer 409 `state_conflict` and change nothing; the check runs under the attempt row lock after the database time is read, before any attempt change, and the refusal is not stored under the idempotency key, so the holder can reuse the key. An attempt that nobody holds, a released hold, and a hold that stopped renewing (after at most two minutes) admit every page, and `StartSession` and `SubmitAnswer` of a service built without work sessions are unchanged.
- How it relates to `MaxSessions` and `IdleTimeoutSeconds`. Those attempt policy limits describe the sequential work sessions of an attempt: a new one starts only after the idle timeout, and the count is bounded. The hold is the concurrency dimension inside the current work session. It starts, extends, and consumes no work session of that policy, does not change the attempt version, and is not stored in the attempt row.
- Limits of the rule. It is a one-page-at-a-time rule, not a security boundary: a client that never holds the session is refused only while another page holds it, a candidate can always continue after the hold is released or has expired, and two windows of one candidate are not told from two people. The hold is renewed by a page timer, so a browser that throttles a background tab to one tick a minute still renews within the two minutes.
- Operator reading. `make -C backend assessment-review ARGS='inspect ...'` prints the new counts `extra_agents`, `client_screenshot_keys`, and `client_devtools_opens` next to the old ones; the note at its end repeats that browser signals can be forged and that a screenshot or a phone photo cannot be prevented or seen by the page.
### Skill evidence
Implemented as a stored projection of the immutable assessment results, with two reads: the candidate's own list and the permitted projection of a currently visible card. The match search reads the organization projection (see [Matching and explanations](#matching-and-explanations)); no percentile reads it yet.
+1
View File
@@ -441,6 +441,7 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
- 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.
- Capture hints and the one-window rule add three counts to this output (`extra_agents`, `client_screenshot_keys`, `client_devtools_opens`) and the reason `extra_agents`; they raise the band only through optional thresholds of the policy section (`client_screenshot_keys_attention`, `client_devtools_attention`, `extra_agents_attention`, `extra_agents_review`), which a version published earlier does not have and the demo policies do not set. The rows that hold them are the same kind of data as the others: keyed digests and counts, and no User-Agent, page identifier, address, or image. A screenshot or a phone photo cannot be prevented or seen, so these signals lead only to a manual check, never to an automatic downgrade ([details](ARCHITECTURE.md#capture-hints-one-open-window-and-what-they-cannot-do)). Rolling migration 50 back is refused while the new events, marks, or counts exist.
- 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.
+10 -2
View File
@@ -540,16 +540,24 @@ The tests prove the stored facts, the policy pinning, the job-based computation,
## Assessment lockdown tests
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 3 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for the current version, and its versions follow `CurrentSignalNoticeVersion`.
Vitest runs in Node without a DOM, so the lockdown is checked in parts. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` covers support detection (including a browser without element fullscreen, such as iPhone Safari), that the request is issued synchronously inside the call so it stays in the click, and that a refusal is a result and not an exception. `model/cover.test.ts` is the table of when the task is covered: fullscreen exit, a hidden tab, a window without focus, a request in flight, and the mode without fullscreen. `ui/protected-region.test.tsx` renders the region with a fake lockdown and checks that a covered task leaves no text of the prompt or the options in the markup, that a cover for a left tab has no fullscreen button, and the explanation shown for an unsupported browser; `features/answer-assessment/ui/answer-form.test.tsx` checks that a concealed form renders nothing. The notice text version 4 and its list of measures are checked in `features/assessment-signals/ui/signal-notice.test.tsx`. In the backend, `usecase/assessment/signal_notice_test.go` checks that every version except the current one is refused, and `TestAssessmentSignalNoticeOverHTTP` checks over HTTP with PostgreSQL that a stored acknowledgement of version 1 does not count for the current version, and its versions follow `CurrentSignalNoticeVersion`.
Unit tests of the task protection: `model/task-guard.test.ts` runs the rules with small fake elements and events: selection, the context menu, and drag are cancelled on the task text and left alone in a field, a drop never fills a field, paste is refused in answer fields (and reported, so the screen can say so) and allowed in the code editor, the `beforeinput` routes of paste and drop are closed while typing and composing are never touched, and a copy or cut is refused when the target or the selection reaches into the task but not when it is inside a field. `features/answer-assessment/ui/answer-form.test.tsx` checks that only the code editor carries the paste exception.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 3. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
Two browser specs run against a mocked API, so they need no backend data and also run against the Vite server (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`) as well as in `make -C deploy test-e2e`; the mock is in `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: leaving fullscreen covers the task (its text is not in the page), sends a `fullscreen_exit` signal, and the continue button restores the task with the typed draft; leaving the tab covers the task and returning in fullscreen shows it; a browser without the fullscreen API shows the explanation and still takes the test from the keyboard; a refused fullscreen request continues without it; closing the notice without confirming leaves fullscreen and stores nothing. `assessment-task-protection.spec.ts`: the task text is not selectable, a select-all or scripted copy leaves no task text in the clipboard, the context menu and drag are cancelled on the task but not in a field, a field copies its own text, the text stays in the accessibility tree, and printing hides the task; an answer field refuses a paste, shows the notice, and the refused paste is sent as a `paste` signal with its size and without its text; the practice code editor accepts a paste and sends its size; an item is answered with the keyboard alone. The notice acknowledgement over the real backend is covered by the existing notice test in `assessment.spec.ts`, which now expects version 4. These specs show the page behavior in Chromium with a mocked server; they do not show behavior in other browsers, on a phone, with a real screen reader, or against a window manager that changes fullscreen on its own. The paste rule cannot see text that an on-screen keyboard inserts as typing.
## Assessment watermark tests
`backend/internal/domain/assessment_watermark_test.go` covers the mark: two attempts that were served one real generated variant get different marked statements whose canonical text and reference answer are equal; marking is deterministic and idempotent; the invisible run decodes to the visible code, survives a copy of two sentences, and a cut, padded, or mis-checked run is ignored; the accessible text holds the words only; the alignment of a stored statement with a leak reads only the phrases that it finds there (words around the statement, such as a quotation or a message, are ignored), the wording agreement of the attempt that wrote the text holds for every phrase group, other seeds disagree, a fragment yields the phrases of the fragment, an unrelated text aligns nothing, and another variant of the same family aligns for fewer characters than the leaked one; the pieces between the phrases are the same in every copy of a statement; the number guard keeps `at most` at the end of a sentence; codes parse the way an operator or OCR reads them. `usecase/assessment/watermark_test.go` checks that only root and corrective attempts are marked, that the stored snapshot is not changed, that the visible code equals the invisible one, and that a missing `Watermarker` leaves snapshots alone; `adapter/primary/http/v1/assessment_test.go` checks that every attempt response goes through the presenter and that a presenter failure is an error. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) checks over HTTP that a real attempt shows the code derived on the server and a marked prompt on creation, on a read, and on a replay, that a training run shows neither, that the response holds only the code, and that the stored statement has no mark. In the frontend, `features/assessment-watermark` has Vitest tests of the text split, of the accessible text of the rendered markup (everything in `aria-hidden` removed leaves exactly the words), and of the tile (code and UTC time, no `@`, hidden from assistive technology). `e2e/assessment-watermark.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): the tile is on the task screen with the code and the time and without the account e-mail, is faint and takes no click, an attempt without a code shows no tile, and the accessibility tree of the marked prompt holds the words and no format character while the document keeps them. These tests do not run a real screen reader, a braille display, or another browser, so they do not show how a reader speaks the text; they do not show how many attempts a leak can be told from either, because the wording channel gives about one bit per phrase group.
## Assessment capture hint and work session tests
Domain and usecase. `assessment_signal_review_test.go` has the band rules: capture hints, extra User-Agents, and every weak signal together stop at attention however large their counts, the extra agents reach review only beside a strong signal, and a policy without the capture thresholds ignores the hints. `assessment_signal_policy_test.go` checks that a version published before these fields decodes with them off and encodes back to the same document (so its content hash holds), that the demo policy was not edited, that the thresholds round-trip, and that out-of-range or inconsistent values are rejected. `assessment_signal_test.go` covers the two new event kinds and their refusal with a measurement. `assessment_work_lease_test.go` covers the hold: one page admitted, a second refused until release or expiry, a renewal that keeps the acquisition time, release only by the holder, and invalid leases. `usecase/assessment/work_session_test.go` runs the steps of the hold and the check of the answer and the session start against in-memory repositories: a second page, a page without the header, and a request after an expiry; a training run and a service without work sessions are never refused; the origin of a hold is recorded with the User-Agent digest only. `signal_review_test.go` checks that the origin mark keeps the User-Agent as a keyed digest, writes a new mark only on a change, and that the review counts the extra agents and capture hints and stops at attention. `keyring_test.go` checks the new digests are keyed, bound to the attempt, and separate from each other. The HTTP adapter tests check the mapping of the hold, the release, the refusal of a held attempt on the session start and the answer, the new event variants and their mismatches, and the User-Agent bound.
Over HTTP with PostgreSQL. `TestAssessmentWorkSessionOverHTTP` creates a real attempt and checks that the first page holds the session, that a second page, and a request without the header, are refused for the hold, the session start, and the answer with 409 and nothing is stored, that the refusal is not stored under the key (the holder reuses both keys), that another page's release changes nothing, that the holder's release frees the session at once, that a hold that stopped renewing ends by itself, that bad page identifiers answer 400 and a missing CSRF token 403, that only digests of the page and the User-Agent are stored (no table text holds a page identifier or a browser string), that the capture events are stored without a measurement and refused with one, and that the review job gives the band attention with the extra agents and capture hints counted. `TestAssessmentSignalNoticeOverHTTP` follows `CurrentSignalNoticeVersion`. The migration 50 constraints are exercised by these tests.
Frontend. Vitest covers the key rules (`capture-keys.test.ts`), the heuristic and its watcher with fake windows and timers (`devtools-heuristic.test.ts`), the collector (one event for a press and its release, no cancelling, no event without an item), the session wiring of the watcher, the work session controller (held, busy, lost at a renewal, a network gap, a release during a renewal, the renewal bounds, `work-session.test.ts`), the page identifier header of the answer command, and the notice version 4 text. `e2e/assessment-capture.spec.ts` runs against the mocked API (also on the Vite server, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen and Cmd+Shift+4 are recorded as `screenshot_key` events with no key or image, the key event is not cancelled and the test goes on to an answer; a faked docked panel is recorded as `devtools_open`; a second tab opened on the attempt is refused with the explanation and shows no task, nothing is started in it, the first tab is undisturbed, and after the first tab leaves the second continues; `pagehide` releases the session; a tab that loses the session at a renewal stops and says so. These tests do not show behavior in other browsers or on a phone, whether the operating system hands a shortcut to the page, what a real screenshot looks like, or how often the heuristic is wrong on real windows; the mock server stands for the rules of the real one, which the HTTP test covers.
## Internal notification tests
Unit tests (`make -C backend test`, `make -C frontend test`):
+15
View File
@@ -710,6 +710,21 @@ contact_grant относится к паре кандидат-компания
- Доступность. Некоторые синтезаторы речи и брайлевские дисплеи могут озвучивать символы нулевой ширины или рвать слово на них; с настоящим экранным диктором это не проверялось. Поэтому страница кладет каждый запуск невидимых символов в элемент `aria-hidden`: дерево доступности содержит только слова (проверка Playwright читает дерево через `ariaSnapshot`, проверка Vitest вырезает скрытые элементы из разметки), а документ хранит символы, так что все, что из него скопировано, несет метку. Формулировки - обычные слова, варианты пробелов не используются, потому что неразрывный пробел не везде гарантированно беззвучен.
- Чего знак не делает. Снимок экрана, фото экрана или перепечатку в браузере предотвратить нельзя. Знак - доказательство для ручной проверки и апелляции, но не автоматическое решение; ни одна операция не показывает его работодателю, а кандидат видит только код своей попытки.
### Подсказки о съемке экрана, одно окно и чего они не делают
Реализовано для реальных попыток (root и corrective). У учебного запуска (`demo_express`) этого нет. Усиленный прокторинг здесь без камеры, микрофона, записи экрана, снимков экрана и содержимого буфера обмена: это слабые сигналы для ручной проверки и одно правило об открытых окнах. Код: `backend/internal/domain/assessment_signal.go`, `assessment_signal_review.go`, `assessment_signal_policy.go` и `assessment_work_lease.go`; `backend/internal/usecase/assessment/work_session.go` и наблюдатель в `signal_review.go`; миграция `backend/db/migrations/00050_add_assessment_work_leases_and_capture_signals.sql`; операции `HoldMyAssessmentWorkSession` и `ReleaseMyAssessmentWorkSession`; `frontend/src/features/assessment-signals/` и `frontend/src/features/assessment-work-session/`.
- Снимок экрана и фото экрана телефоном предотвратить нельзя. Страница браузера не может помешать операционной системе или другой программе снять экран, не видит камеру и не видит второе устройство, удаленный рабочий стол и виртуальную машину. Поэтому страница даже не пытается: она не отменяет клавишу, не гасит страницу по клавише и не читает изображения. Она может сообщить, что нажата клавиша снимка, связать утекший текст или снимок с попыткой (см. [Водяной знак текста задания](#водяной-знак-текста-задания)) и отправить и то и другое на ручную проверку.
- Сигналы ведут к проверке и апелляции, но не к автоматическому снижению оценки. Они только поднимают полосу проверки, которая не меняет результат, категорию и квоты; работодатель не видит ни сигналов, ни полосы, а кандидат полосы не видит. Версия 4 уведомления говорит об этом прямо.
- Клавиши снимка экрана. Страница передает `screenshot_key`, когда видит PrintScreen (в том числе с Alt), Cmd+Shift+3, 4 или 5 (macOS) либо Win+Shift+S, при нажатии или отпускании клавиши, не чаще раза в секунду. Операционная система часто забирает эти клавиши раньше страницы, снимок без клавиш ничего не присылает, а удержание не отличается от нажатия, поэтому событие доказывает только нажатие клавиши. В нем есть задание и время клиента, но нет измерений.
- Инструменты разработчика. Страница передает `devtools_open`, когда внешнее окно становится больше страницы по ширине или высоте больше чем на 160 px, как это делает пристыкованная панель, при изменении размера и по таймеру раз в две секунды, не чаще раза в минуту. Это эвристика с ложными срабатываниями (боковая панель, масштаб, изменение размера окна) и пропусками (отдельное окно панели, другие окна), поэтому это тоже лишь слабая подсказка.
- Политика и полоса. Оба вида хранятся как события (проверочные ограничения `assessment_signal_events` разрешают их без измерения) и считаются по попытке (`client_screenshot_keys`, `client_devtools_opens` в `assessment_attempt_reviews`). Пороги - необязательные поля раздела политики `assessment.signals`: `client_screenshot_keys_attention` и `client_devtools_attention` - клиентские пороги, они поднимают нормальную полосу до attention и не выше, а `extra_agents_attention` с `extra_agents_review` входит в слабую группу параллельных сессий и лишних сетей, которая сама достигает не выше attention, а review - только рядом с сильным сигналом. Нулевой или отсутствующий порог исключает сигнал, поэтому версия, опубликованная до этих полей, сохраняет полосу, документ и хеш содержимого (тест проверяет, что в ее документе нет новых ключей и он кодируется обратно без изменений). Демо-политики не менялись; `DemoAssessmentSignalPolicyWithCaptureHints` в `assessment_signal_policy.go` задает согласованные начальные значения (три клавиши снимка, одно обнаружение, два лишних User-Agent), которых никакое исследование не подтверждает, а интеграционный тест публикует их в собственной версии политики.
- Отпечаток User-Agent. HTTP-граница обрезает User-Agent до 512 байт и передает его юзкейсу, который хранит только `HMAC-SHA-256` от него под ключом, выведенным из `IDENTITY_KEY_SECRET` (метка `lincodex/assessment/signal-agent/v1`) и привязанным к попытке, в новой колонке `agent_digest` таблицы `assessment_attempt_origin_marks`. Исходное значение не хранится и не попадает в журнал. Метка пишется, когда сессия, сеть или User-Agent отличаются от последней метки, поэтому список остается коротким; `extra_agents` считает различные отпечатки сверх первого. Браузер, обновившийся во время попытки, или переход кандидата на другое устройство добавляют один, поэтому сигнал слабый.
- Одно открытое окно. `assessment_attempt_work_leases` хранит по строке на реальную попытку: ключевой отпечаток идентификатора, который каждая открытая страница создает при загрузке (`X-Attempt-Client`, от 16 до 64 символов `A-Za-z0-9_-`), время, когда она заняла сеанс, когда в последний раз продлила его и когда освободила. `PUT .../work-session` занимает или продлевает сеанс на 120 секунд (`domain.AssessmentWorkLeaseDuration`) и просит страницу продлевать раз в 15 секунд; `DELETE .../work-session` освобождает его и отвечает 204 при любом исходе. Страница занимает сеанс до начала или продолжения работы, продлевает его, пока работает, освобождает при уходе или закрытии (`pagehide`) и останавливается с объяснением, если продление отклонено. Пока сеанс занят другой страницей, начало сеанса и ответ любой другой страницы или запроса без заголовка (одна анонимная страница) получают 409 `state_conflict` и ничего не меняют; проверка идет под блокировкой строки попытки после чтения времени базы и до любого изменения попытки, а отказ не сохраняется под ключом идемпотентности, поэтому владелец может использовать тот же ключ. Попытка, которую никто не держит, освобожденное и переставшее продлеваться (не позднее чем через две минуты) занятие пускают любую страницу, а `StartSession` и `SubmitAnswer` сервиса, собранного без рабочих сеансов, не меняются.
- Связь с `MaxSessions` и `IdleTimeoutSeconds`. Эти ограничения политики попытки описывают последовательные рабочие сеансы попытки: новый начинается только после простоя, а их число ограничено. Занятие - это измерение одновременности внутри текущего рабочего сеанса. Оно не начинает, не продлевает и не расходует рабочий сеанс этой политики, не меняет версию попытки и не хранится в строке попытки.
- Пределы правила. Это правило "одна страница за раз", а не граница безопасности: клиент, который никогда не занимает сеанс, получает отказ только пока его занимает другая страница, кандидат всегда может продолжить после освобождения или истечения, а два окна одного кандидата не отличаются от двух людей. Занятие продлевает таймер страницы, поэтому браузер, который замедляет фоновую вкладку до одного такта в минуту, все равно продлевает его в пределах двух минут.
- Чтение оператором. `make -C backend assessment-review ARGS='inspect ...'` печатает новые счетчики `extra_agents`, `client_screenshot_keys` и `client_devtools_opens` рядом со старыми; примечание в конце вывода повторяет, что браузерные сигналы можно подделать и что снимок экрана или фото телефоном предотвратить нельзя и страница их не видит.
### Доказательства навыков
Реализовано как сохраняемая проекция неизменяемых результатов оценки с двумя чтениями: собственный список кандидата и разрешенная проекция сейчас видимой карточки. Проекцию для организации читает поиск (см. [Подбор и объяснение](#подбор-и-объяснение)); перцентиль ее пока не читает.
+1
View File
@@ -443,6 +443,7 @@ make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operato
- Каждое чтение записывается в `assessment_review_reads` (идентификатор попытки, имя оператора, найдено или нет, время базы) в той же транзакции, что и чтение, в том числе когда у попытки нет проверки. Таблица отклоняет UPDATE, DELETE и TRUNCATE. Имя оператора - метка для аудита, а не аутентификация: любой, у кого есть доступ к базе, может ввести любое имя. Откат миграции 33 отклоняется, пока в аудите есть строка; сначала экспортируйте или разберите ее.
- Полосы может не быть по реальной причине: в версии политики попытки нет раздела `assessment.signals`, задание проверки еще не выполнено, либо попытка еще не завершилась и не достигла дедлайна.
- Проверка обновляется на месте, когда более поздняя попытка совпала с одним из ее ответов; версия политики и время первого вычисления остаются.
- Подсказки о съемке и правило одного окна добавляют в этот вывод три счетчика (`extra_agents`, `client_screenshot_keys`, `client_devtools_opens`) и причину `extra_agents`; они поднимают полосу только через необязательные пороги раздела политики (`client_screenshot_keys_attention`, `client_devtools_attention`, `extra_agents_attention`, `extra_agents_review`), которых нет в ранее опубликованной версии и которые не задают демо-политики. Строки с ними - данные того же рода, что и остальные: ключевые отпечатки и счетчики, без User-Agent, идентификатора страницы, адреса и изображения. Снимок экрана или фото телефоном предотвратить нельзя и увидеть тоже, поэтому эти сигналы ведут только к ручной проверке, но не к автоматическому снижению оценки ([подробнее](ARCHITECTURE.md#подсказки-о-съемке-экрана-одно-окно-и-чего-они-не-делают)). Откат миграции 50 отклоняется, пока есть новые события, метки или счетчики.
- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `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`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен.
+10 -2
View File
@@ -540,16 +540,24 @@ Spec не проверяет запланированные переходы б
## Тесты ограничений во время попытки
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 3 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
Vitest работает в Node без DOM, поэтому ограничения проверяются по частям. `frontend/src/features/assessment-lockdown/model/fullscreen.test.ts` покрывает определение поддержки (в том числе браузер без полноэкранного режима элемента, например iPhone Safari), то, что запрос делается синхронно внутри вызова и остается внутри клика, и то, что отказ - это результат, а не исключение. `model/cover.test.ts` - таблица случаев, когда задание закрыто: выход из полноэкранного режима, скрытая вкладка, окно без фокуса, запрос в процессе и режим без полноэкранного режима. `ui/protected-region.test.tsx` рисует область с поддельным состоянием и проверяет, что закрытое задание не оставляет в разметке текста условия и вариантов, что у закрытия из-за ухода с вкладки нет кнопки полноэкранного режима, и объяснение для неподдерживаемого браузера; `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что скрытая форма ничего не рисует. Версия 4 текста уведомления и перечень мер проверяются в `features/assessment-signals/ui/signal-notice.test.tsx`. В бэкенде `usecase/assessment/signal_notice_test.go` проверяет, что любая версия, кроме текущей, отклоняется, а `TestAssessmentSignalNoticeOverHTTP` по HTTP с PostgreSQL проверяет, что сохраненное подтверждение версии 1 не засчитывается для текущей версии, а ее версии следуют за `CurrentSignalNoticeVersion`.
Модульные тесты защиты задания: `model/task-guard.test.ts` проверяет правила на небольших поддельных элементах и событиях: выделение, контекстное меню и перетаскивание отменяются на тексте задания и не трогаются в поле, сброс текста мышью никогда не заполняет поле, вставка отклоняется в полях ответа (и об этом сообщается, чтобы экран мог сказать) и разрешена в редакторе кода, пути `beforeinput` для вставки и сброса закрыты, а набор и композиция никогда не затрагиваются, копирование и вырезание отклоняются, когда цель или выделение доходят до задания, и не отклоняются внутри поля. `features/answer-assessment/ui/answer-form.test.tsx` проверяет, что исключение для вставки есть только у редактора кода.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 3. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
Две браузерные спецификации работают с подставным API, поэтому им не нужны данные бэкенда, и их можно запускать и на сервере Vite (`E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-lockdown.spec.ts e2e/assessment-task-protection.spec.ts --project=chromium`), и в `make -C deploy test-e2e`; подставной API лежит в `frontend/e2e/assessment-attempt-mock.ts`. `assessment-lockdown.spec.ts`: выход из полноэкранного режима закрывает задание (его текста нет в странице), отправляет сигнал `fullscreen_exit`, а кнопка продолжения возвращает задание вместе с набранным черновиком; уход с вкладки закрывает задание, а возврат в полноэкранном режиме показывает его; браузер без полноэкранного API показывает объяснение и проходит тест с клавиатуры; отказ в полноэкранном режиме не мешает продолжить; закрытие уведомления без подтверждения выходит из полноэкранного режима и ничего не сохраняет. `assessment-task-protection.spec.ts`: текст задания нельзя выделить, копирование после выделения всего или из скрипта не оставляет текста задания в буфере, контекстное меню и перетаскивание отменяются на задании, но не в поле, поле копирует собственный текст, текст остается в дереве доступности, печать скрывает задание; поле ответа отклоняет вставку и показывает сообщение, а отклоненная вставка уходит сигналом `paste` с размером и без текста; редактор кода принимает вставку и отправляет ее размер; задание отвечается только с клавиатуры. Подтверждение уведомления с настоящим бэкендом покрывает существующий тест уведомления в `assessment.spec.ts`, который теперь ожидает версию 4. Эти спецификации показывают поведение страницы в Chromium с подставным сервером; они не показывают поведение в других браузерах, на телефоне, с настоящим экранным диктором и в оконном менеджере, который сам меняет полноэкранный режим. Правило вставки не видит текст, который экранная клавиатура вставляет как набор.
## Тесты водяного знака оценки
`backend/internal/domain/assessment_watermark_test.go` покрывает метку: две попытки с одним настоящим сгенерированным вариантом получают разные тексты с меткой, у которых равны канонический текст и эталонный ответ; разметка детерминирована и идемпотентна; невидимый запуск декодируется в видимый код, переживает копию двух предложений, а обрезанный, удлиненный или с неверной контрольной цифрой запуск игнорируется; доступный текст содержит только слова; выравнивание сохраненного условия с утекшим текстом читает только найденные там обороты (слова вокруг условия, например цитата или сообщение, игнорируются), согласование формулировок попытки, которая написала текст, выполняется для каждой группы оборотов, другие затравки не согласуются, фрагмент дает обороты фрагмента, посторонний текст ничего не выравнивает, а другой вариант того же семейства выравнивается на меньшее число символов, чем утекший; части между оборотами одинаковы в каждой копии условия; числовая защита оставляет `at most` в конце предложения; коды разбираются так, как их читает оператор или распознавание. `usecase/assessment/watermark_test.go` проверяет, что размечаются только root и corrective, что сохраненный снимок не меняется, что видимый код равен невидимому и что отсутствие `Watermarker` оставляет снимки как есть; `adapter/primary/http/v1/assessment_test.go` проверяет, что каждый ответ с попыткой проходит через презентер и что отказ презентера - ошибка. `TestAssessmentWatermarkOverHTTP` (PostgreSQL) по HTTP проверяет, что реальная попытка при создании, чтении и повторе показывает код, выведенный на сервере, и текст с меткой, что учебный запуск не показывает ни того, ни другого, что в ответе только код и что в сохраненном условии метки нет. Во фронтенде у `features/assessment-watermark` есть тесты Vitest разбиения текста, доступного текста отрисованной разметки (без всего, что в `aria-hidden`, остаются ровно слова) и плитки (код и время UTC, без `@`, скрыта от вспомогательных технологий). `e2e/assessment-watermark.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-watermark.spec.ts --project=chromium`): плитка есть на экране задания с кодом и временем и без email аккаунта, бледная и не перехватывает клики, у попытки без кода плитки нет, а дерево доступности размеченного условия содержит слова и ни одного символа форматирования, хотя документ их хранит. Эти тесты не запускают настоящий экранный диктор, брайлевский дисплей или другой браузер, поэтому не показывают, как диктор читает текст; они не показывают и того, сколько попыток можно различить по утечке, потому что канал формулировок дает около одного бита на группу оборотов.
## Тесты подсказок о съемке экрана и рабочего сеанса оценки
Домен и юзкейс. `assessment_signal_review_test.go` проверяет правила полосы: подсказки о съемке, лишние User-Agent и все слабые сигналы вместе останавливаются на attention при любых счетчиках, лишние агенты достигают review только рядом с сильным сигналом, а политика без порогов съемки игнорирует подсказки. `assessment_signal_policy_test.go` проверяет, что версия, опубликованная до этих полей, декодируется с ними выключенными и кодируется обратно в тот же документ (поэтому хеш содержимого сохраняется), что демо-политика не менялась, что пороги проходят туда и обратно и что значения вне диапазона или противоречивые отклоняются. `assessment_signal_test.go` покрывает два новых вида событий и отказ при наличии измерения. `assessment_work_lease_test.go` покрывает занятие: одна страница допускается, вторая получает отказ до освобождения или истечения, продление сохраняет время занятия, освобождает только владелец, неверные записи отклоняются. `usecase/assessment/work_session_test.go` прогоняет шаги занятия и проверку ответа и начала сеанса на репозиториях в памяти: вторая страница, страница без заголовка и запрос после истечения; учебный запуск и сервис без рабочих сеансов не получают отказов; источник занятия записывается только с отпечатком User-Agent. `signal_review_test.go` проверяет, что метка источника хранит User-Agent как ключевой отпечаток, пишет новую метку только при изменении, а проверка считает лишние агенты и подсказки о съемке и останавливается на attention. `keyring_test.go` проверяет, что новые отпечатки ключевые, привязаны к попытке и различны между собой. Тесты HTTP-адаптера проверяют отображение занятия, освобождения, отказа для занятой попытки при начале сеанса и ответе, новых вариантов событий и их несовпадений и ограничение User-Agent.
По HTTP с PostgreSQL. `TestAssessmentWorkSessionOverHTTP` создает реальную попытку и проверяет, что первая страница занимает сеанс, что вторая страница и запрос без заголовка получают 409 на занятие, начало сеанса и ответ, при этом ничего не сохраняется, что отказ не сохраняется под ключом (владелец использует оба ключа повторно), что освобождение чужой страницей ничего не меняет, что освобождение владельцем освобождает сеанс сразу, что занятие, переставшее продлеваться, заканчивается само, что неверные идентификаторы страницы дают 400, а отсутствие CSRF-токена - 403, что хранятся только отпечатки страницы и User-Agent (ни один текст таблицы не содержит идентификатор страницы или строку браузера), что события съемки хранятся без измерения и отклоняются с ним и что задание проверки дает полосу attention с учтенными лишними агентами и подсказками о съемке. `TestAssessmentSignalNoticeOverHTTP` следует за `CurrentSignalNoticeVersion`. Ограничения миграции 50 проверяются этими тестами.
Фронтенд. Vitest покрывает правила клавиш (`capture-keys.test.ts`), эвристику и ее наблюдателя с поддельными окнами и таймерами (`devtools-heuristic.test.ts`), сборщик (одно событие на нажатие и отпускание, без отмены, без события без задания), подключение наблюдателя к сеансу, контроллер рабочего сеанса (занято, свободно, потеряно при продлении, обрыв сети, освобождение во время продления, границы продления, `work-session.test.ts`), заголовок идентификатора страницы в команде ответа и текст версии 4 уведомления. `e2e/assessment-capture.spec.ts` работает с подставным API (и на сервере Vite, `E2E_BASE_URL=http://localhost:5173 pnpm exec playwright test e2e/assessment-capture.spec.ts --project=chromium`): PrintScreen и Cmd+Shift+4 записываются как события `screenshot_key` без клавиши и изображения, событие клавиши не отменяется, и тест доходит до ответа; подставная пристыкованная панель записывается как `devtools_open`; вторая вкладка с той же попыткой получает отказ с объяснением и не показывает задание, в ней ничего не начинается, первая вкладка не нарушена, а после ухода первой вкладки вторая продолжает; `pagehide` освобождает сеанс; вкладка, потерявшая сеанс при продлении, останавливается и говорит об этом. Эти тесты не показывают поведение в других браузерах и на телефоне, отдает ли операционная система сочетание странице, как выглядит настоящий снимок и как часто эвристика ошибается на настоящих окнах; подставной сервер изображает правила настоящего, которые покрывает тест HTTP.
## Тесты внутренних уведомлений
Модульные тесты (`make -C backend test`, `make -C frontend test`):
+1 -1
View File
@@ -69,7 +69,7 @@ The attempt screen focuses on the item: a strip above it names the attempt and s
The `Idempotency-Key` of the express start is kept in the tab's sessionStorage per account until the run is finished or expired, and for 24 hours at most. When a new start gets 409 `state_conflict`, the page repeats the start with the key of the active run, and the server returns the stored 201 with that attempt: an unfinished demonstration continues after a reload. The key of a start with an unknown outcome (no response, 5xx) is kept and repeated as well. Without a key (another browser, a closed tab, blocked storage), the screen explains that the demonstration ends by itself within 5 minutes of its start.
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 dialog also lists the measures the page applies during the attempt (fullscreen, covering the task when the candidate leaves, blocks on copying, selecting, and printing the task text, the paste rule, and the watermark: a faint tile with the attempt code and the time and an invisible mark in the task text). This is notice text version 3; an acknowledgement of an earlier version does not count for it. 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.
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 dialog also lists the measures the page applies during the attempt (fullscreen, covering the task when the candidate leaves, blocks on copying, selecting, and printing the task text, the paste rule, the one-window rule, and the watermark: a faint tile with the attempt code and the time and an invisible mark in the task text). The browser also records, as weak hints only, a screenshot key (PrintScreen, Cmd+Shift+3, 4, or 5, Win+Shift+S) and a guess that the developer tools are open from the window size; the server keeps the User-Agent only as a keyed digest. The dialog says plainly that a screenshot or a phone photo cannot be prevented and that signals lead only to a manual check. This is notice text version 4; an acknowledgement of an earlier version does not count for it. The page holds the single work session of a real attempt for its own open window (`features/assessment-work-session`) and says so when another window holds it. 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 collector's listeners are passive, block nothing, and show nothing (the measures of the next paragraph are a separate feature and do not depend on it). 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.
+1 -1
View File
@@ -69,7 +69,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
`Idempotency-Key` начала экспресс-запуска хранится в sessionStorage вкладки отдельно для каждого аккаунта, пока запуск не завершен или не истек, и не дольше 24 часов. Если новое начало получает 409 `state_conflict`, страница повторяет начало с ключом активного запуска, и сервер возвращает сохраненный ответ 201 с этой попыткой: незавершенная демонстрация продолжается после перезагрузки. Ключ начала с неизвестным исходом (нет ответа, 5xx) тоже сохраняется и повторяется. Если ключа нет (другой браузер, закрытая вкладка, заблокированное хранилище), экран объясняет, что демонстрация закончится сама не позже чем через 5 минут после начала.
Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Окно также перечисляет меры, которые страница применяет во время попытки (полноэкранный режим, скрытие задания при уходе, запрет копирования, выделения и печати текста задания, правило вставки и водяной знак: бледная плитка с кодом попытки и временем и невидимая метка в тексте задания). Это версия 3 текста уведомления; подтверждение более ранней версии для нее не засчитывается. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным.
Перед началом реальной попытки экран показывает окно с перечнем сигналов. Браузер фиксирует смену вкладки или окна, копирование, вставку и вырезание, выход из полноэкранного режима; сервер измеряет время ответа на задание, смену сетевого адреса во время попытки, параллельные сессии и совпадение отпечатков ответов с ответами других кандидатов. Окно прямо говорит, что изображение, звук и содержимое буфера обмена не собираются, что адреса и токены сессий не хранятся (только односторонние ключевые отпечатки) и что события браузера сохраняются, только пока действует согласие C3. Начало без подтверждения невозможно: закрытие окна или Escape ничего не запускает. Окно также перечисляет меры, которые страница применяет во время попытки (полноэкранный режим, скрытие задания при уходе, запрет копирования, выделения и печати текста задания, правило вставки, правило одного окна и водяной знак: бледная плитка с кодом попытки и временем и невидимая метка в тексте задания). Браузер также фиксирует, как слабые подсказки, клавишу снимка экрана (PrintScreen, Cmd+Shift+3, 4 или 5, Win+Shift+S) и догадку об открытых инструментах разработчика по размеру окна; сервер хранит User-Agent только как ключевой отпечаток. Окно прямо говорит, что снимок экрана или фото телефоном предотвратить нельзя, а сигналы ведут только к ручной проверке. Это версия 4 текста уведомления; подтверждение более ранней версии для нее не засчитывается. Страница занимает единственный рабочий сеанс реальной попытки для своего открытого окна (`features/assessment-work-session`) и сообщает, если его держит другое окно. Подтверждение сохраняется на сервере (`/me/assessment-signal-notice`) для версии текста, поэтому перезагрузка и новый браузер не спрашивают повторно; такое же окно открывается при продолжении старой попытки, начатой без подтверждения. Это запись об ознакомлении, а не согласие: C3 остается отдельным.
Во время реальной попытки `features/assessment-signals` собирает отправляемые сигналы: потерю фокуса с длительностью, копирование, вставку и вырезание только с размером, выход из полноэкранного режима. Слушатели сборщика пассивные, ничего не блокируют и не показывают (меры из следующего абзаца - отдельная функция и от сборщика не зависят); события уходят пакетами (по таймеру в 10 секунд, при скрытии вкладки или накоплении 20 событий), у каждого пакета свой `Idempotency-Key`, который сохраняется при повторах. При закрытии страницы (`pagehide`) и при размонтировании оставшиеся события отправляются последним запросом с `keepalive`, поэтому закрытие вкладки не теряет накопленное за последние секунды; результат такого запроса не ожидается и не повторяется. Сбой сети никогда не мешает отправке ответа: неудачный пакет повторяется с тем же ключом и телом с нарастающей паузой, а после лимита попыток отбрасывается. Ответ сервера об отказе (нет C3, попытка завершена) останавливает сбор. Демонстрационный запуск сигналы не собирает.
+58 -3
View File
@@ -35,9 +35,21 @@ export type SignalEvent = {
[field: string]: unknown;
};
/**
* The work session of the attempt as the server holds it. Pages that mock the
* same attempt share one object, so a second tab meets the hold of the first.
*/
export type LeaseState = { holder: string | null };
export type MockedAttempt = {
/** Events of every signal batch the page sent, in order. */
signals: SignalEvent[];
/** The page identifier of every hold or renewal the page sent. */
holds: string[];
/** The page identifier of every release the page sent. */
releases: string[];
/** The page identifier of every session start the page sent (null: no header). */
starts: Array<string | null>;
/** Bodies of the answers the page sent. */
answers: unknown[];
/** Calls to the notice acknowledgement, to see what was stored. */
@@ -46,7 +58,7 @@ export type MockedAttempt = {
export const watermarkCode = "7K3QD-9XM2T";
/** The notice text version the page knows; the mock server requires the same one. */
export const noticeVersion = 3;
export const noticeVersion = 4;
type Options = {
content: MockItemContent;
@@ -56,6 +68,10 @@ type Options = {
prompt?: string;
/** The visible code of the attempt, or null for an attempt without one. */
watermark?: string | null;
/** The work session shared by the pages of one attempt; one page has its own by default. */
lease?: LeaseState;
/** How often the server asks the page to renew its hold. */
renewAfterSeconds?: number;
};
function isoSeconds(ms: number): string {
@@ -93,7 +109,15 @@ function attemptBody(version: number, options: Options) {
/** Answers the API calls of the attempt page; every other API call gets a 404. */
export async function mockAttemptApi(page: Page, options: Options): Promise<MockedAttempt> {
const recorded: MockedAttempt = { signals: [], answers: [], acknowledgements: [] };
const recorded: MockedAttempt = {
signals: [],
holds: [],
releases: [],
starts: [],
answers: [],
acknowledgements: [],
};
const lease = options.lease ?? { holder: null };
let acknowledged = options.noticeAcknowledged ?? true;
await page.route("**/api/v1/**", async (route: Route) => {
@@ -133,9 +157,40 @@ export async function mockAttemptApi(page: Page, options: Options): Promise<Mock
acknowledged_at: acknowledged ? "2026-10-10T10:00:00Z" : null,
});
}
const client = request.headers()["x-attempt-client"] ?? null;
const heldByAnother = lease.holder !== null && lease.holder !== client;
const busy = () =>
reply(
{
type: "urn:lincodex:problem:state_conflict",
title: "Conflict",
status: 409,
code: "state_conflict",
},
409,
);
if (path === `${base}/work-session`) {
if (method === "DELETE") {
recorded.releases.push(client ?? "");
if (lease.holder === client) lease.holder = null;
return route.fulfill({ status: 204, headers: { "cache-control": "no-store" } });
}
recorded.holds.push(client ?? "");
if (heldByAnother) return busy();
lease.holder = client;
return reply({
held_until: isoSeconds(Date.now() + 120_000),
renew_after_seconds: options.renewAfterSeconds ?? 15,
});
}
if (path === base && method === "GET") return reply(attemptBody(1, options));
if (path === `${base}/sessions`) return reply(attemptBody(2, options));
if (path === `${base}/sessions`) {
recorded.starts.push(client);
if (heldByAnother) return busy();
return reply(attemptBody(2, options));
}
if (path === `${base}/answers`) {
if (heldByAnother) return busy();
recorded.answers.push(JSON.parse(request.postData() ?? "{}"));
return reply(attemptBody(3, options));
}
+162
View File
@@ -0,0 +1,162 @@
import { expect, test } from "@playwright/test";
import {
attemptId,
mockAttemptApi,
numberContent,
startAttempt,
type LeaseState,
} from "./assessment-attempt-mock";
// Weak capture hints and the one-open-window rule of a real attempt. The API is
// mocked: these specs check what the page sends and shows, not what the server
// decides. A screenshot or a phone photo cannot be prevented, so the page never
// tries: it only reports that a screenshot key was pressed.
const answerName = /^Числовой ответ/;
const flushTimeout = 15_000;
test.use({ actionTimeout: 10_000, trace: "off", screenshot: "off", video: "off" });
test("PrintScreen and the macOS shortcuts are recorded as a signal and the test goes on", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The page only watches: the key event is not cancelled, so the system still takes the screenshot.
const notCancelled = await page.evaluate(() =>
document.dispatchEvent(
new KeyboardEvent("keydown", { key: "PrintScreen", code: "PrintScreen", cancelable: true }),
),
);
expect(notCancelled).toBe(true);
await page.waitForTimeout(1_100);
await page.keyboard.press("Meta+Shift+4");
await expect
.poll(() => recorded.signals.filter((event) => event.kind === "screenshot_key").length, {
timeout: flushTimeout,
})
.toBe(2);
const event = recorded.signals.find((signal) => signal.kind === "screenshot_key");
// The event holds the fact and the item, never the key, the screen, or any image.
expect(Object.keys(event ?? {}).sort()).toEqual(["item_instance_id", "kind", "occurred_at"]);
// The task goes on: nothing was covered, and the answer is typed and sent.
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await page.getByRole("textbox", { name: answerName }).fill("42");
await page.getByRole("button", { name: "Отправить ответ" }).click();
await expect.poll(() => recorded.answers.length).toBe(1);
});
test("open developer tools, guessed from the window size, are recorded as a weak signal", async ({
page,
}) => {
const recorded = await mockAttemptApi(page, { content: numberContent });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(recorded.signals.some((signal) => signal.kind === "devtools_open")).toBe(false);
// A docked panel makes the outer window much taller than the page.
await page.evaluate(() => {
Object.defineProperty(window, "outerHeight", {
configurable: true,
get: () => window.innerHeight + 420,
});
window.dispatchEvent(new Event("resize"));
});
await expect
.poll(() => recorded.signals.filter((signal) => signal.kind === "devtools_open").length, {
timeout: flushTimeout,
})
.toBe(1);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
});
test("a second tab of the attempt is refused with an explanation until the first one is closed", async ({
browser,
}) => {
const context = await browser.newContext({ locale: "ru-RU" });
const lease: LeaseState = { holder: null };
const first = await context.newPage();
const second = await context.newPage();
const firstApi = await mockAttemptApi(first, { content: numberContent, lease });
const secondApi = await mockAttemptApi(second, { content: numberContent, lease });
await startAttempt(first);
await expect(first.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(firstApi.holds).toHaveLength(1);
const firstClient = firstApi.holds[0] ?? "";
expect(firstClient).toMatch(/^[A-Za-z0-9_-]{16,64}$/);
// The session start and the answer carry the page identifier as well.
expect(firstApi.starts).toEqual([firstClient]);
// The attempt in a second tab: refused, explained, and the task is not shown.
await startAttempt(second);
const explanation = second
.getByRole("alert")
.filter({ hasText: "Попытка открыта в другом окне" });
await expect(explanation).toBeVisible();
await expect(explanation).toContainText("Работать над попыткой можно только в одном окне");
await expect(second.getByRole("heading", { name: "Задание 1" })).toHaveCount(0);
expect(await second.content()).not.toContain("SECRET-PROMPT");
expect(secondApi.holds).toHaveLength(1);
expect(secondApi.holds[0]).not.toBe(firstClient);
// Nothing was started in the second tab, and the first tab is undisturbed.
expect(secondApi.starts).toEqual([]);
await expect(first.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The first tab goes to the list of checks: its page releases the session at once.
await first.getByRole("link", { name: "К доступным проверкам" }).click();
await expect.poll(() => firstApi.releases).toEqual([firstClient]);
expect(lease.holder).toBeNull();
// The second tab continues.
await second.getByRole("button", { name: "Начать или продолжить" }).click();
await expect(second.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(explanation).toHaveCount(0);
expect(secondApi.holds).toHaveLength(2);
expect(lease.holder).toBe(secondApi.holds[1]);
await context.close();
});
test("a page that is going away releases the work session", async ({ page }) => {
const lease: LeaseState = { holder: null };
const recorded = await mockAttemptApi(page, { content: numberContent, lease });
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(lease.holder).not.toBeNull();
await page.evaluate(() => window.dispatchEvent(new Event("pagehide")));
await expect.poll(() => recorded.releases.length).toBe(1);
expect(lease.holder).toBeNull();
});
test("a tab that loses the work session to another window stops and says so", async ({
browser,
}) => {
const context = await browser.newContext({ locale: "ru-RU" });
const lease: LeaseState = { holder: null };
const page = await context.newPage();
const recorded = await mockAttemptApi(page, {
content: numberContent,
lease,
renewAfterSeconds: 5,
});
await startAttempt(page);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
expect(recorded.holds).toHaveLength(1);
// Another window takes the session over (the mock server hands it away).
lease.holder = "another-window-AAAAAAAAAAAAAAAA";
await expect(page.getByRole("heading", { name: "Задание 1" })).toHaveCount(0, {
timeout: 12_000,
});
await expect(
page.getByRole("alert").filter({ hasText: "Попытка открыта в другом окне" }),
).toBeVisible();
// The attempt in the page is the same one; it only waits for the session to be free.
expect(page.url()).toContain(attemptId);
await context.close();
});
+1 -1
View File
@@ -806,7 +806,7 @@ test("closing the notice does not start the attempt and a confirmation is rememb
await page.getByRole("button", { name: "Закрыть без подтверждения" }).click();
await expect(dialog).toBeHidden();
expect(creates).toHaveLength(0);
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 3 });
expect(await readNotice(page)).toMatchObject({ acknowledged: false, notice_version: 4 });
await start.click();
await expect(dialog).toBeVisible();
@@ -154,3 +154,37 @@ describe("assessment answer response validation", () => {
]);
});
});
describe("assessment answer command page identifier", () => {
it("sends the open page identifier so a second window is refused, and omits it when there is none", async () => {
const interceptedFetch = globalThis.fetch;
vi.stubGlobal("fetch", (input: string, init?: RequestInit) =>
interceptedFetch(new URL(input, "http://localhost"), init),
);
const clients: Array<string | null> = [];
server.use(
http.post(
`http://localhost/api/v1/me/assessment-attempts/${attemptId}/answers`,
({ request }) => {
clients.push(request.headers.get("X-Attempt-Client"));
return HttpResponse.json(validAttempt, { status: 200 });
},
),
);
const command: PendingAnswerCommand = {
key: "answer-command-key",
body: '{"expected_version":1,"item_id":"item-1","answer":{"format":"number","number":1}}',
itemId: "item-1",
};
const withClient = await submitPendingAnswerCommand(
command,
attemptId,
"csrf-token",
"7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG",
);
const withoutClient = await submitPendingAnswerCommand(command, attemptId, "csrf-token");
expect(withClient.kind).toBe("accepted");
expect(withoutClient.kind).toBe("accepted");
expect(clients).toEqual(["7mK2pQx9Rt4vWc1Zb8NfYd3Ha6Js0LeG", null]);
});
});
@@ -13,10 +13,15 @@ export type AnswerCommandOutcome =
| { kind: "retry"; command: PendingAnswerCommand; error: unknown }
| { kind: "rejected"; error: unknown };
/**
* Sends the answer. `client` names the open page, so that a second window of
* the same attempt is refused while another one holds its work session.
*/
export async function submitPendingAnswerCommand(
command: PendingAnswerCommand,
attemptId: string,
csrfToken: string,
client?: string,
): Promise<AnswerCommandOutcome> {
try {
const attempt = await apiRequest<AssessmentAttempt>(
@@ -27,6 +32,7 @@ export async function submitPendingAnswerCommand(
"Content-Type": "application/json",
"Idempotency-Key": command.key,
"X-CSRF-Token": csrfToken,
...(client ? { "X-Attempt-Client": client } : {}),
},
body: command.body,
},
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { isScreenshotKey } from "./capture-keys";
describe("screenshot keys", () => {
it("recognizes PrintScreen alone and with Alt", () => {
expect(isScreenshotKey({ key: "PrintScreen", code: "PrintScreen" })).toBe(true);
expect(isScreenshotKey({ key: "PrintScreen", code: "PrintScreen", metaKey: false })).toBe(true);
expect(isScreenshotKey({ code: "PrintScreen" })).toBe(true);
});
it("recognizes the macOS shortcuts by the physical digit key, whatever Shift types", () => {
for (const code of ["Digit3", "Digit4", "Digit5"]) {
// With Shift the keys type #, $, and %, so the character is not what matters.
expect(isScreenshotKey({ key: "#", code, metaKey: true, shiftKey: true })).toBe(true);
}
});
it("recognizes the Windows snipping shortcut", () => {
expect(isScreenshotKey({ key: "S", code: "KeyS", metaKey: true, shiftKey: true })).toBe(true);
});
it("leaves ordinary typing and incomplete combinations alone", () => {
expect(isScreenshotKey({ key: "3", code: "Digit3" })).toBe(false);
expect(isScreenshotKey({ key: "3", code: "Digit3", shiftKey: true })).toBe(false);
expect(isScreenshotKey({ key: "3", code: "Digit3", metaKey: true })).toBe(false);
expect(isScreenshotKey({ key: "s", code: "KeyS", metaKey: true })).toBe(false);
expect(isScreenshotKey({ key: "s", code: "KeyS", shiftKey: true })).toBe(false);
expect(isScreenshotKey({ key: "6", code: "Digit6", metaKey: true, shiftKey: true })).toBe(
false,
);
expect(isScreenshotKey({})).toBe(false);
});
});
@@ -0,0 +1,26 @@
/** The parts of a keyboard event that the screenshot check reads. */
export type KeyLike = {
key?: string;
code?: string;
metaKey?: boolean;
shiftKey?: boolean;
};
/**
* Tells whether a key event is a screenshot shortcut that the browser can see:
* PrintScreen (also with Alt), Cmd+Shift+3, 4, or 5 on macOS, and Win+Shift+S on
* Windows. The operating system often takes these keys before the page, and a
* photo of the screen sends none, so a missed shortcut proves nothing and a seen
* one proves only that a key was pressed. Only the physical key (`code`) is used
* for the digits, because the produced character changes with Shift.
*/
export function isScreenshotKey(event: KeyLike): boolean {
if (event.code === "PrintScreen" || event.key === "PrintScreen") return true;
if (!event.metaKey || !event.shiftKey) return false;
return (
event.code === "Digit3" ||
event.code === "Digit4" ||
event.code === "Digit5" ||
event.code === "KeyS"
);
}
@@ -133,6 +133,55 @@ describe("signal collector", () => {
expect(events[0]).toMatchObject({ kind: "fullscreen_exit" });
});
it("records a screenshot key once for its press and release, and never prevents it", () => {
const { doc, events, advance } = setup();
const press = new Event("keydown", { cancelable: true });
Object.assign(press, { key: "PrintScreen", code: "PrintScreen" });
doc.dispatchEvent(press);
const release = new Event("keyup", { cancelable: true });
Object.assign(release, { key: "PrintScreen", code: "PrintScreen" });
doc.dispatchEvent(release);
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ kind: "screenshot_key", item_instance_id: itemId });
expect(Object.keys(events[0] ?? {}).sort()).toEqual(
["item_instance_id", "kind", "occurred_at"].sort(),
);
expect(press.defaultPrevented).toBe(false);
expect(release.defaultPrevented).toBe(false);
// A later press is a new event.
advance(5_000);
doc.dispatchEvent(press);
expect(events).toHaveLength(2);
});
it("records the macOS and Windows screenshot shortcuts and no other key", () => {
const { doc, events, advance } = setup();
const press = (init: Record<string, unknown>) => {
const event = new Event("keydown");
Object.assign(event, init);
doc.dispatchEvent(event);
advance(2_000);
};
press({ key: "#", code: "Digit3", metaKey: true, shiftKey: true });
press({ key: "$", code: "Digit4", metaKey: true, shiftKey: true });
press({ key: "S", code: "KeyS", metaKey: true, shiftKey: true });
press({ key: "a", code: "KeyA" });
press({ key: "3", code: "Digit3", metaKey: true });
expect(events.map((event) => event.kind)).toEqual([
"screenshot_key",
"screenshot_key",
"screenshot_key",
]);
});
it("does not record a screenshot key while no item is shown", () => {
const { doc, events } = setup(null);
const press = new Event("keydown");
Object.assign(press, { key: "PrintScreen", code: "PrintScreen" });
doc.dispatchEvent(press);
expect(events).toHaveLength(0);
});
it("ignores events while no item is shown", () => {
const { doc, events } = setup(null);
doc.dispatchEvent(new Event("copy"));
@@ -1,6 +1,13 @@
import type { AssessmentSignalEvent } from "../../../shared/api/schemas";
import { pasteSizeBytes, selectionSize, type PasteSource, type SelectionSource } from "./measure";
import { clipboardEvent, focusLossEvent, fullscreenExitEvent } from "./signal-events";
import { isScreenshotKey, type KeyLike } from "./capture-keys";
import type { WindowSizes } from "./devtools-heuristic";
import {
clipboardEvent,
focusLossEvent,
fullscreenExitEvent,
screenshotKeyEvent,
} from "./signal-events";
/** The browser objects the collector listens to; tests pass small fakes. */
export type CollectorEnvironment = {
@@ -10,7 +17,7 @@ export type CollectorEnvironment = {
readonly fullscreenElement: unknown;
hasFocus(): boolean;
};
window: EventTarget;
window: EventTarget & Partial<WindowSizes>;
/** Device clock in milliseconds; only differences of it are used as durations. */
now: () => number;
/**
@@ -34,6 +41,13 @@ export type CollectorOptions = {
type ClipboardLike = Event & { clipboardData?: PasteSource | null };
/**
* A shortcut is reported once for its press and release, which both reach the
* page on some systems (Windows sends only the release of PrintScreen), and a
* held key repeats.
*/
const screenshotKeyCooldownMs = 1_000;
/**
* Observes the disclosed signals and reports them through onEvent.
*
@@ -47,6 +61,7 @@ export function attachSignalCollector(options: CollectorOptions): () => void {
const stamp = options.environment.toServerTime ?? ((deviceMs: number) => deviceMs);
let awaySince: number | null = null;
let wasFullscreen = doc.fullscreenElement != null;
let lastScreenshotKeyAt: number | null = null;
function emit(build: (itemId: string) => AssessmentSignalEvent): void {
const itemId = options.currentItemId();
@@ -102,6 +117,17 @@ export function attachSignalCollector(options: CollectorOptions): () => void {
const size = pasteSizeBytes((event as ClipboardLike).clipboardData);
emit((itemId) => clipboardEvent("paste", itemId, stamp(now()), size));
});
function onKey(event: Event): void {
if (!isScreenshotKey(event as unknown as KeyLike)) return;
const at = now();
if (lastScreenshotKeyAt !== null && at - lastScreenshotKeyAt < screenshotKeyCooldownMs) return;
lastScreenshotKeyAt = at;
emit((itemId) => screenshotKeyEvent(itemId, stamp(at)));
}
// The keys are only observed: nothing is prevented, so a screenshot is never
// blocked by the page, and typing is untouched.
listen(doc, "keydown", onKey);
listen(doc, "keyup", onKey);
listen(doc, "fullscreenchange", () => {
const isFullscreen = doc.fullscreenElement != null;
if (wasFullscreen && !isFullscreen) emit((itemId) => fullscreenExitEvent(itemId, stamp(now())));
@@ -0,0 +1,139 @@
import { describe, expect, it } from "vitest";
import { devtoolsDockedOpen, startDevtoolsWatcher, type WindowSizes } from "./devtools-heuristic";
const closed: WindowSizes = {
innerWidth: 1280,
innerHeight: 720,
outerWidth: 1280,
outerHeight: 820,
};
class FakeWindow extends EventTarget implements WindowSizes {
innerWidth = closed.innerWidth;
innerHeight = closed.innerHeight;
outerWidth = closed.outerWidth;
outerHeight = closed.outerHeight;
}
describe("developer tools heuristic", () => {
it("leaves a window with ordinary browser chrome alone", () => {
expect(devtoolsDockedOpen(closed)).toBe(false);
expect(devtoolsDockedOpen({ ...closed, outerHeight: 720 + 130 })).toBe(false);
// Fullscreen has no chrome at all.
expect(devtoolsDockedOpen({ ...closed, outerHeight: 720 })).toBe(false);
});
it("suspects a panel docked at the bottom or at the side", () => {
expect(devtoolsDockedOpen({ ...closed, innerHeight: 420 })).toBe(true);
expect(devtoolsDockedOpen({ ...closed, innerWidth: 900 })).toBe(true);
});
it("never suspects a window that reports no sizes", () => {
expect(devtoolsDockedOpen({})).toBe(false);
expect(devtoolsDockedOpen({ innerWidth: 100 })).toBe(false);
});
});
function watch(overrides: { cooldownMs?: number } = {}) {
const win = new FakeWindow();
let clock = 1_000_000;
const opens: number[] = [];
const timers: Array<() => void> = [];
const cancelled: unknown[] = [];
const stop = startDevtoolsWatcher({
window: win,
now: () => clock,
schedule: (callback) => {
timers.push(callback);
return timers.length;
},
cancel: (handle) => cancelled.push(handle),
onOpen: () => opens.push(clock),
...overrides,
});
return {
win,
opens,
timers,
cancelled,
stop,
advance: (ms: number) => {
clock += ms;
},
};
}
describe("developer tools watcher", () => {
it("reports the change from closed to open once, on a resize", () => {
const { win, opens } = watch();
expect(opens).toHaveLength(0);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(1);
});
it("notices a panel that is opened between resizes on its timer", () => {
const { win, opens, timers } = watch();
win.innerWidth = 800;
timers.at(-1)?.();
expect(opens).toHaveLength(1);
});
it("reports a panel that is already open when the watcher starts", () => {
const win = new FakeWindow();
win.innerHeight = 300;
const opens: number[] = [];
startDevtoolsWatcher({
window: win,
now: () => 1,
schedule: () => 1,
cancel: () => undefined,
onOpen: () => opens.push(1),
});
expect(opens).toHaveLength(1);
});
it("reports a panel that is closed and opened again only after the cooldown", () => {
const { win, opens, advance } = watch({ cooldownMs: 60_000 });
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
win.innerHeight = closed.innerHeight;
win.dispatchEvent(new Event("resize"));
advance(10_000);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(1);
win.innerHeight = closed.innerHeight;
win.dispatchEvent(new Event("resize"));
advance(60_000);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(2);
});
it("stops listening and cancels its timer", () => {
const { win, opens, stop, cancelled } = watch();
stop();
expect(cancelled).toHaveLength(1);
win.innerHeight = 400;
win.dispatchEvent(new Event("resize"));
expect(opens).toHaveLength(0);
});
it("is not disturbed by a consumer that throws", () => {
const win = new FakeWindow();
win.innerHeight = 300;
expect(() =>
startDevtoolsWatcher({
window: win,
now: () => 1,
schedule: () => 1,
cancel: () => undefined,
onOpen: () => {
throw new Error("consumer failed");
},
}),
).not.toThrow();
});
});
@@ -0,0 +1,96 @@
/** The window sizes the heuristic reads. */
export type WindowSizes = {
innerWidth: number;
innerHeight: number;
outerWidth: number;
outerHeight: number;
};
/**
* How much larger the outer window may be than the page before the developer
* tools are suspected, in pixels. Window frames, tab strips, and address bars
* take up to about 130 px of height, and a docked panel takes at least 200.
*/
const sizeGapPx = 160;
/**
* Guesses that a docked developer tools panel is open, because it takes room
* from the page and leaves the outer window as it was. It is a heuristic with
* known false positives (a sidebar, a zoomed page, a window that is being
* resized) and false negatives (a detached panel), so a result is only a weak
* hint. A window that reports no sizes is never suspected.
*/
export function devtoolsDockedOpen(sizes: Partial<WindowSizes>): boolean {
const { innerWidth, innerHeight, outerWidth, outerHeight } = sizes;
if (
innerWidth === undefined ||
innerHeight === undefined ||
outerWidth === undefined ||
outerHeight === undefined
) {
return false;
}
return outerWidth - innerWidth > sizeGapPx || outerHeight - innerHeight > sizeGapPx;
}
export type DevtoolsWatcherOptions = {
window: EventTarget & Partial<WindowSizes>;
now: () => number;
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
/** Called once when the panel looks opened, and again only after the cooldown. */
onOpen: () => void;
intervalMs?: number;
cooldownMs?: number;
};
const defaultIntervalMs = 2_000;
const defaultCooldownMs = 60_000;
/**
* Watches the window sizes on every resize and on a slow timer, and reports a
* change from closed to open. A panel that is closed and opened again reports
* again only after the cooldown, so a candidate who toggles it cannot flood the
* batch. Returns the function that stops the watcher.
*/
export function startDevtoolsWatcher(options: DevtoolsWatcherOptions): () => void {
const interval = options.intervalMs ?? defaultIntervalMs;
const cooldown = options.cooldownMs ?? defaultCooldownMs;
let open = false;
let lastReportAt: number | null = null;
let timer: unknown = null;
let stopped = false;
function check(): void {
const nowOpen = devtoolsDockedOpen(options.window);
if (nowOpen && !open) {
const at = options.now();
if (lastReportAt === null || at - lastReportAt >= cooldown) {
lastReportAt = at;
try {
options.onOpen();
} catch {
// A watcher must never disturb the test.
}
}
}
open = nowOpen;
}
function tick(): void {
if (stopped) return;
check();
timer = options.schedule(tick, interval);
}
const onResize = () => check();
options.window.addEventListener("resize", onResize, { passive: true });
check();
timer = options.schedule(tick, interval);
return () => {
stopped = true;
options.window.removeEventListener("resize", onResize);
if (timer !== null) options.cancel(timer);
};
}
@@ -3,7 +3,7 @@
* 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 = 3;
export const knownSignalNoticeVersion = 4;
export type DisclosedSignal = { code: string; title: string; detail: string };
@@ -24,6 +24,17 @@ export const browserSignals: readonly DisclosedSignal[] = [
title: "Выход из полноэкранного режима",
detail: "Только факт выхода.",
},
{
code: "screenshot_key",
title: "Клавиши снимка экрана",
detail:
"PrintScreen, Cmd+Shift+3, 4 или 5 и Win+Shift+S, если браузер их видит. Фиксируется только факт нажатия: сам снимок страница не видит и не блокирует.",
},
{
code: "devtools",
title: "Признаки открытых инструментов разработчика",
detail: "Это догадка по размерам окна, она может ошибаться. Фиксируется только факт.",
},
];
/**
@@ -54,6 +65,12 @@ export const attemptMeasures: readonly DisclosedSignal[] = [
title: "Вставка в поля ответа",
detail: "Отключена. В редакторе кода вставка разрешена, фиксируется только ее размер.",
},
{
code: "single_window",
title: "Одно окно",
detail:
"Попытку можно вести только в одном окне. Второе окно не сможет начать работу, пока первое открыто. После закрытия окна попытка освобождается сразу, а после потери связи - в течение двух минут.",
},
{
code: "watermark",
title: "Водяной знак на странице задания",
@@ -80,6 +97,12 @@ export const serverSignals: readonly DisclosedSignal[] = [
title: "Параллельные сессии",
detail: "Токен сессии не хранится, только односторонний ключевой отпечаток.",
},
{
code: "user_agent",
title: "Тип браузера (User-Agent)",
detail:
"Хранится только односторонний ключевой отпечаток, привязанный к попытке. Смена браузера или устройства во время попытки - слабый сигнал.",
},
{
code: "answer_match",
title: "Совпадение ответов с ответами других кандидатов",
@@ -94,3 +117,9 @@ export const notCollected: readonly string[] = [
"Звук: микрофон не используется.",
"Содержимое буфера обмена и вводимый текст: отправляется только размер вставки.",
];
/** What the measures and signals do not do, stated plainly. */
export const limits: readonly string[] = [
"Снимок экрана и фото экрана телефоном предотвратить нельзя: страница видит лишь часть клавиш и не знает о камере. Водяной знак нужен только затем, чтобы по утечке можно было найти попытку.",
"Сигналы ведут к ручной проверке и апелляции, но не к автоматическому снижению оценки. Работодатель их не видит.",
];
@@ -41,3 +41,17 @@ export function clipboardEvent(
export function fullscreenExitEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "fullscreen_exit", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
/**
* A key or key combination that usually takes a screenshot, as the browser saw
* it. It is a weak hint: the browser does not see every screenshot, and the
* event carries no measurement.
*/
export function screenshotKeyEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "screenshot_key", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
/** The developer tools were probably opened. A heuristic, so it is a weak hint. */
export function devtoolsOpenEvent(itemId: string, atMs: number): AssessmentSignalEvent {
return { kind: "devtools_open", item_instance_id: itemId, occurred_at: timestamp(atMs) };
}
@@ -37,6 +37,52 @@ function start(overrides: { itemId?: string | null; offsetMs?: number } = {}) {
return { doc, win, send, timers, stop, clock };
}
describe("signal session developer tools watcher", () => {
function startWatching() {
const win = Object.assign(new EventTarget(), {
innerWidth: 1280,
innerHeight: 720,
outerWidth: 1280,
outerHeight: 820,
});
const send = vi.fn<SignalSender>(async () => undefined);
const timers: Array<() => void> = [];
const stop = startSignalSession({
environment: {
document: new FakeDocument(),
window: win,
now: () => Date.UTC(2026, 9, 8, 12, 0, 0),
} as CollectorEnvironment,
send,
newKey: () => "key",
schedule: (callback) => timers.push(callback),
cancel: () => undefined,
currentItemId: () => itemId,
watchDevtools: true,
});
return { win, send, timers, stop };
}
it("batches a developer tools event bound to the current item", async () => {
const { win, send, timers } = startWatching();
win.innerHeight = 380;
win.dispatchEvent(new Event("resize"));
// The watcher's own timer comes first, the batch timer after the event.
for (const timer of [...timers]) timer();
await Promise.resolve();
expect(send).toHaveBeenCalled();
const events = send.mock.calls.flatMap((call) => call[0].events);
expect(events).toEqual([
expect.objectContaining({ kind: "devtools_open", item_instance_id: itemId }),
]);
});
it("does not watch the window unless asked to", () => {
const { timers } = start();
expect(timers).toHaveLength(0);
});
});
describe("signal session life cycle", () => {
it("batches an event and sends it when the timer fires", async () => {
const { doc, send, timers } = start();
@@ -1,5 +1,7 @@
import { createSignalBatcher, type SignalBatcher, type SignalSender } from "./batcher";
import { attachSignalCollector, type CollectorEnvironment } from "./collector";
import { startDevtoolsWatcher } from "./devtools-heuristic";
import { devtoolsOpenEvent } from "./signal-events";
export type SignalSessionOptions = {
environment: CollectorEnvironment;
@@ -8,6 +10,11 @@ export type SignalSessionOptions = {
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
currentItemId: () => string | null;
/**
* Also watches the window size for open developer tools, on the timers above.
* Off by default: it needs a window that reports its sizes.
*/
watchDevtools?: boolean;
};
/**
@@ -30,8 +37,22 @@ export function startSignalSession(options: SignalSessionOptions): () => void {
onHidden: () => batcher.flush(),
onPageHide: () => batcher.flushOnExit(),
});
const stamp = options.environment.toServerTime ?? ((deviceMs: number) => deviceMs);
const stopDevtools = options.watchDevtools
? startDevtoolsWatcher({
window: options.environment.window,
now: options.environment.now,
schedule: options.schedule,
cancel: options.cancel,
onOpen: () => {
const itemId = options.currentItemId();
if (itemId) batcher.enqueue(devtoolsOpenEvent(itemId, stamp(options.environment.now())));
},
})
: () => undefined;
return () => {
detach();
stopDevtools();
batcher.dispose();
};
}
@@ -54,6 +54,7 @@ export function useAssessmentSignals({
schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),
cancel: (handle) => window.clearTimeout(handle as number),
currentItemId: () => itemRef.current,
watchDevtools: true,
});
}, [attemptId, enabled]);
}
@@ -4,8 +4,25 @@ import { knownSignalNoticeVersion } from "../model/notice-content";
import { SignalNoticeContent, SignalNoticeDialog, SignalNoticeSummary } from "./signal-notice";
describe("signal notice", () => {
it("is version 3, the text that describes the watermark", () => {
expect(knownSignalNoticeVersion).toBe(3);
it("is version 4, the text that adds the capture hints and the one-window rule", () => {
expect(knownSignalNoticeVersion).toBe(4);
});
it("lists the screenshot keys, the developer tools hint, the User-Agent digest, and the single window", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Клавиши снимка экрана");
expect(markup).toContain("сам снимок страница не видит и не блокирует");
expect(markup).toContain("Признаки открытых инструментов разработчика");
expect(markup).toContain("Тип браузера (User-Agent)");
expect(markup).toContain("Одно окно");
});
it("says plainly that a screenshot or a photo cannot be prevented and that signals never lower a grade by themselves", () => {
const markup = renderToStaticMarkup(<SignalNoticeContent headingLevel="h3" />);
expect(markup).toContain("Чего эти меры не делают");
expect(markup).toContain("Снимок экрана и фото экрана телефоном предотвратить нельзя");
expect(markup).toContain("не к автоматическому снижению оценки");
expect(markup).toContain("Работодатель их не видит");
});
it("lists every measure the page applies during a real attempt", () => {
@@ -3,6 +3,7 @@ import { Button } from "../../../shared/ui";
import {
attemptMeasures,
browserSignals,
limits,
notCollected,
serverSignals,
type DisclosedSignal,
@@ -42,6 +43,12 @@ export function SignalNoticeContent({ headingLevel }: ContentProps) {
<SignalList signals={attemptMeasures} />
<Heading>Что измеряет сервер</Heading>
<SignalList signals={serverSignals} />
<Heading>Чего эти меры не делают</Heading>
<ul>
{limits.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
<Heading>Что не собирается</Heading>
<ul>
{notCollected.map((item) => (
@@ -0,0 +1,5 @@
export { pageClientId } from "./model/page-client";
export { useWorkSession } from "./model/use-work-session";
export type { UseWorkSession } from "./model/use-work-session";
export { createWorkSession } from "./model/work-session";
export type { WorkSessionStatus } from "./model/work-session";
@@ -0,0 +1,7 @@
/**
* The identifier of this open page. A new one is made when the page loads and
* lives until it closes, so a reload is a new page and a second tab is another
* one. It is random, 36 characters of `A-Za-z0-9-`, and the server keeps only a
* keyed digest of it bound to the attempt.
*/
export const pageClientId: string = crypto.randomUUID();
@@ -0,0 +1,86 @@
import { useCallback, useEffect, useRef, useState } from "react";
import {
holdMyAssessmentWorkSession,
releaseMyAssessmentWorkSession,
} from "../../../shared/api/endpoints/assessment/assessment";
import { pageClientId } from "./page-client";
import {
createWorkSession,
type AcquireResult,
type WorkSession,
type WorkSessionStatus,
} from "./work-session";
export type UseWorkSessionOptions = {
attemptId: string;
csrfToken: string;
/** True for a real attempt, the only kind that has a protected work session. */
enabled: boolean;
};
export type UseWorkSession = {
status: WorkSessionStatus;
/** Holds the session for this page; `busy` means another page holds it. */
acquire: () => Promise<AcquireResult>;
release: () => void;
};
/**
* Keeps the work session of a real attempt for this page while it works, and
* gives it back when the page closes or leaves. A demonstration run has none.
*/
export function useWorkSession({
attemptId,
csrfToken,
enabled,
}: UseWorkSessionOptions): UseWorkSession {
const [status, setStatus] = useState<WorkSessionStatus>("idle");
const csrfRef = useRef(csrfToken);
const sessionRef = useRef<WorkSession | null>(null);
useEffect(() => {
csrfRef.current = csrfToken;
}, [csrfToken]);
useEffect(() => {
if (!enabled || !attemptId) return undefined;
const session = createWorkSession({
transport: {
hold: async () => {
const lease = await holdMyAssessmentWorkSession(
attemptId,
{ "X-Attempt-Client": pageClientId },
{ headers: { "X-CSRF-Token": csrfRef.current } },
);
return { renewAfterSeconds: lease.renew_after_seconds };
},
release: () =>
releaseMyAssessmentWorkSession(
attemptId,
{ "X-Attempt-Client": pageClientId },
{ headers: { "X-CSRF-Token": csrfRef.current }, keepalive: true },
),
},
schedule: (callback, delayMs) => window.setTimeout(callback, delayMs),
cancel: (handle) => window.clearTimeout(handle as number),
onStatus: setStatus,
});
sessionRef.current = session;
// A page that is closing or going to the back-forward cache frees the session
// at once, so the candidate can open the attempt in another window.
const onPageHide = () => session.release();
window.addEventListener("pagehide", onPageHide);
return () => {
window.removeEventListener("pagehide", onPageHide);
session.release();
sessionRef.current = null;
};
}, [attemptId, enabled]);
const acquire = useCallback(async (): Promise<AcquireResult> => {
const session = sessionRef.current;
return session ? session.acquire() : "held";
}, []);
const release = useCallback(() => sessionRef.current?.release(), []);
return { status, acquire, release };
}
@@ -0,0 +1,135 @@
import { describe, expect, it, vi } from "vitest";
import { ApiRequestError } from "../../../shared/api";
import {
createWorkSession,
type WorkSessionStatus,
type WorkSessionTransport,
} from "./work-session";
const conflict = () =>
new ApiRequestError({ status: 409, code: "state_conflict", title: "Conflict" });
const unavailable = () =>
new ApiRequestError({ status: 0, code: "network_error", title: "Offline" });
function setup(hold: WorkSessionTransport["hold"]) {
const statuses: WorkSessionStatus[] = [];
const timers: Array<{ callback: () => void; delayMs: number; id: number }> = [];
const cancelled: number[] = [];
const release = vi.fn<WorkSessionTransport["release"]>(async () => undefined);
const session = createWorkSession({
transport: { hold: vi.fn(hold), release },
schedule: (callback, delayMs) => {
const id = timers.length + 1;
timers.push({ callback, delayMs, id });
return id;
},
cancel: (handle) => cancelled.push(handle as number),
onStatus: (status) => statuses.push(status),
});
return { session, statuses, timers, cancelled, release };
}
const lease = { renewAfterSeconds: 15 };
describe("work session of a real attempt", () => {
it("holds the session, renews it on the server's cadence, and releases it on leaving", async () => {
const { session, statuses, timers, release } = setup(async () => lease);
await expect(session.acquire()).resolves.toBe("held");
expect(statuses).toEqual(["held"]);
expect(timers.at(-1)?.delayMs).toBe(15_000);
timers.at(-1)?.callback();
await Promise.resolve();
await Promise.resolve();
// A renewal arms the next one and changes no status.
expect(timers).toHaveLength(2);
expect(statuses).toEqual(["held"]);
session.release();
expect(release).toHaveBeenCalledTimes(1);
expect(statuses).toEqual(["held", "idle"]);
});
it("says busy when another page holds the session, and holds nothing", async () => {
const { session, statuses, timers, release } = setup(async () => {
throw conflict();
});
await expect(session.acquire()).resolves.toBe("busy");
expect(statuses).toEqual(["busy"]);
expect(timers).toHaveLength(0);
session.release();
// A page that never held the session has nothing to release.
expect(release).not.toHaveBeenCalled();
});
it("is lost when another page takes the session over at a renewal", async () => {
let refuse = false;
const { session, statuses, timers, cancelled } = setup(async () => {
if (refuse) throw conflict();
return lease;
});
await session.acquire();
refuse = true;
timers.at(-1)?.callback();
await Promise.resolve();
await Promise.resolve();
expect(statuses).toEqual(["held", "lost"]);
// It stops renewing a session it no longer has.
expect(timers).toHaveLength(1);
expect(cancelled).toHaveLength(1);
});
it("keeps trying through a network gap instead of giving the session up", async () => {
let offline = false;
const { session, statuses, timers } = setup(async () => {
if (offline) throw unavailable();
return lease;
});
await session.acquire();
offline = true;
timers.at(-1)?.callback();
await Promise.resolve();
await Promise.resolve();
expect(statuses).toEqual(["held"]);
expect(timers).toHaveLength(2);
expect(timers.at(-1)?.delayMs).toBe(5_000);
});
it("reports a failed start as an error without holding anything", async () => {
const { session, statuses, timers } = setup(async () => {
throw unavailable();
});
await expect(session.acquire()).resolves.toBe("error");
expect(statuses).toEqual([]);
expect(timers).toHaveLength(0);
});
it("keeps the renewal cadence within sane bounds", async () => {
const fast = setup(async () => ({ renewAfterSeconds: 1 }));
await fast.session.acquire();
expect(fast.timers.at(-1)?.delayMs).toBe(5_000);
const slow = setup(async () => ({ renewAfterSeconds: 3600 }));
await slow.session.acquire();
expect(slow.timers.at(-1)?.delayMs).toBe(60_000);
});
it("ignores a renewal that finishes after the page released the session", async () => {
const pending: { finish: (() => void) | null } = { finish: null };
let calls = 0;
const { session, statuses, timers } = setup(() => {
calls += 1;
if (calls === 1) return Promise.resolve(lease);
return new Promise((resolve) => {
pending.finish = () => resolve(lease);
});
});
await session.acquire();
timers.at(-1)?.callback();
session.release();
pending.finish?.();
await Promise.resolve();
await Promise.resolve();
expect(statuses).toEqual(["held", "idle"]);
expect(timers).toHaveLength(1);
});
});
@@ -0,0 +1,123 @@
import { ApiRequestError } from "../../../shared/api";
/** What the page knows about the single work session of the attempt. */
export type WorkSessionStatus =
/** Not holding it: before the work starts, and after a release. */
| "idle"
/** This page holds it. */
| "held"
/** Another open page holds it, so this page cannot work on the attempt. */
| "busy"
/** This page held it and another page took it over. */
| "lost";
export type AcquireResult = "held" | "busy" | "error";
export type WorkSessionTransport = {
/** Holds or renews the session and returns how often to renew it. */
hold: () => Promise<{ renewAfterSeconds: number }>;
/** Releases it. A page that closes uses a keepalive request. */
release: () => Promise<void>;
};
export type WorkSessionOptions = {
transport: WorkSessionTransport;
schedule: (callback: () => void, delayMs: number) => unknown;
cancel: (handle: unknown) => void;
onStatus: (status: WorkSessionStatus) => void;
};
export type WorkSession = {
/** Takes the session for this page and keeps it. Resolves `busy` when another page holds it. */
acquire: () => Promise<AcquireResult>;
/** Frees the session now, for a page that is closing or leaving the attempt. */
release: () => void;
};
const minRenewMs = 5_000;
const maxRenewMs = 60_000;
function isConflict(error: unknown): boolean {
return error instanceof ApiRequestError && error.status === 409;
}
/**
* Holds the one-page-at-a-time work session of a real attempt: the first call
* asks for it, a timer repeats the hold while this page works, and a release
* frees it when the page closes. A refusal at the start is `busy`; a refusal at a
* renewal means that another page took the session over, which is `lost`. A
* renewal that fails for any other reason is tried again at the next tick, so a
* short network gap does not end the work.
*/
export function createWorkSession(options: WorkSessionOptions): WorkSession {
let status: WorkSessionStatus = "idle";
let timer: unknown = null;
let generation = 0;
function setStatus(next: WorkSessionStatus): void {
if (status === next) return;
status = next;
options.onStatus(next);
}
function stopTimer(): void {
if (timer !== null) options.cancel(timer);
timer = null;
}
function renewDelay(renewAfterSeconds: number): number {
return Math.min(Math.max(renewAfterSeconds * 1000, minRenewMs), maxRenewMs);
}
function scheduleRenewal(delayMs: number, owner: number): void {
timer = options.schedule(() => void renew(owner), delayMs);
}
async function renew(owner: number): Promise<void> {
if (owner !== generation || status !== "held") return;
try {
const hold = await options.transport.hold();
if (owner !== generation) return;
scheduleRenewal(renewDelay(hold.renewAfterSeconds), owner);
} catch (error: unknown) {
if (owner !== generation) return;
if (isConflict(error)) {
stopTimer();
setStatus("lost");
return;
}
scheduleRenewal(minRenewMs, owner);
}
}
return {
async acquire(): Promise<AcquireResult> {
generation += 1;
const owner = generation;
stopTimer();
try {
const hold = await options.transport.hold();
if (owner !== generation) return "error";
setStatus("held");
scheduleRenewal(renewDelay(hold.renewAfterSeconds), owner);
return "held";
} catch (error: unknown) {
if (owner !== generation) return "error";
if (isConflict(error)) {
setStatus("busy");
return "busy";
}
setStatus("idle");
return "error";
}
},
release(): void {
generation += 1;
stopTimer();
if (status === "held") {
void options.transport.release().catch(() => undefined);
}
setStatus("idle");
},
};
}
@@ -64,6 +64,7 @@ import {
useAssessmentSignals,
useSignalNoticeGate,
} from "../../../features/assessment-signals";
import { pageClientId, useWorkSession } from "../../../features/assessment-work-session";
import { WatermarkedText, WatermarkTile } from "../../../features/assessment-watermark";
import { forgetExpressStart } from "../model/express-start";
import { AttemptFocusBar, type AnswerSaveState } from "./attempt-focus-bar";
@@ -165,6 +166,14 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
applies: Boolean(attempt && collectsSignals && !isTerminal(attempt)),
running: workReady,
});
// One open page per real attempt: this page asks for the work session before it
// starts, keeps it while it works, and learns when another window took it over.
const workSession = useWorkSession({
attemptId,
csrfToken: actor?.csrf_token ?? "",
enabled: actorReady && collectsSignals,
});
const [openElsewhere, setOpenElsewhere] = useState(false);
const [resumeBusy, setResumeBusy] = useState(false);
const [pendingResume, setPendingResume] = useState<{ key: string; version: number } | null>(null);
const [pendingAnswer, setPendingAnswer] = useState<PendingAnswerCommand | null>(null);
@@ -230,6 +239,18 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
resultQuery.isError,
]);
// Another window took the work session over: stop here and say why.
const workSessionLost = workSession.status === "lost";
const leaveFullscreen = lockdown.leave;
useEffect(() => {
if (!workSessionLost) return;
queueMicrotask(() => {
setWorkReady(false);
setOpenElsewhere(true);
leaveFullscreen();
});
}, [workSessionLost, leaveFullscreen]);
// A finished or expired express run cannot be resumed; its start key goes.
const expressFinishedId =
attempt && attempt.kind === "demo_express" && isTerminal(attempt) ? attempt.id : null;
@@ -278,11 +299,19 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
requestInFlight.current = true;
setResumeBusy(true);
setPageError(null);
setOpenElsewhere(false);
try {
if (collectsSignals && (await workSession.acquire()) === "busy") {
// The other window keeps the attempt: nothing was started here.
setPendingResume(null);
setOpenElsewhere(true);
lockdown.leave();
return;
}
const resumedResponse = await startMyAssessmentAttemptSession(
attempt.id,
{ expected_version: command.version },
{ "Idempotency-Key": command.key },
{ "Idempotency-Key": command.key, "X-Attempt-Client": pageClientId },
{ headers: { "X-CSRF-Token": actor.csrf_token } },
);
const resumed = parseAssessmentAttemptResponse(resumedResponse);
@@ -301,6 +330,11 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
} else if (isAccessLoss(error)) {
removeAssessmentQueries(queryClient);
setAccessDenied(true);
} else if (error instanceof ApiRequestError && error.status === 409) {
// Another window took the work session between the hold and the start.
setPendingResume(null);
setOpenElsewhere(true);
lockdown.leave();
} else if (isOutcomeAmbiguous(error)) {
setPageError("Не удалось подтвердить продолжение. Повторите запрос с тем же ключом.");
} else {
@@ -358,6 +392,7 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
command,
currentAttemptId,
currentActor.csrf_token,
pageClientId,
);
if (!isCurrentAssessmentSession(queryClient, currentActor)) return;
if (outcome.kind === "retry") {
@@ -630,6 +665,18 @@ function AssessmentAttemptContent({ attemptId }: { attemptId: string }) {
</div>
) : null}
{openElsewhere && !terminal ? (
<div role="alert">
<Notice tone="danger" title="Попытка открыта в другом окне">
<p className={attemptStyles["notice-text"]}>
Работать над попыткой можно только в одном окне. Закройте ее в другом окне или
вкладке и нажмите «Начать или продолжить» здесь. Если то окно уже закрыто или
браузер завершился, подождите до двух минут и повторите.
</p>
</Notice>
</div>
) : null}
{!workReady && !terminal ? (
<Card tone="raised" className={attemptStyles.resume}>
<p>
@@ -36,6 +36,7 @@ import type {
AssessmentSignalNotice,
AssessmentSignalReceipt,
AssessmentUncertainty,
AssessmentWorkSession,
BasicScore,
ChoiceItemContent,
ConfigurationItemContent,
@@ -150,6 +151,8 @@ export const getStartMyAssessmentAttemptSessionResponseMock = (): AssessmentAtte
export const getRecordMyAssessmentAttemptSignalsResponseMock = (overrideResponse: Partial<Extract<AssessmentSignalReceipt, object>> = {}): AssessmentSignalReceipt => ({status: faker.helpers.arrayElement(['accepted','saturated'] as const), accepted_events: faker.number.int({min: 0, max: 50}), received_at: faker.date.past().toISOString().slice(0, 19) + 'Z', ...overrideResponse})
export const getHoldMyAssessmentWorkSessionResponseMock = (overrideResponse: Partial<Extract<AssessmentWorkSession, object>> = {}): AssessmentWorkSession => ({held_until: faker.date.past().toISOString().slice(0, 19) + 'Z', renew_after_seconds: faker.number.int({min: 1, max: 3600}), ...overrideResponse})
export const getSubmitMyAssessmentAnswerResponseAssessmentSessionsMock = (overrideResponse: Partial<AssessmentSessions> = {}): AssessmentSessions => ({...{used: faker.number.int({min: 1, max: 10}), max: faker.number.int({min: 1, max: 10}), idle_timeout_seconds: faker.number.int({min: 60, max: 86400})}, ...overrideResponse});
export const getSubmitMyAssessmentAnswerResponseChoiceItemContentMock = (overrideResponse: Partial<ChoiceItemContent> = {}): ChoiceItemContent => ({...{format: faker.helpers.arrayElement(['choice'] as const), options: Array.from({ length: faker.number.int({min: 2, max: 10}) }, (_, i) => i + 1).map(() => ({id: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 32}), text: faker.string.alpha({length: {min: 1, max: 2000}})})), multiple: faker.datatype.boolean()}, ...overrideResponse});
@@ -315,6 +318,28 @@ export const getRecordMyAssessmentAttemptSignalsMockHandler = (overrideResponse?
}, options)
}
export const getHoldMyAssessmentWorkSessionMockHandler = (overrideResponse?: AssessmentWorkSession | ((info: Parameters<Parameters<typeof http.put>[1]>[0]) => Promise<AssessmentWorkSession> | AssessmentWorkSession), options?: RequestHandlerOptions) => {
return http.put('*/api/v1/me/assessment-attempts/:attemptId/work-session', async (info: Parameters<Parameters<typeof http.put>[1]>[0]) => {
return HttpResponse.json(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getHoldMyAssessmentWorkSessionResponseMock(),
{ status: 200
})
}, options)
}
export const getReleaseMyAssessmentWorkSessionMockHandler = (overrideResponse?: void | ((info: Parameters<Parameters<typeof http.delete>[1]>[0]) => Promise<void> | void), options?: RequestHandlerOptions) => {
return http.delete('*/api/v1/me/assessment-attempts/:attemptId/work-session', async (info: Parameters<Parameters<typeof http.delete>[1]>[0]) => {
if (typeof overrideResponse === 'function') {await overrideResponse(info); }
return new HttpResponse(null,
{ status: 204
})
}, options)
}
export const getSubmitMyAssessmentAnswerMockHandler = (overrideResponse?: AssessmentAttempt | ((info: Parameters<Parameters<typeof http.post>[1]>[0]) => Promise<AssessmentAttempt> | AssessmentAttempt), options?: RequestHandlerOptions) => {
return http.post('*/api/v1/me/assessment-attempts/:attemptId/answers', async (info: Parameters<Parameters<typeof http.post>[1]>[0]) => {
@@ -359,6 +384,8 @@ export const getAssessmentMock = () => [
getGetMyAssessmentAttemptMockHandler(),
getStartMyAssessmentAttemptSessionMockHandler(),
getRecordMyAssessmentAttemptSignalsMockHandler(),
getHoldMyAssessmentWorkSessionMockHandler(),
getReleaseMyAssessmentWorkSessionMockHandler(),
getSubmitMyAssessmentAnswerMockHandler(),
getFinalizeMyAssessmentAttemptMockHandler(),
getGetMyAssessmentResultMockHandler()
@@ -37,11 +37,14 @@ import type {
AssessmentSignalNotice,
AssessmentSignalNoticeAcknowledgement,
AssessmentSignalReceipt,
AssessmentWorkSession,
CreateMyAssessmentAttemptHeaders,
FinalizeMyAssessmentAttemptHeaders,
HoldMyAssessmentWorkSessionHeaders,
ListMyAssessmentResultsParams,
Problem,
RecordMyAssessmentAttemptSignalsHeaders,
ReleaseMyAssessmentWorkSessionHeaders,
StartMyAssessmentAttemptSessionHeaders,
SubmitMyAssessmentAnswerHeaders
} from '../../schemas';
@@ -700,6 +703,8 @@ export const getStartMyAssessmentAttemptSessionUrl = (attemptId: string,) => {
*
* If the attempt deadline or session budget has passed, this command commits the due terminal transition and returns the resulting attempt. A pending practice submitted before the limit is graded first. `GetMyAssessmentAttempt` and `GetMyAssessmentResult` remain read-only: they never start a session or commit a due transition. A background transition may persist a due outcome independently; after that, this command returns the stored terminal attempt without changing it.
*
* One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and changes nothing; the client tells the candidate that the attempt is open in another window. That refusal is not stored under the Idempotency-Key, because it lasts only until the other page closes or stops renewing. A real attempt that nobody holds is not refused.
*
* The attempt must belong to the candidate of the session. An attempt of another candidate answers 404 not_found, the same as an unknown identifier. An employer account answers 403 forbidden; no operation gives an employer answers, qualification evidence, or attempt history.
* @summary Start or resume a work session for the current candidate's attempt.
*/
@@ -875,6 +880,194 @@ export const useRecordMyAssessmentAttemptSignals = <TError = ErrorType<Problem>,
> => {
return useMutation(getRecordMyAssessmentAttemptSignalsMutationOptions(options), queryClient);
}
export const getHoldMyAssessmentWorkSessionUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/work-session`
}
/**
* Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. A real attempt (`root` or `corrective`) allows one open page at a time. The page that works on the attempt calls this operation when the candidate starts or resumes work and then repeats it every `renew_after_seconds`; each call holds the work session until `held_until`.
*
* - If nobody holds the work session, the previous holder released it, or its hold expired, the page becomes the holder and the answer is 200.
* - If the same page holds it, the hold is renewed and the answer is 200.
* - If another page holds it, the answer is 409 `state_conflict` and nothing changes: the second page is refused until the first one releases the session (ReleaseMyAssessmentWorkSession) or stops renewing and its hold expires. The client tells the candidate that the attempt is open in another window and does not show the task.
*
* The same 409 answers a terminal or expired attempt and a `demo_express` attempt, which has no protected work session. The hold is a one-page-at-a-time rule, not a lock on the candidate: a candidate who closes a page, reloads, or opens the attempt on another device can continue when the hold is released or has expired (at most two minutes after the last renewal). It is not a security boundary: a client that never calls this operation is refused only while another page holds the session. The server stores one-way keyed digests of the page identifier and of the User-Agent, bound to the attempt; it never stores or returns either value. A change of the User-Agent digest during an attempt is a weak server signal for a manual review, never an automatic decision.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the hold (409 state_conflict).
* @summary Hold the single active work session of a real assessment attempt for this page.
*/
export const holdMyAssessmentWorkSession = async (attemptId: string,
headers: HoldMyAssessmentWorkSessionHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<AssessmentWorkSession> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<AssessmentWorkSession>(getHoldMyAssessmentWorkSessionUrl(attemptId),
{
...options,
method: 'PUT',
headers: { ...headers, ...getHeaders(options?.headers) }
}
);}
export const getHoldMyAssessmentWorkSessionMutationKey = () => ['holdMyAssessmentWorkSession'] as const;
export const getHoldMyAssessmentWorkSessionMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, TError,HoldMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, TError,HoldMyAssessmentWorkSessionMutationVariables, TContext> => {
const mutationKey = getHoldMyAssessmentWorkSessionMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, HoldMyAssessmentWorkSessionMutationVariables> = (props) => {
const {attemptId,headers} = props ?? {};
return holdMyAssessmentWorkSession(attemptId,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type HoldMyAssessmentWorkSessionMutationResult = NonNullable<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>>
export type HoldMyAssessmentWorkSessionMutationError = ErrorType<Problem>
export type HoldMyAssessmentWorkSessionMutationVariables = {attemptId: string;headers: HoldMyAssessmentWorkSessionHeaders}
/**
* @summary Hold the single active work session of a real assessment attempt for this page.
*/
export const useHoldMyAssessmentWorkSession = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>, TError,HoldMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof holdMyAssessmentWorkSession>>,
TError,
HoldMyAssessmentWorkSessionMutationVariables,
TContext
> => {
return useMutation(getHoldMyAssessmentWorkSessionMutationOptions(options), queryClient);
}
export const getReleaseMyAssessmentWorkSessionUrl = (attemptId: string,) => {
return `/api/v1/me/assessment-attempts/${attemptId}/work-session`
}
/**
* Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and the `X-Attempt-Client` header of the page. The page calls it when it closes, so that the candidate can open the attempt in another window at once instead of waiting for the hold to expire. The request is idempotent and reveals nothing: it answers 204 whether this page held the session, another page holds it (which stays held), nobody held it, or the attempt is not held at all, and a repeat after a lost response succeeds. A page that is killed without calling it loses the hold within two minutes.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden), the attempt (404 not_found for an unknown attempt or one of another candidate), then the release (204).
* @summary Release the work session that this page holds.
*/
export const releaseMyAssessmentWorkSession = async (attemptId: string,
headers: ReleaseMyAssessmentWorkSessionHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<void> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<void>(getReleaseMyAssessmentWorkSessionUrl(attemptId),
{
...options,
method: 'DELETE',
headers: { ...headers, ...getHeaders(options?.headers) }
}
);}
export const getReleaseMyAssessmentWorkSessionMutationKey = () => ['releaseMyAssessmentWorkSession'] as const;
export const getReleaseMyAssessmentWorkSessionMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, TError,ReleaseMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, TError,ReleaseMyAssessmentWorkSessionMutationVariables, TContext> => {
const mutationKey = getReleaseMyAssessmentWorkSessionMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, ReleaseMyAssessmentWorkSessionMutationVariables> = (props) => {
const {attemptId,headers} = props ?? {};
return releaseMyAssessmentWorkSession(attemptId,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type ReleaseMyAssessmentWorkSessionMutationResult = NonNullable<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>>
export type ReleaseMyAssessmentWorkSessionMutationError = ErrorType<Problem>
export type ReleaseMyAssessmentWorkSessionMutationVariables = {attemptId: string;headers: ReleaseMyAssessmentWorkSessionHeaders}
/**
* @summary Release the work session that this page holds.
*/
export const useReleaseMyAssessmentWorkSession = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>, TError,ReleaseMyAssessmentWorkSessionMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof releaseMyAssessmentWorkSession>>,
TError,
ReleaseMyAssessmentWorkSessionMutationVariables,
TContext
> => {
return useMutation(getReleaseMyAssessmentWorkSessionMutationOptions(options), queryClient);
}
export const getSubmitMyAssessmentAnswerUrl = (attemptId: string,) => {
@@ -892,6 +1085,8 @@ export const useRecordMyAssessmentAttemptSignals = <TError = ErrorType<Problem>,
*
* Practice: an answer with format `practice` submits the solution of the main or the additional practice. It is stored, and the sandbox runs it asynchronously against the hidden check groups; the response shows the practice `pending`, and the client polls GetMyAssessmentAttempt for the verdict. Only the score 0-3 and the pass state of each group are shown, never the checks, error output, or seeds. Every outcome caused by the solution, such as a compilation error, a crash, or a time or memory limit, is a `finished` verdict. A `failed` verdict means only that the sandbox infrastructure could not run it; it consumes nothing. After `finished` the practice accepts no other solution, so hidden group results cannot be used to tune it. Debug runs of the candidate's own tests and the public examples are unlimited apart from the sandbox rate limit and never show hidden group results; they are planned as a separate operation.
*
* One page at a time. While another page holds the work session of this attempt (HoldMyAssessmentWorkSession), a request from a different `X-Attempt-Client`, or from none, answers 409 `state_conflict` and stores nothing, so a second window cannot answer. That refusal is not stored under the Idempotency-Key and is checked before the stored answer is replayed.
*
* Repeats and conflicts, per item:
* - A retry with the same Idempotency-Key and body within 24 hours replays the stored response.
* - Sending the answer already stored for the item again, even with a new key or an older `expected_version`, stores nothing, keeps the version, and answers 200 with the current attempt. Each answer format defines equality: sets for `option_ids` and `line_numbers`, the exact sequence for `element_ids`, numeric equality for `number`, identical text without normalization for `text` and `config`, and the same language with identical source for a practice.
@@ -0,0 +1,16 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import * as zod from 'zod';
export const AssessmentCaptureSignal = zod.object({
"kind": zod.enum(['screenshot_key', 'devtools_open']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.')
export type AssessmentCaptureSignal = zod.input<typeof AssessmentCaptureSignal>;
export type AssessmentCaptureSignalOutput = zod.output<typeof AssessmentCaptureSignal>;
@@ -29,7 +29,11 @@ export const AssessmentSignalBatch = zod.object({
"kind": zod.enum(['fullscreen_exit']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
})]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(assessmentSignalBatchEventsMax)
}),zod.object({
"kind": zod.enum(['screenshot_key', 'devtools_open']),
"item_instance_id": zod.uuid().describe('Identifier of an item instance in one attempt. It identifies the fixed variant served to this candidate and reveals neither the task family, its version, nor the variant seed.'),
"occurred_at": zod.iso.datetime({"offset":true}).describe('UTC instant in RFC 3339 format with the Z suffix, for example 2026-10-05T09:30:00Z. Servers always emit UTC. Every date-time field in this contract uses this schema.')
}).describe('A hint that the screen may be captured or inspected. `screenshot_key` is a key or key combination that the browser saw and that usually takes a screenshot (PrintScreen, Cmd+Shift+3, 4, or 5 on macOS, Win+Shift+S); `devtools_open` is the result of a heuristic that guesses that the developer tools are open (a docked panel changes the window size, or the console reads an object). Both are weak: a browser does not see every screenshot, an operating system can take one without a key the page sees, a phone photo is invisible to the page, and the heuristic gives false positives. They lead to attention in a manual review at most, never to a score change, and they carry no measurement.')]).describe('One client-reported event bound to an item instance of the attempt. The timestamp is untrusted input and is used only as event metadata; server receipt time is authoritative for limits and retention.')).min(1).max(assessmentSignalBatchEventsMax)
}).describe('A bounded batch of client event metadata. The raw request body is limited to 32 KiB before decoding and the batch contains at most 50 events.')
export type AssessmentSignalBatch = zod.input<typeof AssessmentSignalBatch>;
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more